4. Binders - MagnusThor/BobTheBinder GitHub Wiki
##Binders
Binders are the mechanisms that connects the DOM element you associate with the model. It normally handles the two-way data binding. The first part of the data-bind indicates which binder you aim to use. Your data-bind expression can contain multiple binders if necessary. You can also register you own custom binders.
###"text" binder
The text binder updates the associated DOM element's text ( innerText), note that a text-binder will overwrite all the content of the DOM element when a mutation occurs.
'<mark data-bind="text:item.name"></mark>'
###"value" binder
The value binder connects the associated DOM element <input>
with a property of your model. This binder comes handy when working with form fields such as <input>
, <select>
and <textarea>
<input type="text" data-bind="value:item.name" />
###"click" binder
The click binder adds an event handler to the DOM element associated <button>
, <a>
or <input>
, the value specified in the click binder must be a JavaScript function that you chosen to be called when the associated DOM element is clicked.
<button data-bind="click:echo">Click me</button>
Where the model has a function named echo
var ViewModel = function () {
this.item = {
name: "John Doe"
};
this.echo = function () {
alert(this.item.name);
};
};
###"css" binder
The css binding adds or removes one ( limited in this version) CSS classes to the associated DOM element. The value of the binder must be a function ( not a inline expression ) on your model.
<p data-bind="text:item.name,css:item.isToOld"></p>
Where is isToOld is a function on the model that evaluates and returns a string, css class name to toggle
var ViewModel = function ()
{
var self = this;
this.item = {
name: "John Doe",
age: 40,
isToOld: function () {
return self.item.age < 40 ? "no" : "yes";
}
}
};
###"hide" binder
The hide binding makes the associated DOM element to hidden or visible according to the value you pass to the binding. Not that the value cannot be an inline expression. It must be a function on your model return a bool ( true/false )
<span data-bind="hide:isApproved">
<mark>A short message that shows when checked</mark>
</span>
Where the model looks like this.
var ViewModel = function () {
this.name = "Iggy pop";
this.email = "[email protected]";
this.isApproved = true;
this.signUp = function (evt) {
alert(this.name + ',has approved ' +
this.isApproved);
};
};
###href "binder"
The href binder modifies the href attribute on the associated DOM element, typical a <a>
element.
<a data-bind="href:item.url">My URL</a>