Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 491 lines (356 sloc) 15.879 kb
376574a1 »
2011-07-23 initial commit / structure
1 # Backbone.ModelBinding
2
239cc50a »
2011-08-14 version bump and starting to work on api for unbind
3 Convention-based, awesome model binding for [Backbone.js](http://documentcloud.github.com/backbone)
376574a1 »
2011-07-23 initial commit / structure
4
2dd1d19b »
2011-07-24 correct name in the link to the inspiring post
5 Inspired by [Brad Phelan](http://xtargets.com/2011/06/11/binding-model-attributes-to-form-elements-with-backbone-js/),
239cc50a »
2011-08-14 version bump and starting to work on api for unbind
6 Knockout.js' data-binding capabilities, and [Brandon Satrom](http://userinexperience.com/?p=633)'s
7 work with Knockout.
153f0078 »
2011-07-23 link to blog post that inspired this
8
004fd10d »
2011-07-24 updating readme with example and cautionary info
9 ## Getting Started
000549a5 »
2011-07-23 note on not being ready for use
10
dfc805a6 »
2011-07-24 updating readme with info about prerequisites, etc
11 It's easy to get up and running. You only need to have Backbone (including underscore.js -
12 a requirement for Backbone) and jQuery in your page before including the backbone.modelbining
13 plugin.
000549a5 »
2011-07-23 note on not being ready for use
14
dfc805a6 »
2011-07-24 updating readme with info about prerequisites, etc
15 ### Prerequisites
16
17 * Backbone.js v0.5.1 or higher
18 * jQuery v1.6.2 or higher
19
20 This is a plugin for Backbone.js and is built and tested against Backbone v0.5.1. It also uses jQuery
21 to perform most of the bindng and manipulations, and is built and tested against v1.6.1. However, I am
22 currently using this plugin in a production application with Backbone v0.3.3 and jQuery v1.5.1.
23
24 At this point, I make no guarantees of it working with any version of Backbone or jQuery,
25 other than what it has been built and tested against. It works for me, so it may work for you
26 with versions other than what is stated
27
28 ### Get The ModelBinding Plugin
29
30 Download the `backbone.modelbinding.js` file from this github repository and copy it into
31 your javascripts folder. Add the needed `<script>` tag to bring the plugin into any page
32 that wishes to use it. Be sure to include the modelbinding file _after_ the backbone.js file.
33
2c8eb061 »
2011-08-15 documentation for unbind method
34 ### Model Binding
7f2301e9 »
2011-07-24 added basic support for htmlBindings - to go from the model's fields …
35
2c8eb061 »
2011-08-15 documentation for unbind method
36 The model binding code is executed with a call to `Backbone.ModelBinding.bind(view)`. There are
8755836b »
2011-08-11 updated the documentation concerning when to call the model binding code
37 several places that it can be called from, depending on your circumstances.
38
39 All of the element binding happens within the context of the view's `el`, therefore you must
40 call the model binding code after your view's `el` has been populated with the elements that
41 will be bound to.
42
43 #### Binding After Rendering
44
45 If your view modifies the html contents of the view's `el` in the `render` method, you should
46 call the model binding after the modifications are made:
004fd10d »
2011-07-24 updating readme with example and cautionary info
47
48 ````
49 SomeView = Backbone.View.extend({
7f2301e9 »
2011-07-24 added basic support for htmlBindings - to go from the model's fields …
50 render: function(){
51 // ... render your form here
8755836b »
2011-08-11 updated the documentation concerning when to call the model binding code
52 $(this.el).html("... some html and content goes here ... ");
7f2301e9 »
2011-07-24 added basic support for htmlBindings - to go from the model's fields …
53
8755836b »
2011-08-11 updated the documentation concerning when to call the model binding code
54 // execute the model bindings
2c8eb061 »
2011-08-15 documentation for unbind method
55 Backbone.ModelBinding.bind(this);
004fd10d »
2011-07-24 updating readme with example and cautionary info
56 }
57 });
58 ````
59
8755836b »
2011-08-11 updated the documentation concerning when to call the model binding code
60 #### Binding A View That Does Not Render
61
62 If, however, your view has an `el` that represents an existing element in your html, and the
63 contents of the `el` are not modified during a call to `render`, then you can make the call to
64 the model binding code in the initializer or anywhere else.
65
66 ````
67 <form id="some-form">
68 Name: <input id="name">
69 </form>
70 ````
71
72 ````
73 FormView = Backbone.View.extend({
74 el: "#some-form",
75
76 initialize: function(){
2c8eb061 »
2011-08-15 documentation for unbind method
77 Backbone.ModelBinding.bind(this);
8755836b »
2011-08-11 updated the documentation concerning when to call the model binding code
78 }
79 });
80 ````
81
82 #### Binding From Outside A View
83
84 There is no requirement for the model binding code to be called from within a view directly.
85 You can bind the view from external code, like this:
86
87 ````
88 FormView = Backbone.View.extend({
89 el: "#some-form",
90 });
91
92 formView = new FormView();
2c8eb061 »
2011-08-15 documentation for unbind method
93 Backbone.ModelBinding.bind(formView);
94 ````
95
96 ### Model Unbinding
97
98 When your view has completed its work and is ready to be removed from the DOM, you not only
99 need to unbnd your view's events (handled through the view's `remove` method, typically), you
100 also need to unbind the model events that are bound in the view.
101
102 Backbone.ModelBinding can unbind its own events through a simple call to
103 `Backbone.ModelBinding.unbind(view)`. If you do not call this method when your view is being
104 closed / removed / cleaned up, then you may end up with memory leaks and zombie views that
105 are still responding to model change events.
106
107 ````
108 FormView = Backbone.View.extend({
109 el: "#some-form",
110
111 initialize: function(){
112 Backbone.ModelBinding.bind(this);
113 },
114
115 close: function(){
116 this.remove();
117 this.unbind();
118 Backbone.ModelBinding.unbind(this);
119 }
120 });
8755836b »
2011-08-11 updated the documentation concerning when to call the model binding code
121 ````
122
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
123 ## Convention Bindings
e4932c63 »
2011-07-24 updated readme to talk about convention binding
124
125 Automatic bi-directional binding between your form input and your model.
126
127 The convention based binding requires no additional configuration or code in your
2c8eb061 »
2011-08-15 documentation for unbind method
128 view, other than calling the `Backbone.ModelBinding.bind(this);` as noted above.
e4932c63 »
2011-07-24 updated readme to talk about convention binding
129 With the conventions binding, your `<input>` fields will be bound to the views model
130 by the id of the input.
131
132 For example:
133
134 ````
135 // something.html
136
137 <input id='name'>
138
139 // something.js
140
141 SomeModel = Backbone.Model.extend();
142
143 SomeView = Backbone.View.extend({
144 render: function(){
145 // ... render your form here
146
147 // execute the defined bindings
2c8eb061 »
2011-08-15 documentation for unbind method
148 Backbone.ModelBinding.bind(this);
e4932c63 »
2011-07-24 updated readme to talk about convention binding
149 }
150 });
151
152 model = new SomeModel();
153 view = new SomeView({model: model});
154
155 model.set({name: "some name"});
156
157 ````
158
159 In this example, when `model.set` is called to set the name, "some name" will appear
160 in the `#name` input field. Similarly, when the `#name` input field is changed, the
161 value entered into that field will be sent to the model's `name` attribute.
162
bb8d2341 »
2011-08-06 documented data-bind
163 ## Data-Bind Attributes
57ed5b93 »
2011-07-25 updated docs to list supported input types
164
bb8d2341 »
2011-08-06 documented data-bind
165 Backbone.ModelBinding supports Knockout-style data-bind attributes on any arbitrary
166 HTML element. These bindings will populate any attribute, the text, or HTML contents
167 of an HTML element based on your configurations. This is particularly useful when a
168 model that is being edited is also being displayed elsewhere on the screen.
169
170 To bind an element to a model's attributes, add a `data-bind` attribute to the element
171 and specify what should be updated with which model attribute using a `elementAttr modelAttr`
172 format. For example `<span data-bind="text name">` will update the span's text with
173 the model's name attribute, when the model's name changes.
174
175 ````
176 <form>
177 <input type="text" id="name">
178 </form>
179 Name: <span data-bind="text name">
180
181 SomeView = Backbone.View.extend({
182 // ...
183
184 render: function(){
185 // ...
2c8eb061 »
2011-08-15 documentation for unbind method
186 Backbone.ModelBinding.bind(this);
bb8d2341 »
2011-08-06 documented data-bind
187 }
188 });
189
190 someModel = new SomeModel();
191 someView = new SomeView({model: someModel});
192 ````
193
194 In this example, the model's `name` will be updated when you type into the text box
195 and then tab or click away from it (to fire the change event). When the model's `name`
196 attribute is updated, the `data-bind` convention will pick up the change and set
197 the text of the `span` to the model's name.
198
977f6743 »
2011-08-14 docs for data-bind='enabled ...' and spec to prove data-bind='disable…
199 ### Special Cases For data-bind
200
201 There are several special cases for the data-bind attribute. These allow a little more
202 functionality than just setting an attribute on an element.
203
204 * html - replace the html contents of the element
205 * text - replace the text contents of the element
206 * enabled - enable or disable the html element
207
208 #### html
209
210 If you set the data-bind attribute to use `html`, it will replace the entire
211 inner html of the html element, instead of just setting an element attribute.
212
213 ````
214 <div id="someDiv" data-bind="html someProperty"></div>
215
216
217 someModel.set({someProperty: "some value"});
218 ````
219
220 #### text
221
222 If you set the data-bind attribute to use `text`, it will replace the text contents of the
223 html element instead of just setting an element attribute.
224
225 ````
226 <div id="someDiv" data-bind="text someProperty"></div>
227
228
229 someModel.set({someProperty: "some value"});
230 ````
231
232 #### enabled
233
234 This special case breaks the html element standard of using a `disabled` attribute, specifically
235 to inver the logic used for enabling / disabling an element, to keep the data-bind attribute
236 clean and easy to read.
237
238 If you have a model with a property that indicates a negative state, such as `invalid`, then you
239 can use a data-bind attribute of `disabled`:
240
241 ````
242 <button id="someButton" data-bind="disabled invalid"></div>
243
244
245 someModel.set({invalid: true});
246 ````
247
248 However, some developers prefer to use positive state, such as `isValid`. In this case, setting
249 the disabled attribute to the model's isValid attribute would result in the button being disabled
250 when the model is valid and enabled when the model is not valid. To correct this, a special case
251 has been added to enable and disable an element with `enabled`.
252
253 ````
254 <button id="someButton" data-bind="enabled isValid"></div>
255
256
257 someModel.set({isValid: false});
258 ````
259
260 This will disable the button when the model is invalid and enable the button when the model is
261 valid.
262
b2fef6d8 »
2011-08-07 removed the formBinding code. it wasn't that useful and the configura…
263 ## Form Binding Conventions
bb8d2341 »
2011-08-06 documented data-bind
264
265 The following form input types are supported by the form convention binder:
57ed5b93 »
2011-07-25 updated docs to list supported input types
266
267 * text
268 * textarea
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
269 * password
57ed5b93 »
2011-07-25 updated docs to list supported input types
270 * checkbox
e4417b12 »
2011-08-01 updated documentation to discuss the behavior of select box convention
271 * select
272 * radio button groups
273
274 Radio buttons are group are assumed to be grouped by the `name` attribute of the
275 radio button items.
276
277 Select boxes will populate 2 separate fields into the model that they are bound to.
278 The standard `#fieldid` will be populated with the selected value. An additional
279 `{#fieldid}_text` will be populated with the text from the selected item. For example,
280 a selected option of
281
282 ````
283 <select id='company'>
284 <option value="foo_bar">Foo Bar Widgets, Inc.</option>
285 ...
286 </select>
287 ````
288
289 will populate the `company` attribute of the model with "foo_bar", and will populate
290 the `company_text` attribute of the model with "Foo Bar Widgets, Inc."
57ed5b93 »
2011-07-25 updated docs to list supported input types
291
292 There is no support for hidden fields at the moment, because there is no 'change' event
293 that jQuery can listen to on a hidden field.
e4932c63 »
2011-07-24 updated readme to talk about convention binding
294
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
295 ### Configuring The Bound Attributes
7f2301e9 »
2011-07-24 added basic support for htmlBindings - to go from the model's fields …
296
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
297 The convention binding system allows you to specify the attribute to use for the convention, by
298 the input type. The default configuration is:
004fd10d »
2011-07-24 updating readme with example and cautionary info
299
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
300 ```
301 {
302 text: "id",
303 textarea: "id",
304 password: "id",
305 radio: "name",
306 checkbox: "id",
307 select: "id"
308 }
004fd10d »
2011-07-24 updating readme with example and cautionary info
309 ````
310
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
311 You can override this configuration and use any attribute you wish, by specifying any or all of
312 these input types when you call the model binding. This is useful when you have field ids that
b3f6e8e1 »
2011-08-10 updated documentation to discuss setting all binding attributes
313 do not match directly to the model attributes.
314
315 #### Override All Element Binding Attributes
316
317 The following will use use the `class` attribute's value as the binding for all input field:
318
319 ````
320 SomeView = Backbone.View.extend({
321 render: function(){
322 // ... some rendering here
2c8eb061 »
2011-08-15 documentation for unbind method
323 Backbone.ModelBinding.bind(this, { all: "class" });
b3f6e8e1 »
2011-08-10 updated documentation to discuss setting all binding attributes
324 }
325 });
326
327 <input type="text" id="the_model_name" class="name">
328 ````
329
330 If the same convention needs to be used throughout an application, and not just withing a single
331 view, the configuration can be set at a global level:
332
333 ````
334 Backbone.ModelBinding.Configuration.configureAllBindingAttributes({all: "class"});
335 ````
336
337 #### Override Individual Element Binding Attributes
338
339 The following will use a `modelAttr` attribute value as the convention for text boxes, only.
7f2301e9 »
2011-07-24 added basic support for htmlBindings - to go from the model's fields …
340
341 ````
342 SomeView = Backbone.View.extend({
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
343 render: function(){
344 // ... some rendering here
2c8eb061 »
2011-08-15 documentation for unbind method
345 Backbone.ModelBinding.bind(this, { text: "modelAttr" });
7f2301e9 »
2011-07-24 added basic support for htmlBindings - to go from the model's fields …
346 }
347 });
348
47e4cbc3 »
2011-08-06 updated the readme to talk about the configuration options for the co…
349 <input type="text" id="the_model_name" modelAttr="name">
350 ````
351
352 When this text box has it's value changed, the model's `name` attribute will be populated with
353 the value instead of `the_model_name`.
404d7638 »
2011-07-24 note about htmlBindings
354
1fe9132d »
2011-08-06 updated readme to discuss global config
355 If the same convention needs to be used throughout an application, and not just withing a single
356 view, the configuration can be set at a global level:
357
358 ````
650e27ab »
2011-08-06 moved glocal attribute binding to the Configuration object
359 Backbone.ModelBinding.Configuration.configureBindingAttributes({text: "modelAttr"});
1fe9132d »
2011-08-06 updated readme to discuss global config
360 ````
361
362 Now all text boxes will update the model attribute specified in the text box's `modelAttr`.
363
bb8d2341 »
2011-08-06 documented data-bind
364 ## Pluggable Conventions
c3433ddd »
2011-07-25 spec to show that you can add your own conventions. documentation on …
365
366 The convention based bindings are pluggable. Each of the existing form input types can have it's
367 convention replaced and you can add your own conventions for input types not currently handled,
368 etc.
369
370 To replace a convention entirely, you need to supply a json document that has two pieces of
371 information: a jQuery selector string and an object with a `bind` method. Place the convention
372 in the `Backbone.ModelBinding.Conventions` and it will be picked up and executed. The `bind`
373 method receives three parameters: the jQuery selector you specified, the Backbone view, and
374 the model being bound.
375
4ea0020a »
2011-07-25 updated the documentation for convention building
376 You can replace the handler of an existing convention. For example, this will set the
c3433ddd »
2011-07-25 spec to show that you can add your own conventions. documentation on …
377 value of a textbox called `#name` to some text, instead of doing any real binding.
378
379 ````
380 var nameSettingsHandler = {
381 bind: function(selector, view, model){
382 view.$("#name").val("a custom convention supplied this name");
383 }
384 };
385
386 Backbone.ModelBinding.Conventions.text.handler = nameSettingsHandler;
387 ````
388
4ea0020a »
2011-07-25 updated the documentation for convention building
389 You can also create your own conventions that do just about anything you want. Here's an example
390 that modifies the contents of `<p>` tags:
391
392 ````
393 var PConvention = {
394 selector: "p",
395 handler: {
396 bind: function(selector, view, model){
397 view.$(selector).each(function(index){
398 var name = model.get("name");
399 $(this).html(name);
400 });
401 }
402 }
403 };
404
405 Backbone.ModelBinding.Conventions.paragraphs = PConvention;
406 ````
407
408 This example will find all `<p>` tags in the view and render the `name` attribute from the model
409 into that paragraph, replacing all other text. Note that the name of the convention is set to
410 `paragraphs` when added to the conventions. This name did not exist prior to this assignment, so
411 the convention was added. If you assign a convention to an existing name, you will replace that
412 convention.
413
414 The list of existing conventions includes:
415 * text
416 * password
417 * radio
418 * checkbox
419 * select
420 * textarea
bb8d2341 »
2011-08-06 documented data-bind
421 * formbinding
422 * databind
4ea0020a »
2011-07-25 updated the documentation for convention building
423
c3433ddd »
2011-07-25 spec to show that you can add your own conventions. documentation on …
424 For fully functional, bi-directional binding convention examples, check out the source code
425 to Backbone.ModelBinding in the `backbone.modelbinding.js` file.
126af8d9 »
2011-08-11 adding release notes, retroactive
426
427 ## Release Notes
428
63f3c92e »
2011-08-15 release notes for v0.3.0
429 ### v0.3.0
430
0b009b63 »
2011-08-15 updated release notes for v0.3.0
431 * **Breaking Change:** Changed the `Backbone.ModelBinding.call(view)` method signature to `Backbone.ModelBinding.bind(view)`
432 * Added ability to unbind model binding with `unbind` method, to prevent memory leaks and zombie forms
437566d9 »
2011-08-15 added minified version to the repo
433 * Added backbone.modelbinding.min.js to the repository, compiled with
434 [Google's Closure Compiler Service](http://closure-compiler.appspot.com/home "Google's Closure Compiler Service")
0b009b63 »
2011-08-15 updated release notes for v0.3.0
435 * Updated the selectors used for the conventions. Text inputs are now found with "input:text", which should
436 select all text inputs, even without a `type='text'` attribute (though this seems to be buggy in jQuery
437 v1.6.2)
438 * Significant internal restructuring of code
63f3c92e »
2011-08-15 release notes for v0.3.0
439
e36b828b »
2011-08-14 added release notes for v0.2.4
440 ### v0.2.4
441
442 * data-bind will bind the model's value immediately instead of waiting for the model's value to change
443 * support `enabled` functionality for data-bind: `data-bind="enabled isValid"`
444 * documented existing support for data-bind `disabled`: `data-bind="disabled invalid"`
445
126af8d9 »
2011-08-11 adding release notes, retroactive
446 ### v0.2.3
447
448 * Fixes for 'falsey' value bindings
449 * Update the docs to include when and where to call the model bindings
450
451 ### v0.2.2
452
453 * Making some global vars not global
454
455 ### v0.2.1
456
457 * Configuration to easily set all binding attributes for all elements
458 * Fix for IE
459 * Making some global vars not global
460
461 ### v0.1.0 - v0.2.0
462
463 * Added data-bind convention
464 * Added configuration options
465 * Conventions for all form input types
466 * Removed formBinding code
467 * Removed htmlBinding code
468 * Significant internal code cleanup and restructuring
c3433ddd »
2011-07-25 spec to show that you can add your own conventions. documentation on …
469
004fd10d »
2011-07-24 updating readme with example and cautionary info
470 # Legal Mumbo Jumbo (MIT License)
376574a1 »
2011-07-23 initial commit / structure
471
11a2e01d »
2011-07-25 added copyright and license notice. cleaned up the way the code execu…
472 Copyright (c) 2011 Derick Bailey, Muted Solutions, LLC
376574a1 »
2011-07-23 initial commit / structure
473
474 Permission is hereby granted, free of charge, to any person obtaining a copy
475 of this software and associated documentation files (the "Software"), to deal
476 in the Software without restriction, including without limitation the rights
477 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
478 copies of the Software, and to permit persons to whom the Software is
479 furnished to do so, subject to the following conditions:
480
481 The above copyright notice and this permission notice shall be included in
482 all copies or substantial portions of the Software.
483
484 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
485 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
486 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
487 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
488 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
489 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
490 THE SOFTWARE.
Something went wrong with that request. Please try again.