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.
I roll my own objects based on this good article:
http://www.klauskomenda.com/code/javascript-programming-patterns/
I just choose whichever pattern makes sense for the project I'm working on. So like a quick example to do what you're asking would be:
$.myNamespace.myClass = function (options) {
this.settings = $.extend({ ... defaults ... }, options);
this.init();
};
$.myNamespace.myClass.prototype.settings = {
someValue: 'default',
someSelector: '#myButton'
};
$.myNamespace.myClass.prototype.init = function () {
var self = this;
$(self.settings.someSelector).click(function (event) {
console.log(self.settings.someValue);
});
};
You responded below that you knew about prototype but the syntax is a bit annoying. I think that's just a matter of being used to one syntax over another. I'm sure the Prototype library makes use of closures and .prototype just like I did above and like some other answers suggest below. In the end, just write syntax that you feel comfortable with. The suggestion to use Coffee Script is cool too - whatever floats your boat :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With