Skip to content

Instantly share code, notes, and snippets.

@darrenderidder
Created August 12, 2012 01:06
Show Gist options
  • Save darrenderidder/3328550 to your computer and use it in GitHub Desktop.
Save darrenderidder/3328550 to your computer and use it in GitHub Desktop.
simple mvc pubsub example
// MVC PubSub and Chaining Explained in < 20 lines of JavaScript
// PubSub
var subscribers = [];
function publish(info) {
for (i in subscribers) {
subscribers[i].update(info);
}
};
// MVC
var Model = {
counter: 0,
incr: function () {
this.counter++;
publish(this);
}
};
var View = {
update: function(model) {
console.log(JSON.stringify(model));
}
};
subscribers.push(View); // Subscribe for updates
var Controller = {
model: Model,
count: function () {
this.model.incr();
return this; // Chaining
}
};
Controller.count().count().count();
var subscribers = [];
function publish(info) {
for (i in subscribers) {
subscribers[i].update(info);
}
};
// after View is defined...
subscribers.push(View);
var Model = {
counter: 0,
incr: function () {
this.counter++;
publish(this);
}
};
var Controller = {
model: Model,
count: function () {
this.model.incr();
return this;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment