Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: Why isn't this event bound?

Tags:

I have a simple todo list, and all is rendering as expected, but when I click on the submit button in the edit form, the form is submitted (GET /todo_items), and the page is reloaded an only shows the edit form. The "submit form" event isn't being bound and I can't figure out why. What am I missing?

App.Views.Edit = Backbone.View.extend({   events: {     "submit form": "save"   },   initialize: function(){     this.render();   },   save: function(){     var self = this;     var msg  = this.model.isNew() ? 'Successfully created!' : 'Saved!';      this.model.save({       title: this.$('[name=title]').val(),        success: function(model, resp){         console.log('good');         new App.Views.Notice({message: msg});         self.model = model;         self.render();         self.delegateEvents();         Backbone.history.saveLocation('todo_items/'+ model.id);         $('#edit_area').html('');       },       error: function(){         console.log('bad');         new App.Views.Error();       }     });      return false;   },   render: function(){     $('#edit_area').html(ich.edit_form(this.model.toJSON()));   } }); 

Here's the edit form:

<script id="edit_form" type="text/html">   <form>     <label for="title">Title:</label>     <input name="title" type="text" value="{{title}}" />     <button>Save</button>   </form> </script> 
like image 878
Matt Darby Avatar asked Feb 05 '11 20:02

Matt Darby


1 Answers

Backbone uses delegateEvents on the el element. If you do not specify "el" or do not use "el" to render your view, the event delegation will not work. Instead of doing

$("#edit_area")  

within your render, pass it as the "el" option in the constructor:

edit = new App.Views.Edit({el: $("#edit_area")}) 

Refer to it as this.el everywhere in your view code, especially in your render.

like image 69
Julien Avatar answered Sep 19 '22 15:09

Julien