public
Created

knockout-style data-bind attributes for backbone.js

  • Download Gist
1-DataBindConvention.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
var DataBindConvention = {
selector: "*[data-bind]",
handler: {
bind: function(selector, view, model){
view.$(selector).each(function(index){
var element = view.$(this);
var databind = element.attr("data-bind").split(" ");
var elementAttr = databind[0];
var modelAttr = databind[1];
 
model.bind("change:" + modelAttr, function(changedModel, val){
switch(elementAttr){
case "html":
element.html(val);
break;
case "text":
element.text(val);
break;
default:
element.attr(elementAttr, val);
}
});
 
});
}
}
};
 
Backbone.ModelBinding.Conventions.dataBind = DataBindConvention;
2-rerender.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
var vent = _.extend({}, Backbone.Events);
 
AddEditView = Backbone.View.extend({
events: {
"click #save": "save"
}
 
initialize: function(options){
this.vent = options.vent;
},
 
save: function(){
this.model.save();
this.vent.trigger("modelUpdated");
}
});
 
MedicationView = Backbone.View.extend({
initialize: function(options){
_.bindAll(this, "render");
options.vent.bind("modelUpdated", this.render);
},
 
render: function(){
// ... jQuery template stuff here
}
});
3-databind.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
AddEditView = Backbone.View.extend({
render: function(){
// ... jQuery template stuff here
Backbone.ModelBinding.call(this);
}
});
 
MedicationView = Backbone.View.extend({
render: function(){
// ... jQuery template stuff here
Backbone.ModelBinding.call(this);
}
});
4-databind.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<fieldset>
<legend data-bind="text trade_name">Some drugs</legend>
<ul>
<li class="medication-data">
<div class="label">Dosage</div>
<div class="data" data-bind="text dosage">5000mg</div>
</li>
<li class="medication-data">
<div class="label">Route</div>
<div class="data" data-bind="text route">something</div>
</li>
...
</ul>
</fieldset>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.