Monday, May 23, 2011

simple keyword message selectors for javascript

As I have been messing with alternative object systems for php one of the ones I came up with was ab(using) the __invoke magic method to take a keyword argument list and find a given selector based upon it. I realized this could be done in an even more trivial manner in javascript using the object syntax and returning a new object w/ the dispatch mechanism rather than "return this".


var Klasses = {
'Person': {
'selectorPart1:selectorPart2': function(a, b) {
console.log('called with ' + a + ' and ' + b);
return obj(this);
},
'subSelector': function(a) {
console.log('subselector with:' + a + ' for ' + this.name);
return obj(this);
},
'get': function(field) {
console.log(this.name + ' over-ride of get with ' + field);
}
},
'*': {
'get': function(field) {
if(this[field]) {
return this[field]
} else {
throw new Exception('No field ' + field);
}
}
}
};

var obj = function(self) {
return function(selector) {
var sel = [];
var args = [];
$.each(selector, function(k, v) {
sel.push(k);
args.push(v);
});

var selectorName = sel.join(':');
var message = false;
if(Klasses[self.klass][selectorName]) {
message = Klasses[self.klass][selectorName];
}
else if(Klasses['*'][selectorName]) {
message = Klasses['*'][selectorName];
}

if(message) {
return message.apply(self, args);
}
};
}

var guy = obj({klass: 'Person', name: 'peter'});
guy({selectorPart1: 'apple', selectorPart2: 'candy'})
({subSelector: 'rotten'})

var otherGuy = obj({klass: 'Person', name: 'samuel'})({subSelector: 'cotton'})
console.log(otherGuy({get: 'name'}))


To see it live: jsfiddle running the above

No comments: