backbone.computed
v0.0.6
Published
Simple computed fields for Backbone models
Downloads
6
Maintainers
Readme
backbone.computed
Simple computed fields for Backbone models
Introduction
Ever get the feeling that there is something missing from backbone models? Well I got the feeling especially when using backbone models with so called "logic-less" template systems such as Mustache, Hogan and handlebars.
Although handlebars has some built in "logic" helpers (which you can add to) and Marionette has helpfull features such as templateHelpers
some properties are computed over and over again and they really belong on the model.
This is where backbone.computed attempts to bridge the gap.
Usage
Similar to model.events
, you define your computed properties to model.computed
:
var Person = Backbone.Model.extend({
computed: {
fullName: function () {
return this.get('firstName') + ' ' + this.get('lastName');
}
}
});
var person = new Person({
firstName: 'Tim',
lastName: 'Burton',
age: 20
});
you can access your computed properties just like normal model attributes:
person.get('fullName'); // returns 'Tim Burton'
Computed properties do not come into effect when calling save
:
person.save();
/**
* submitted in ajax body:
* {
* firstName: 'Tim',
* lastName: 'Burton',
* age: 20
* }
*/
If you are using a handlebars
and want to serialise your model ready for your template:
<script id="person-template" type="text/x-handlebars-template">
<div class="person">
<h1>{{fullName}}</h1>
<div class="details">
Age: {{age}}
</div>
</div>
</script>
var source = $("#person-template").html();
var template = Handlebars.compile(source);
var html = template(person.toJSON());
results in:
<div class="person">
<h1>Tim Burton</h1>
<div class="details">
Age: 20
</div>
</div>
If using Marionette
in conjunction with backbone.computed
things get really simple as when Marionette
passes the model data to the views template it just calls toJSON
on the backbone model.
The example below is using Marionettes
default template system which is really just underscores template system but this can easily be swapped out for handlebars
or another:
<script id="person-template" type="text/template">
<div class="person">
<h1><%= fullName %></h1>
<div class="details">
Age: <%= age %>
</div>
</div>
</script>
var PersonView = Marionette.ItemView.extend({
template: '#person-template'
});
...
var person = new Person({
firstName: 'Tim',
lastName: 'Burton',
age: 20
});
layoutView.content.show(new PersonView({ model: person }));
this will again results in:
<div class="person">
<h1>Tim Burton</h1>
<div class="details">
Age: 20
</div>
</div>
Duck Punching
This plugin adds its functionality by duck punching the original implementations of get
and toJSON
on Backbone.Model
.
If no computed properties exist the original implementations will kick in.