Mmvp.js
µ-MVP LibraryMmvp.js is a micro-MVP javascript library which allows you to bind presenter callbacks to be triggered in reaction to changes in a model.
Binding1 callbacks is as simple as passing a presenter callback function to Mmvp
's set_action
function. Once an action is bound, modifying the model dispatches the attached callback:
var presenter = new Mmvp();
var model = {};
presenter.set_action({
add: function(key, value) {
console.log(
"key '" + key + "' added with value '" + value + "'"
);
}
});
model.item_a = "hello";
presenter.sync(model);
// console.log: key 'item_a' added with value 'hello'</pre>
The above example2 shows binding of the add
action callback. In addition to the add
callback, the following callbacks may be bound to react to model changes:
Action | Arguments | Dispatched when |
---|---|---|
add |
key , value
|
An item is added to the model |
remove |
key |
An item is removed from the model |
update |
key , value
|
An item's value was udpated |
populate |
key , value
|
The model goes from being empty to populated |
empty |
The model goes from being populated to empty |
You can imagine how you might construct more complex views by putting to use DOM selectors and a templating engine in your action callbacks.
A MVP library explication wouldn't be complete without a TodoMVC demo. So, here's an archetypal TodoMVC demo coded up3 using Mmvp
's presenter callbacks. :
- Binding as in specifying M->V callbacks; and not V->M callbacks. After all V->M logic is typically handled as consequent of user-interaction and thus should be specified in user-interface callbacks.
- Feel free to pop open web inspector and run on this page!
Mmvp
is in global scope. - The demo code (74 SLOC) is only slighter heavier than the Mmvp library itself (45 SLOC)