Backbone.js: Changing view.attributes does not affect view.el

I have a skeleton view similar to

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 that I am facing is that when I change the hash of the attributes view, it does not affect el ,

So, I should do something like this this.el = this.make(this.tagName,this.attributes,''); so that changes are reflected.

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

+4
source share
2 answers

To automate everything that you are trying to do when your model changes, you need to bind the method to the model change event. In your initialization method, you need something like:

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

and then define this method later in your view:

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

Now, anytime the model associated with this view changes the updateElement method.

+1
source

You just overwrite the view el property, which I think is not what you want. As you can see below, the make function does not attach the newly created element to the DOM, so it will not appear and the old element will not be removed from the page.

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:

 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; }, 
+1
source

Source: https://habr.com/ru/post/1399635/


All Articles