Backbone's philosophy is for a View, the display of a Model's state, to re-render after any changes have been made to the Model. This works beautifully for simple apps, but rich apps often need to render, respond, and synchronize changes with finer granularity.

Stickit is a Backbone data binding plugin that binds Model attributes to View elements with a myriad of options for fine-tuning a rich app experience. Unlike most model binding plugins, Stickit does not require any extra markup in your html; in fact, Stickit will clean up your templates, as you will need to interpolate fewer variables (if any at all) while rendering. In Backbone style, Stickit has a simple and flexible api which plugs in nicely to a View's lifecycle.

Similar to view.events, you can define view.bindings to map selectors to binding configurations. The following bindings configuration will bind the view.$('#title') element to the title model attribute and the view.$('#author') element to the authorName model attribute:

bindings:{

'#title':'title',

'#author':'authorName'

}

When the view's html is rendered, usually the last call will be to stickit. By convention, and in the following example, stickit will use view.model and the view.bindings configuration to initialize:

render: function(){

this.$el.html('<div id="title"/> <input id="author" type="text">');

this.stickit();

}

On the initial call, stickit will initialize the innerHTML of view.$('#title') with the value of the title model attribute, and will setup a one-way binding (model->view) so that any time a model change:title event is triggered, the view.$('#title') element will reflect those changes. For form elements, like view.$('#author'), stickit will configure a two-way binding (model<->view), connecting and reflecting changes in the view elements with changes in bound model attributes.

Uses view.bindings and view.model to setup bindings. Optionally, you can pass in a model and bindings hash. Note, it is safe to re-render or call stickit multiple times, as stickit will match any previously bound selectors and their associated models and unbind them before reinitializing.

