Chris Dutrow
Chris Dutrow

Reputation: 50362

Backbone View events not firing after the view is replaced, then put back on the page

Problem:

Events that are set inside a view are not firing after the view is replaced with something else using $element.html(anotherView) and then put back on the page using #element.html(theView).

Example:

var BuggyView = Backbone.View.extend({
    // Event works the at first, but not after the view is replaced, then added back
    //     onto the page
    events:{
        'click #some-element': 'on_click_some_element'
    },
    // This function gets called before the view is replaced by another view, but
    //     not after it is added back into the page the second time
    on_click_some_element:function(event){
        alert('User clicked "some element"');
    }
});

The events work after this code executes:

// Create the new view:
var buggyView = new BuggyView({});
// Add the view to the page
$element.html(buggyView.el);

This code would happen later when the view is replaced on the page with something else:

$element.html(anotherView.el);

After the view is added back onto the page, the events no longer work:

$element.html(buggyView.el);

Upvotes: 1

Views: 732

Answers (2)

Jack
Jack

Reputation: 10993

Most likely when you are removing your view you are also removing the views' bound events, You probably need to either redelgate your events. or instead of using the (jquery) .remove use .detach.

Upvotes: 1

Daniel Aranda
Daniel Aranda

Reputation: 6552

Run render after set the element of the view in the DOM:

$element.html(anotherView.el);
anotherView.render();

$element.html(theView.el);
theView.render();

Probably your issue is that the render did not run again. You are only switching the DOM assignment.

Upvotes: 1

Related Questions