Skip to content

Instantly share code, notes, and snippets.

@bregenspan
Created April 26, 2012 23:28
Show Gist options
  • Save bregenspan/2504141 to your computer and use it in GitHub Desktop.
Save bregenspan/2504141 to your computer and use it in GitHub Desktop.
Add support for combination of manual and automatic bindings to Backbone ModelBinder
diff --git a/static/js/lib/Backbone.ModelBinder.js b/static/js/lib/Backbone.ModelBinder.js
index b321c37..53881b1 100644
--- a/static/js/lib/Backbone.ModelBinder.js
+++ b/static/js/lib/Backbone.ModelBinder.js
@@ -25,6 +25,10 @@
this._model = model;
this._rootEl = rootEl;
+ this._attributeBindings = {};
+ this._options = { // TODO: set this properly
+ alwaysDefaultBindings: true
+ };
if (!this._model) throw 'model must be specified';
if (!this._rootEl) throw 'rootEl must be specified';
@@ -54,10 +58,7 @@
_initializeAttributeBindings:function () {
var attributeBindingKey, inputBinding, attributeBinding, elementBindingCount, elementBinding;
- if(!this._attributeBindings){
- this._initializeDefaultAttributeBindings();
- }
- else {
+ if(this._attributeBindings){
for (attributeBindingKey in this._attributeBindings) {
inputBinding = this._attributeBindings[attributeBindingKey];
@@ -86,13 +87,24 @@
this._initializeElBindings();
}
+
+ if(!this._attributeBindings || this._options.alwaysDefaultBindings){
+ this._initializeDefaultAttributeBindings();
+ }
},
_initializeDefaultAttributeBindings: function(){
var elCount, namedEls, namedEl, name;
- this._attributeBindings = {};
namedEls = $('[name]', this._rootEl);
+ // If we're using combination of default and manual bindings, prevent manual ones from having defaults applied
+ if(this._options.alwaysDefaultBindings){
+ namedEls = _.filter(namedEls, function(namedEl){
+ var name = $(namedEl).attr('name');
+ return !(name in this);
+ }, this._attributeBindings);
+ }
+
for(elCount = 0; elCount < namedEls.length; elCount++){
namedEl = namedEls[elCount];
name = $(namedEl).attr('name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment