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

10,729

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.

Share:
10,729

Related videos on Youtube

Matt Darby
Author by

Matt Darby

I've developed on the web for 17 years. I can configure pools of servers, architect and develop the applications on those servers, and make it all look good (and run). I am a Professor at Franklin University, hold a Master's in Computer Science and I lead 500 members of the Columbus Ruby Brigade. I've launched projects for folks from Rackspace, AT&T, Sprint, LivingSocial and SeoMoz to local engineering and consulting firms. I currently work at Rackspace as a Developer Advocate. It rules.

Updated on February 09, 2020

Comments

  • Matt Darby
    Matt Darby about 4 years

    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>
    
  • Matt
    Matt about 13 years
    Could you clarify / post your answer? Thanks!
  • LeRoy
    LeRoy almost 13 years
  • Doug Molineux
    Doug Molineux over 10 years
    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?