0

My JavaScript object create some HTML elements (two buttons for example) and after user click on these buttons I should call some method of this object. So the question is how I can refer JS object in HTML element to call its method?

<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
    <title>Title Goes Here</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        function myObj(){
            this.a = null;

            this.setA = function(a){
                this.a = a;
            }

            this.requestA = function(){
                $( "body" ).append($('<input><button onclick="referenceToMyObject.setA($(this).prev().val());">Set A</button>'));
            }
            return this;
        }

    </script>
</head> 
<body> 
    <script>
        var myObjInst = myObj();
        myObjInst.requestA();

    </script>
</body> 

2
  • Could you show the relevant part of your script and what you’ve tried? Commented Jul 7, 2018 at 20:53
  • @Aankhen I added the code Commented Jul 8, 2018 at 12:46

2 Answers 2

1

Creating the event handler inline (onclick="foo()") won’t allow you to reference the object, and is discouraged in any case because you should avoid evaluating strings as code. In addition, your code bypasses JavaScript’s idea of objects somewhat. You can reformulate it as follows:

function MyObj() {
  this.a = null;
}

MyObj.prototype.setA = function(a) {
  const old = this.a;

  this.a = a;

  console.log("Updated a from", old, "to", this.a);
};

MyObj.prototype.requestA = function() {
  const input = $("<input type='text'>");
  const button = $("<button>Set A</button>");

  button.click((e) => {
    this.setA($(e.target).prev().val());
  });

  const body = $("body");
  body.append(input);
  body.append(button);
};

$(document).ready(() => {
  const myObjInst = new MyObj();
  myObjInst.requestA();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Here, we use button.click to define the event handler and new MyObj() to instantiate the object. Apart from that, I cleaned up the code a bit and added a bit of logging so you can see what’s going on.

You could still define setA and requestA within the constructor, as you do in your example. I chose to define them on the prototype since their behaviour is the same across instances.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this and please let me know if this works for you. (working example in JSFiddle https://jsfiddle.net/galeroy/9nocztk4/1/)

<!doctype html>

<html>
    <head>
        <script>
            var myObject = {
                createButton: function(){
                                    var p = document.getElementById('par')
                                    var b = document.createElement('button');
                                    b.innerHTML = 'click me';
                                    b.setAttribute('onclick', 'myObject.myMethod()'); // this is the important part
                                    p.appendChild(b);                           
                },
                myMethod: function(){
                    alert("Button created by object, when clicked, calls another method in the same object")
                }
            }

            function init(){
                myObject.createButton();
            }
        </script>
    </head>

    <body onload="init()">
        <p id="par"></p>
    </body>
</html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.