I am working on a website where various objects bind to common events on $(window). However, I want to run these functions within the context of the objects that receive the triggers. (In other words, preserve “this” so it still refers to the object instead of the window when it calls the function.) How can I do this? For example, inside the object:
var someNum = 1;
$(window).bind("test", printNum);
function printNum() {
alert(this.someNum); // should return 1
}
Check out
$.proxy, which you can use to create a function that always has a particular context:Also,
onis preferred overbindas of jQuery 1.7.