Archive for June 24, 2011

Simple Javascript MVC (2)

The previous version of the code just showed some “proof of concept” about using pub/sub to implement MVC in javascript. The AmplifyJS framework was used for its Pub/Sub implementation.
To make what is going on a little bit clearer I isolated the pub/sub code into an Observer object. I also formalised the MVC triad into the Model, View and Controller objects.
View decorates the Observer object with some view specific functionanlity, while Controller and Model are still mere Observers.
Next step: maybe try and use the Command pattern.

Observer:

/* requires AmplifyJS */

Observer = function (aEventsToPublish, aEventsToSubscribeTo){
var pubsub = amplify;
var events = [];

obj = function(){ };
obj.prototype.addEvent = function(sEvent){events[sEvent]=true};
obj.prototype.removeEvent = function(sEvent){if(events[sEvent]) delete events[sEvent]};
obj.prototype.publish = function(sEvent,oData){

if(events[sEvent]){

pubsub.publish(sEvent, oData);
}
};

obj.prototype.init = function(aEventsToPublish, aEventsToSubscribeTo){
if(aEventsToPublish)
{
for(var i=0; i<aEventsToPublish.length;i++)
{
this.addEvent(aEventsToPublish[i]);
}
}
if(aEventsToSubscribeTo)
{
for(i=0; i<aEventsToSubscribeTo.length;i++)
{
pubsub.subscribe(aEventsToSubscribeTo[i].event, aEventsToSubscribeTo[i].handler);

}

}
}
obj.prototype.init(aEventsToPublish, aEventsToSubscribeTo);
return obj;

};

View:

/* requires AmplifyJS */

View = function (aTriggers, aEventsToPublish, aEventsToSubscribeTo){

var view = new Observer( aEventsToPublish, aEventsToSubscribeTo);

view.init = function (aTriggers,aEventsToPublish, aEventsToSubscribeTo ){
view.prototype.init(aEventsToPublish, aEventsToSubscribeTo);

//peform view specific initialisation.
var i=0;
if(aTriggers)
{
for(i=0; i<aTriggers.length;i++)
{
eval('this[aTriggers['+i+']['+0+']]' +'=function(){view.prototype.publish("'+aTriggers[i][1]+'")}');
}
}
}
view.init(aTriggers,aEventsToPublish, aEventsToSubscribeTo);
return view;
};

Find the remainder of the code here

Follow

Get every new post delivered to your Inbox.