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 initialize
d, 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:
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