22

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>
Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
Matt Darby
  • 6,294
  • 4
  • 27
  • 35

2 Answers2

25

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.

Julien
  • 9,216
  • 4
  • 37
  • 38
  • Thank you for this answer, so `$('#edit_area').html("blah");` won't work. How can I set the html of an element without having to render the whole view? – Doug Molineux Sep 17 '13 at 18:49
0

After many hours of monkeying with this, it worked after I explicitly set el on the view, and used$(this.el) in the render function. Weird.

Matt Darby
  • 6,294
  • 4
  • 27
  • 35