Gautam
Gautam

Reputation: 7958

Backbone.js : Changing view.attributes does not reflect on view.el

I have a backbone view like so

 window.InputView = Backbone.View.extend({
        tagName:'input',
        className:'',
        attributes:{},
        initialize:function(){
            this.attributes=this.model.attributes;
            this.el = this.make(this.tagName,this.attributes,'');
        }
    });

The problem I am having is that When I modify the attributes hash of the View it does not reflect on the el,

So I have to do something like this this.el = this.make(this.tagName,this.attributes,''); for the changes to reflect .

Is this the only way , or is there a better way to do it ? like automate it ?

Upvotes: 4

Views: 7136

Answers (2)

ryanmarc
ryanmarc

Reputation: 1680

To automate whatever you're trying to do when your model changes you need to bind a method to the change event of the model. In your initialize method you'd need something like:

initialize: function() {
    this.model.on("change", updateElement);
    ...
}

and then define that method later on in your view:

updateElement: function() {
    //use this.model.attributes to update your el
}

Now, anytime the model associated to that view changes the updateElement method will run.

Upvotes: 1

biziclop
biziclop

Reputation: 14596

You are simply overwriting the view's el property, which is not what you want, I think. As you see below, the make function does not attach the freshly created element to the DOM, so it won't appear, AND the old element is not removed from the page.

A possible way to fix it:

initialize: function(){
  this.attributes = this.model.attributes; // why are you doing this anyway? :)
  var $oldEl = this.$el; // backbone 0.91
  var newEl = this.make(this.tagName,this.attributes,'');
  $oldEl.after( newEl ); // the old element must be in the DOM, when doing this!
  $oldEl.remove();
  this.setElement( newEl ); // proper setup
}

Quotes from BackBone's source:

make: function(tagName, attributes, content) {
  var el = document.createElement(tagName);
  if (attributes) $(el).attr(attributes);
  if (content) $(el).html(content);
  return el;
},

setElement: function(element, delegate) {
  this.$el = $(element);
  this.el = this.$el[0];
  if (delegate !== false) this.delegateEvents();
  return this;
},

Upvotes: 1

Related Questions