Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind events to DOM after initialize function in backbone?

I have backbone view that binds an action to an element in the DOM. The problem is that the DOM element hasn't been rendered when the events is called. My code looks like this:

  // Change the focus to a full goal view
  var GoalFullView = Backbone.View.extend({

    // Bind the goal full view
    el: $("#main"),

    // Events for making changes to the goal
    events: {
      "keypress #goal-update": "createOnEnter",
    },

    // Cache the template for the goal full view
    template: _.template($("#goal-full-template").html()),

    // Render the goal full and all of its goal updates
    initialize: function() {
      this.render();
      this.collection = new GoalUpdateList;
      this.collection.bind('add', this.addOne, this);
      this.collection.bind('reset', this.addAll, this);

      this.collection.fetch();
    },

As you can see, the event binding occurs before the initialization so it cannot locate the DOM element because it hasn't been rendered. How can I delay the event binding until after initialize?

Edit 1: Hmm, I do a console log, and it prints something out on a keypress, but I am getting this message in my Chrome's developer console:

Uncaught TypeError: Cannot call method 'apply' of undefined

What does this mean?

like image 531
egidra Avatar asked Oct 24 '22 03:10

egidra


1 Answers

As I expected the problem is in another place.

The DOM events binding declaration can be done before the DOM element real exists.

I think this code example reproduces the situation you are talking and still the DOM event is binded correctly.

var View = Backbone.View.extend({
  events: {
    "click #link": "click"
  },

  click: function(){
    console.log( "click event" );
  },

  render: function(){
    this.$el.html( "<a href='#' id='link' onclick='return false'>link</a>" );
  }
});

new View({ el: "body" }).render();​

Check the jsfiddle example code

like image 74
fguillen Avatar answered Nov 01 '22 09:11

fguillen