Created
February 6, 2012 07:04
-
-
Save kaineer/1750357 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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