Simplest implementation:
function NewMessageBus() { return { when: function(name, fn) { this.fire[name] = fn; }, fire: {} }; } var msgBus = NewMessageBus(); Usage of this requires two things:
Creating the event
var presenter = (function() { msgBus.when('getContent', function() { model.load(view.content); }); }()); Note that the presenter is state-less.
Firing the event
var view = { getContent: function() { msgBus.fire.getContent(); }, content(htmlData) { $('#contentContainer').html(htmlData); } } var model = { load: function(cb) { $.ajax({ type: 'GET', url: 'myContent.php', dataType: 'json', data: {/* some parameters */}, success: function(data) { // some preprocessing of data cb(data.html); // some post processing of data }); } } Usage
view.getContent(); That’s it pretty simple.
The view/model does not have any references to each other.
Tags: decoupling, event messaging, Javascript
July 5, 2010 at 7:27 pm |
that’s all cool tips, thank you very much for sharing.