render: function(){

this.$el.html(/* ... */);

// Initialize stickit with view.bindings and view.model

this.stickit();

// In addition to, or instead, call stickit with a different model and bindings configuration.

Adds a single binding to the view, using the given model, or view.model, and the given selector and configuration. It's also possible to pass in a bindings hash as the second parameter. If you use a selector that was already used for a binding, then the old binding will be destroyed before initializing the new binding.

Removes event bindings from all models. Optionally, a model can be passed in which will remove events for the given model and its corresponding bindings configuration only. Another option is to pass in a binding selector or bindings hash to granularly remove any bindings that are associated with this.model or the given model. Note, Stickit is setup to automatically unbind all bindings associated with a view on view.remove().

For each model that is unbound, a stickit:unstuck event will be triggered, and for each binding that is unbound the destroy callback will be executed.

The view.bindings is a hash of jQuery or Zepto selector keys with binding configuration values. Similar to the callback definitions configured in view.events, bindings callbacks can be defined as the name of a method on the view or a direct function body. view.bindings may also be defined as a function.

Once you are familiarized with the bindings callbacks, use this reference for a better idea of when they are called.

A string, function, or array which is used to map a model attribute to a view element. If binding to observe is the only configuration needed, then it can be written in short form where the attribute name is the value of the whole binding configuration.

Notes on binding to an array of attributes: when binding from model->view, this configuration should be paired with an onGet callback that can unpack/format the values. When binding from view->model, then onSet or getVal should be defined and should return an array of values that stickit will set into the model.

A callback which overrides stickit's default handling for retrieving the value from the bound view element. Use onSet to format values - this is better used in handlers or when extra/different dom operations need to be handled.

A callback which overrides stickit's default handling for updating the value of a bound view element. Use onGet to format model values - this is better used in handlers or when extra/different dom operations need to be handled .

A boolean value or a function that returns a boolean value which controls whether or not the model gets changes/updates from the view (model<-view). This is only relevant to form elements, as they have two-way bindings with changes that can be reflected into the model. Defaults to true.

When true, visible shows or hides the view element based on the model attribute's truthiness. visible may also be defined with a callback which should return a truthy value.
The updateView option defaults to false when using visible. You must opt-in to updateView in order to have both view element visibility and value changes bound to the observed attribute.

If more than the standard jQuery show/hide is required, then you can manually take control by defining visibleFn with a callback.

By default, form and contenteditable elements will be configured with two-way bindings, syncing changes in the view elements with model attributes. Optionally, one-way bindings can be configured with updateView or updateModel. With the events, you can specify a different set of events to use for reflecting changes to the model.

The following is a list of the supported form elements, their binding details, and the default events used for binding:

input, textarea, and contenteditable

element value synced with model attribute value

propertychange, input, change events are used for handling

input[type=checkbox]

checked property determined by the truthiness of the model attribute or if the checkbox "value" attribute is defined, then its value is used to match against the model. If a binding selector matches multiple checkboxes then it is expected that the observed model attribute will be an array of values to match against the checkbox value attributes.

if you choose to pre-render your select-options (not recommended) then there are two ways of configuring the bindings:

"data-stickit-bind-val" attributes in the DOM. This allows for binding non-string values from a prerendered <select>, assuming that you are using jQuery or a build of Zepto that includes the "data" module.

"option[value]" attributes in the DOM (used if no data-stickit-bind-val is present)

With the given collection, creates <option>s for the bound <select>, and binds their selected values to the observed model attribute. It is recommended to use selectOptions instead of pre-rendering select-options since Stickit will render them and can bind Objects, Arrays, and non-String values as data to the <option> values. The following are configuration options for binding:

collection: an object path of a collection relative to window or view/this, or a string function reference which returns a collection of objects. A collection should be an array of objects, a Backbone.Collection or a value/label map.

labelPath: the path to the label value for select options within the collection of objects. Default value when undefined is label.

valuePath: the path to the values for select options within the collection of objects. When an options is selected, the value that is defined for the given option is set in the model. Leave this undefined if the whole object is the value or to use the default value.

defaultOption: an object or method that returns an object with label and value keys, used to define a default option value. A common use case would be something like the following: {label: "Choose one...", value: null}.

When bindings are initialized, Stickit will build the <select> element with the <option>s and bindings configured. selectOptions are not required - if left undefined, then Stickit will expect that the <option>s are pre-rendered and build the collection from the DOM.

Note: if you are using Zepto and referencing object values for your select options, like in the second example, then you will need to also include the Zepto data module. Also, <select> bindings are two-way bindings only - updateView:false will be ignored.

The following example references a collection of stooges at window.app.stooges and uses the age attribute for labels and the name attribute for option values:

It is often useful to have a lookup table for converting between underlying values which are actually stored and transmitted and the human-readable labels that represent them. Such a lookup table (an object like { value1: label1, value2: label2 }) can be used to populate a select directly. By default, the options will be sorted alphabetically by label; pass a comparatorfunction or property name string to override this ordering (which delegates to _.sortBy).

bindings:{

'select#sounds':{

observe:'sound',

selectOptions:{

collection:{

moo:'cow',

baa:'sheep',

oink:'pig'

}

}

}

}

Finally, multiselects are supported if the select element contains the [multiple="true"] attribute. By default stickit will expect that the model attribute is an array of values, but if your model has a formatted value, you can use onGet and onSet to format attribute values (this applies to any select bindings).

//

// model.get('books') returns a dash-delimited list of book ids: "1-2-4"

bindings:{

'#books':{

observe:'books',

onGet: function(val){

// Return an array of the ids so that stickit can match them to select options.

return _.map(val.split('-'),Number);

},

onSet: function(vals){

// Format the array of ids into a dash-delimited String before setting.

Adds the given handler or array of handlers to Stickit. A handler is a binding configuration, with an additional selector key, that is used to customize or override any of Stickit's default binding handling. To derive a binding configuration, the selectors are used to match against a bound element, and any matching handlers are mixed/extended in the order that they were added.

Internally, Stickit uses addHandler to add configuration for its default handling. For example, the following is the internal handler that matches against textarea elements:

Backbone.Stickit.addHandler({

selector:'textarea',

events:['keyup','change','paste','cut'],

update: function($el, val){ $el.val(val);},

getVal: function($el){return $el.val();}

})

Except for the selector, those keys should look familiar since they belong to the binding configuration api. If unspecified, the following keys are defaulted for handlers: updateModel:true, updateView:true, updateMethod:'text'.

By adding your own selector:'textarea' handler, you can override any or all of Stickit's default textarea handling. Since binding configurations are derived from handlers with matching selectors, another customization trick would be to add a handler that matches textareas with a specific class name. For example:

Backbone.Stickit.addHandler({

selector:'textarea.trim',

getVal: function($el){return $.trim($el.val());}

})

With this handler in place, anytime you bind to a textarea, if the textarea contains a trim class then this handler will be mixed into the default textarea handler and getVal will be overridden.

Another good use for handlers is setup code for third-party plugins. At the end of View.render, it is common to include boilerplate third-party initialization code. For example the following sets up a Chosen multiselect,

render: function(){

this.$el.html(this.template());

this.setupChosenSelect(this.$('.friends'),'friends');

this.setupChosenSelect(this.$('.albums'),'albums');

}

setupChosenSelect: function($el, modelAttr){/* initialize Chosen for the el and map to model */}

Instead, a handler could be setup to match bound elements that have a chosen class and initialize a Chosen multiselect for the element:

JavaScript frameworks seem to be headed in the wrong direction - controller callbacks/directives, configuration, and special tags are being forced into the template/presentation layer. Who wants to program and debug templates?

If you are writing a custom frontend, then you're going to need to write custom JavaScript. Backbone helps you organize with a strong focus on the model, but stays the hell out of your presentation. Configuration and callbacks should only be in one place - the View/JavaScript.

Breaking Change: Calling view#stickit a second time with the same model, will no longer unbind all previously bound bindings associated with that model; instead, it will unbind any duplicate bindings (selectors) found in the given bindings hash (or whatever's in view.bindings) before initializing.

Added an view#addBinding which will initiate a single, or hash, of bindings.

view#unstickit now takes a second, optional, parameter which gives you the control to granularly remove a single, or hash, of bindings.

Breaking Change: removed support for input[type="number"]. Instead, use onSet to format Number values, if needed.

Breaking Change: The updateModel method parameters changed so the event is now passed as the second parameter. updateModel(val, options) -> updateModel(val, event, options)

Stickit will now load using the UMD pattern so it is compatible with AMD, Node.js, and CommonJS.

A view's bindings configuration can be defined as a function.

When observing an array, if onSet or getVal return an array of values, Stickit will match the values to their respective attributes defined in observe and set them in the model. If you don't desire this change, then you can override this behavior with the following change:

Added a set callback which by default calls model#set

Added the destroy binding callback to compliment initialize.

Trigger stickit:unstick for each model that is unbound in unstickit (or view.remove).

Added handling for observe in function form.

When binding with visible the {updateView:false} property is defaulted.

Stickit will no longer sanitize (convert a null/ model attribute value to empty string) values if onGet is defined.

Added support for the use of dot-notation in binding callbacks that are defined with a string that names a method on the view. For example - onGet: "myObj.myCallback".

Added Backbone.Stickit.getConfiguration which exposes the method of deriving configurations from handlers.

Fixed a bug where "null" would show in Chrome when binding attribute:null to an element value.

Breaking Change: Changed the last parameter from the model attribute name to the bindings hash in most of the binding callbacks. Note the model attribute name can still be gleaned from the bindings hash - options.observe. The following are the callbacks that were affected and their parameters (options are the bindings hash):
onGet(value, options)onSet(value, options)updateModel(value, options)updateView(value, options)afterUpdate($el, value, originalVal, options)visible(value, options)visibleFn($el, isVisible, options)

Added support for handling multiple checkboxes with one binding/selector and using the value attribute, if present, for checkboxes.

Added default values for labelPath and valuePath in selectOptions: label and value respectively.

Refactored event registration to use $.on and $.off instead of delegating through Backbone which fixed the following bugs:

view.events selectors and binding selectors that are equal were overriding #49