5. Custom binders - MagnusThor/BobTheBinder GitHub Wiki
Custom binders can easily be added/removed by calling the register
or unregister
methods on Bob.binders
object as show below.
##How to register or unregister a custom binder
###register binder
Bob.binders.register(name,fn)
###unregister binder
Bob.binders.unregister(name);
Where your binder function (fn) has the following signature.
function(node, onchange, onadd,onremove)
##Custom binder stub
Bob.binders.registerBinder("customBinder", function (node,
onchange,
onadd,
onremove) {
var previousListener;
// node is the DOM node associated
return {
updateProperty: function (value) {
var listener = function(evt) {
// call onchage(value) for instance
};
if (previousListener) {
node.removeEventListener("click", listener);
}
node.addEventListener("click", listener);
previousListener = listener;
}
};
});
updateProperty function
You binder must return a updateProperty
, a function that will be invoked when the model mutates.
return {
updateProperty: function(value,parent) {
}
The value
argument contains the value of the property specified in the DOM association , in ex. if you have the following model
var ViewModel = (function () {
var ctor = function (name) {
this.name = name || "robin hood";
};
return ctor;
})();
with the following DOM association
<input type="text" data-bind="valueUpperCase:name" />
The value
argument will contain 'robin hood' when the model mutates ( the property is modified ), the parent
in this case will be the model it self , as the we associate the name property using valueUpperCase:name
The binders updateProperty
is invoked by Bob him self. When it comes to scenarios where you from the UI want to pass changes to the model you need to use the call the onchange method. For binders that are deals with collection/arrays use the onadd,onremove functions.
A quick example
This custom binder ensures that the value entered / modified becomes upperCase ( i.e robin hood -> ROBIN HOOD)
Bob.binders.registerBinder("valueUpperCase", function(node,
onchange, onadd, onremove) {
node.addEventListener('keyup', function() {
onchange(node.value.toUpperCase());
});
return {
updateProperty: function (value) {
console.log(arguments);
if (value !== node.value) {
node.value = value.toUpperCase();
}
}
};
});