Event messaging between JavaScript objects.

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: , ,

One Response to “Event messaging between JavaScript objects.”

  1. Javascript Examples's avatarJavascript Examples Says:

    that’s all cool tips, thank you very much for sharing.

Leave a comment


Design a site like this with WordPress.com
Get started