Skip to content

Instantly share code, notes, and snippets.

@kaineer
Created February 6, 2012 07:04
Show Gist options
  • Select an option

  • Save kaineer/1750357 to your computer and use it in GitHub Desktop.

Select an option

Save kaineer/1750357 to your computer and use it in GitHub Desktop.
/*
YourApp.Foo = YourApp.Model.extend({
modelBindings: {
"change:name": "displayName",
"change:weight": function() { $("#weight").val(this.model.get("weight")); }
}
})
*/
YourApp.Model = Backbone.Model.extend({
//
setModel: function(newModel) {
var eventName, handler;
// Unbind previous model, if any
if(this.model) {
this.model.unbind();
}
//
if(newModel) {
switch(typeof(this.modelBindings)) {
case "function":
this.modelBindings(this, newModel);
break;
case "object":
this._applyModelBindingsObject(newModel);
break;
}
}
//
this.model = newModel;
},
_applyModelBindingsObject: function(model, modelBindings) {
// Defaults
model || (model = this.model);
modelBindings || (modelBindings = this.modelBindings || {});
// Loop through bindings
for(eventName in modelBindings) {
handler = modelBindings[eventName];
if(typeof(handler) == "string") {
handler = this[handler];
}
if(_.isFunction(handler)) {
model.bind(eventName, _.bind(handler, this));
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment