Only just started learning Backbone so this is probably me completely misunderstanding a core concept.
The code below is from my View object and there's a few things I don't understand...
Why the CSS change in highlightHero function isn't working. If I do a
console.log(this.$el.children(".playerIcon"))
afterwards I can see in the outerHTML property that the appropriate style has been added to the object but it hasn't made the change to the element in the DOM.
Why if I insert a deliberate syntax error at the bottom of highlightHero the whole thing works perfectly, albeit throwing an exception aswell.
.
initialize: function(){
this.model.on('change', this.render, this);
this.model.on('change:isHero', this.highlightHero, this);
},
events: {
'click .playerIcon': 'toggleHero'
},
toggleHero: function(){
this.model.toggleHero();//This just toggles a boolean
},
highlightHero: function(){
if(this.model.get('isHero')==true)
{
this.$el.children(".playerIcon").css("background-image", "url('/imgs/user-red.png')");
console.log(this.$el.children(".playerIcon"))
}
else
{
this.$el.children(".playerIcon").css("background-image", "url('/imgs/user.png')");
}
},
Any explanation greatly appreciated.
highlightHero
is being called successfully after the change:isHero
event and applying the CSS class which is reflected in the DOM. However, then the change
event is fired, causing the View to re-render without the CSS applied, and it's too quick to notice. If you add a syntax error, the change
event won't be called since the application crashed.
To resolve this, I suggest calling highlightHero
in your render function and deleting the change:isHero
event.