Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: calling object function/method from onclick event, with dynamic argument

I'm trying to do this:

<script>
var MyItem;

MyItem = new myobj('testobj');

function myobj(id)
{
     var _id = id;

     this.toggle = function()
     {
       ...
     }

     function draw()
     {
         document.body.innerHTML += "<a onclick='" + MyItem + ".toggle();'>link</a>";
     }

     draw();

}
</script>

I get "function is not defined", but can invoke MyItem.toggle() from console successfully. I've also tried:

document.body.innerHTML += "<a onclick='(function(){" + MyItem + ".toggle();})()'>link</a>";

The anchor has to be dynamically created in javascript. How do I invoke the MyItem object method toggle() from the dynamically created anchor?

ps, I'm typing js from memory, so if there are syntax errors I apologise.

like image 590
Dave Avatar asked Dec 11 '22 18:12

Dave


1 Answers

Do not add event handlers and elements like that. Use DOM methods

var anchor = document.createElement("a");
anchor.innerHTML = "link";
anchor.onclick = function(){ MyItem.toggle(); };
document.body.appendChild(anchor);

I actually think you are after something like this

var MyItem;

MyItem = new myobj('testobj');

function myobj(id) {
    var that = this;
    this.toggle = function () {
        alert(id);
    }
    function draw() {
        var anchor = document.createElement("a");
        anchor.innerHTML = "link";
        anchor.onclick = function () {
            that.toggle();
        };
        document.body.appendChild(anchor);
    }
    draw();
}
like image 76
epascarello Avatar answered Dec 28 '22 07:12

epascarello