Monday, May 26, 2008

Meta classes and jQuery

I am currently experimenting with making Joose the perfect match to everyones favorite JavaScript library jQuery.
One result is basic Widget class that makes it possible to link a Joose class to a jQuery selector:
Class("Button", {
isa: Widget,

has: {
message: {
init: "hello world"
}
},

events: {
click: function () {
alert(this.message)
},
dblclick: function () {
alert("please only click once :)")
}
}
})

You can now instantiate buttons like this:
var buttons = new Button(".button")



Only for the interested here is the source code of the meta class WidgetMetaclass and the abstract class Widget:

/* Meta class for widgets */
Class("WidgetMetaclass", {
isa: Joose.Class,

has: {
events: {
is: "rw",
init: function () { return {} }
}
},

override: {

// make events from declaration available as instance var of the meta class
builders: function () {
var orig = this.SUPER();
return Joose.O.extend({
events: function (events) {
this.setEvents(events)
}
}, orig)
}
}
})

Class("Widget", {
meta: WidgetMetaclass,
isAbstract: true,
has: {
"$": {}, // the jQuery objects
selector: {
is: "rw"
}
},

methods: {
initialize: function () {

var j;
if(arguments.length > 0) {
j = jQuery.apply(jQuery, arguments);
}
else {
j = this.getSelector()
}
this.$ = j;

var me = this
var meta = this.meta;
var events = meta.getEvents();
// put my events into my jQuery object
Joose.O.each(events, function (func, name) {
var bound = function () { func.apply(me, arguments) }
var obj = me;
me.$[name](bound)
})
}
}
})
Post a Comment