Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone JS View Events not Firing?

I'm trying to play around with Backbone JS and so far everything seems to be making sense and working smoothly.

However with the code below, my custom events do not seem to be firing. Anything in the below code stand out as to why that might be? Do I need to "initialize" anything in the View? Any other pointers on the code/structure would be cool as well. Below is my full JS/HTML.

JS

var Todo = Backbone.Model.extend({});  var TodoCollection = Backbone.Collection.extend({      model: Todo,     url: '/Home/Todos'  });  var AppView = Backbone.View.extend({      // where it should listen, required?     el: $(".content"),      events: {         "keypress #new-todo": "enter"     },      initialize: function () {         // _.bindAll(this, "render", "createOnEnter");         // this.collection.bind("all", this.render);     },      hi: function () {         alert('ohai');     },      render: function () {         var lis = '';         $.each(this.collection.models, function () {             lis += '<li>' + this.get('Text') + '</li>';         });         $('#todo-list').append(lis);         return this.el;     },      enter: function (e) {         alert('hi');     }  });   var TodoController = Backbone.Controller.extend({      routes: {         "": "todos"     },      initialize: function (options) { },      todos: function () {         var todolist = new TodoCollection();         todolist.fetch({             success: function (data) {                 var appview = new AppView({ collection: data });                 appview.render();             }         });     }  });  $(function () {     window.app = new TodoController();     Backbone.history.start(); }); 

HTML

<div id="todoapp">     <div class="content">         <input id="new-todo" placeholder="What needs to be done?" type="text" />         <div id="todos">             <ul id="todo-list">             </ul>         </div>         <a href="#">say hey</a>     </div> </div> 
like image 744
aherrick Avatar asked Apr 28 '11 23:04

aherrick


2 Answers

el: $(".content") 

Try this:

var appview = new AppView({ el:$(".content"), collection: data }); 

You cannot call a jQuery there because the DOM is not yet created. You must do it when the view is loaded either as my example or in the initialize.

like image 167
Julien Avatar answered Sep 16 '22 14:09

Julien


Additionally, for your events to work, you must bind your content in the render function to this.el. Events are all bound to the element you specify, so it follows that you need to have your event-generating elements bound as children to the element which acts as the delegator.

like image 20
Jess Jacobs Avatar answered Sep 16 '22 14:09

Jess Jacobs