outback is a JavaScript library that extends Backbone.js with support for Knockout-inspired declarative bindings.
- jQuery (>=1.7)
- Backbone.js (>=0.9.1)
- Underscore.js (>=1.3.1)
- rj
Just add these dependencies to your site's <head>
, in order:
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script src="rj.js"></script>
<script src="outback.js"></script>
Let's start with a complete example (given in CoffeeScript):
<body id="fixture">
<button id="show" data-bind="disable: @shouldShowMessage">Reveal Text</button>
<button id="reset" data-bind="enable: @shouldShowMessage">Reset</button>
<div data-bind="visible: @shouldShowMessage">
<p>You will see this message only when "shouldShowMessage" holds a true value.</p>
</div>
</body>
class MainView extends Backbone.View
events:
'click #show': 'showMessage'
'click #reset': 'hideMessage'
initialize: ->
@render()
render: ->
Backbone.outback.bind @
remove: ->
Backbone.outback.unbind @
showMessage: function() {
@model.set shouldShowMessage: true
hideMessage: function() {
@model.set shouldShowMessage: false
$ ->
window.app = new MainView
el: '#fixture'
model: new Backbone.Model
shouldShowMessage: false
Here's a more detailed rundown.
Configure your markup and templates with 'data-bind' attributes to bind elements to Backbone.Model attributes:
<body id="fixture">
<button id="show" data-bind="disable: @shouldShowMessage">Reveal Text</button>
<button id="reset" data-bind="enable: @shouldShowMessage">Reset</button>
<div data-bind="visible: @shouldShowMessage">
<p>You will see this message only when "shouldShowMessage" holds a true value.</p>
</div>
</body>
The directionality of the binding is handled in the binding API. For example, text is a one-way binding useful for spans and paragraphs, and value is a two-way binding that is useful for form inputs, selects, and textareas.
In the render
method of your Backbone.View, call bind
after appending your markup to $el
:
render: ->
Backbone.outback.bind @
Under the hood, outback attaches change
event handlers to your model. In order to avoid leaks and zombie function callbacks, you'll need to unbind
the view in remove
:
remove: ->
Backbone.outback.unbind @
That's it!
Yes.