9. Notifier (example) - MagnusThor/BobTheBinder GitHub Wiki
#Simple notifier "app"
Below is a complete example of how you use Bob's notifiers. The examples uses value, text and repeater binders as well as it illustrates how to attach notifiers to the view model. You can find an executable version of this example https://jsfiddle.net/MagnusThor/pagzcqb5/embedded/result/ ( as well as example code )
var ViewModel = (function() {
var ctor = function (name,age) {
var self = this;
this.item = {
name: name || "Robin Hood",
age: age || 40,
favColor: ["Green"]
};
this.color = "Red";
this.addFavColor = function (evt) {
evt.preventDefault();
this.item.favColor.push(self.color);
};
this.deleteFavColor = function (evt) {
evt.preventDefault();
var value = this.toString();
var removed = self.item.favColor.findIndex(function(pre) {
return pre === value;
});
self.item.favColor.remove(removed);
};
};
return ctor;
})();
bob.on(vm.item, "item").update(
function(object,propertyName,typeOfMutation,
oldValue) {
logger("new value for " +
propertyName + " is " +
object[propertyName] + " oldValue was '"
+ oldValue + "'");
});
// attach notifiers for the collection / array of favColor
bob.on(vm.item.favColor, "favColor").add(function(object) {
logger("added a favColor -" + object);
}).delete(function (object) {
logger("removed a favColor - " + object);
});
The markup below shows the binders uses and how those are associated to the view model using bob's syntax for binding.
<div id="app">
<fieldset>
<div>
<label>Name:</label>
<input type="text" name="name"
data-bind="value:item.name,validate:item.name" />
</div>
<div>
<label>Age:</label>
<input type="text" name="age"
data-bind="value:item.age" />
</div>
<hr/>
<input type="text" name="favCol" data-bind="value:color" />
<button data-bind="click:addFavColor">Add color</button>
<ul>
<li data-repeat="item.favColor"
data-bind="text:$this,click:$root.deleteFavColor"></li>
</ul>
<em>Click color to remove..</em>
</fieldset>
</div>
###Demo page
You can try the example out at the following url (jsfiddle )