2

I'm new to Backbone and trying to do some examples, but I'm stuck with this one. I have the below BackBone View:

CommentBoxView = Backbone.View.extend({
    initialize: function () {
        this.render();
    },
    render: function () {
        var template = _.template( $("#comment_box_template").html(), {} );
        this.el.html(template);
    },
    events: {
        "keypress textarea": "doKeyPress"
    },
    doKeyPress: function (event) {
        console.log(event);
    }
});

Everything's running ok but if I replace

this.el.html(template);

with this:

this.el = $(template).replaceAll(this.el);

The keypress event is not fired at all. Could anyone please explain to me why it happened and how to make this code works? Thank you all very much.

VinhBS
  • 677
  • 8
  • 17

1 Answers1

6

Backbone uses the view's delegateEvents method to bind a jQuery delegate call to the view's el, this delegate is what handles all the view's events. If you do this:

this.el = $(template).replaceAll(this.el);

you lose the delegate bound to this.el and your events go with it. You'll also end up with your this.$el not matching this.el and that's not good either. The proper way to change a view's el is to use setElement:

setElement view.setElement(element)

If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

So you should be able to do it like this:

this.setElement($(template).replaceAll(this.el));
mu is too short
  • 426,620
  • 70
  • 833
  • 800