Search code examples
marionette

Backbone.View.remove in a Marionette application


To destroy a Backbone view, you would call its remove method, but in a Marionette application, the views provide a new destroy method which does the same, but also takes care of removing child views. Does this mean the remove method should never be used on Marionette views?


Solution

  • Looking at the source, we can see that Marionette view destroy() method internally calls Backbone remove() method. Calling remove() will delete the dom element and unbind events, but Marionette destroy() is more powerful and does a lot more plumbing, like destroying behaviors and etc. So in Marionette apps you should only use destroy().

      destroy: function() {
        if (this.isDestroyed) { return this; }
    
        var args = _.toArray(arguments);
    
        this.triggerMethod.apply(this, ['before:destroy'].concat(args));
    
        // mark as destroyed before doing the actual destroy, to
        // prevent infinite loops within "destroy" event handlers
        // that are trying to destroy other views
        this.isDestroyed = true;
        this.triggerMethod.apply(this, ['destroy'].concat(args));
    
        // unbind UI elements
        this.unbindUIElements();
    
        this.isRendered = false;
    
        // remove the view from the DOM
        this.remove();
    
        // Call destroy on each behavior after
        // destroying the view.
        // This unbinds event listeners
        // that behaviors have registered for.
        _.invoke(this._behaviors, 'destroy', args);
    
        return this;
      },