The following code doesn’t work as I intuitively expect it to:
function MyObject(input) {
input.change(this._foo);
this.X = undefined;
}
MyObject.prototype._foo = function() {
alert("This code is never called");
// but if it did
this.X = true;
}
var test_input = $("input#xyz"); // a random, existing input
var m = MyObject(test_input); // attach handler (or try to)
test_input.change(); // trigger event
alert(m.X); // undefined
I’d expect that _foo() would be called (and, if that ever happens, that the this variable in _foo() would be an instantiation of MyObject.
Does anyone know why this doesn’t work, and of any alternative pattern for passing an object to an event handler?
Thank you for reading.
Brian
As Kenny points out you’re missing the
new. You also need to make sure thatthisin_foorefers to theMyObjectinstanceOne way to do it:-
P.S
You can’t avoid using the new operator by leaving it out! 🙂