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
}
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.