I am using backbone.js to create a View which contains a Like button. The model of this View contains the attribute is_liked, and if its value is 1, then the function setStateLike called will change the style of the Like button.
Problem: I am not able to select the button using this.setStateLike() in the initialize function. Doing so just returns a []. However, when I define this.setStateLike as a click event handler, selecting the button works! The stranger thing is that this.setStateLike() called within initialize is able to select $(this.el), but not $(this.el).find()!
Any idea what has happened here and how can it be fixed? Thanks!
PhotoListItemView = Backbone.View.extend({
tagName: 'div',
className: 'photo_box',
events: {
'click': 'setStateLike'
},
initialize: function() {
this.setStateLike();
},
render: function() {
$(this.el).html( this.template( this.model.toJSON() ) );
return this;
},
setStateLike: function() {
console.log( $(this.el).find('#like') ); // returns []
if(this.model.get('is_liked')) {
console.log( $(this.el) ); // returns correctly
console.log( $(this.el).find('#like') ); // returns []
// Change icon to Active state
$(this.el).find('#like.photo_btn').addClass('photo_btn_active').attr('id', 'unlike');
}
}
});
If your script comes before the bulk of the body HTML and if the
initializefunction is being called immediately, that’s your issue: the DOM isn’t actually built yet, so no elements can be selected. Either run the script at the end of the</body>, or use jQuery’s DOM-ready handler.