I come from a Prototype JS background where OO Javascript is encouraged through the use of Class.create()
. Now I am doing some JQuery work and I am trying to write some properly structured JQuery code where I can, for example, call the same object function from two different click event handlers.
Here is the code in Prototype:
document.observe("dom:loaded", function() {
// create document
APP.pageHelper = new APP.PageHelper();
});
// namespace our code
window.APP = {};
// my class
APP.PageHelper = Class.create({
// automatically called
initialize: function(name, sound) {
this.myValue = "Foo";
// attach event handlers, binding to 'this' object
$("myButton").observe("click", this.displayMessage.bind(this))
},
displayMessage: function() {
console.log("My value: " + this.myValue); // 'this' is the object not the clicked button!
}
});
I am wondering how the following code can be replicated in JQuery where there is no way to bind a function call to the object it is called in, and 'this' is always the element clicked.
I have heard of a way to do it the Douglas Crockford 'module' pattern (http://www.yuiblog.com/blog/2007/06/12/module-pattern/) but I would love if someone could show me how you would implement the code above using JQuery and that pattern.
Thanks in advance.
You can absolutely bind an event to something other then the dom element. Just use $.proxy
.
Takes a function and returns a new one that will always have a particular context. version added: 1.4
/**
* @param function - The function whose context will be changed.
* @param context - The object to which the context (this) of the function should be set.
*/
jQuery.proxy( function, context )
This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function if passed the original.