javascriptbackbone.jsbackbone-viewsbackbone-eventsweebly

Destroy event, or linking external DOM item to Backbone model


I'm creating a drag & drop element for Weebly. Weebly wraps each element in a Backbone JS view, as explained here.

// My js file. PlatformElement is a Weebly-controlled object exposed to me.
PlatformElement.extend({
    initialize: function() {
        // Weebly calls this method automatically at element creation time.
        // This is where I add a new menu item to an external navigation menu.
    }
});

When the Backbone view is initialized, I add a new DOM node to an external navigation menu. My issue begins here: when my model is destroyed, the DOM node I've created persists.

Weebly destroys/recreates the view each time a user re-configures my element in the web designer interface. My external menu node doesn't get destroyed because it's not part of the model, and my JS doesn't have awareness of the destory event to manually remove the menu node.

Of course, that means each change to my element creates another duplicate menu nodes.

Question:

  1. Is there an event Weebly exposes to me, or native Backbone functionality exposes to me, to let me know that my model is being destroyed?
  2. Or, is there a way to "link" my external menu node to my model so that when my model is destroyed, so is the menu node?

Solution

  • Backbone does provide ways to listen to events happened to Backbone object (Model, View, Collection, ...). To listen to destroy event of a model, you could:

    const model = new Model({/*...*/});
    
    // solution 1
    model.on('destroy', () => console.log('model is destroyed'));
    
    // soluction 2
    const view = new View({/*...*/});
    view.listenTo(model, 'destroy', () => console.log('model is destroyed'));
    
    model.destroy(); // this will trigger two callbacks above