Created
August 12, 2012 01:06
-
-
Save darrenderidder/3328550 to your computer and use it in GitHub Desktop.
simple mvc pubsub example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var subscribers = []; | |
function publish(info) { | |
for (i in subscribers) { | |
subscribers[i].update(info); | |
} | |
}; | |
// after View is defined... | |
subscribers.push(View); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Model = { | |
counter: 0, | |
incr: function () { | |
this.counter++; | |
publish(this); | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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