I’m creating an app using JQuery (Mobile) and I’m facing a problem with the structure of JQuery events. I defined a dummy “class” like this:
MyClass = function()
{
this.property = initvalue;
this.foo = function()
{
alert("That's my property = " + this.property);
}
}
Then I defined an object based on MyClass:
var obj1 = new MyClass();
The problem comes when I use obj1.foo() as a callback function to be informed on an event, for example:
$(element).click(obj1.foo);
or
$(element).load(URL, obj1.foo);
When foo() is executed, “this” refers to the element, not to the object “obj1”, and of course I can’t access the object’s “property” with a self reference. How can I fix it?
You can use jQUery’s
proxymethod:This will assign the
obj1context to your method.