I want to be able to pass one object to another, then set up events that execute different methods from the initial object.
var TEST = {};
//User-created object
TEST.testObj = function () { this.initialize.apply(this, arguments); };
TEST.testObj.prototype = {
initialize: function(a) {
this.a = a;
},
sayHi: function() {
alert(a);
}
}
//Menu accosiated with that class of objects
TEST.testMenu = function () { this.initialize.apply(this, arguments); };
TEST.testMenu.prototype = {
initialize: function(obj) {
this.obj = obj;
var menuItem = document.createElement('div');
menuItem.innerHTML = 'Say Hi!';
menuItem.onclick = this.obj.sayHi;
document.body.appendChild(menuItem);
}
}
t1 = new TEST.testObj('Test Object');
menu = new TEST.testMenu(t1);
Activating the event by clicking the div alerts undefined. It looks like it’s calling the function sayHi, but a generic one not associated with an instantiated object.
Thanks!
You don’t have a sayHi() function declared in this code. Just add this line
after the
TEST.testObj.prototype...part. This will create a new function in TEST’s prototype chain that you can call inside the testMenu objectEDIT
The way you are binding the onclick event, this was referring to the div HTML element, not the object. This is the changed code that should work: