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

dynamic, invoke, javascript, object, onclick

Solution

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();
}

Problem

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.

Original source