The biggest problem I have with backbone is that I never seem to grasp how "el" works. I feel like I truly do know how it is supposed to work, but it always seems to give me trouble.
Why is this.$el undefined in this codepen example?
http://codepen.io/anon/pen/gPdyvj?editors=0010
the html:
<div class="wrapper">
<div class="todo-container">
<h1>To Do List</h1>
<input type="text" class="new-todo-box">
<button class="test">test</button>
<div class="todo-list">
</div>
</div>
</div>
the javascript
var TodoView = Backbone.Collection.extend({
el: '.todo-container',
events: {
'click .test': 'handleEnter'
},
handleEnter: function(){
console.log("hello world test. ")
},
initialize: function(){
this.render();
},
render: function(){
console.log("hello")
//this.$el is undefined
console.log(this.$el)
//so this does not work.
this.$el.html("testing $el")
}
});
$(document).ready(function(){
new TodoView();
});
I don't get it because I am defining what the el element is using the class name. I am pretty sure I have used it like this in the past. I feel like I never know when el is going to work correctly. The events are also not firing and I think it is related to el not being set correctly.
Here's the problem:
var TodoView = Backbone.Collection.extend({ // });
You are trying to make a "View" extending from a collection, and a collection don't have the attribute $el, instead of that, you must do:
var TodoView = Backbone.View.extend({ // });