WordPress 5.3: Backbone Upgrade Guide

In WordPress 5.3, the version of Backbone bundled with WordPress will be updated from v1.3.3 to v1.4.0. Developers who override on and off events on their models may run into a few issues if they have listenTo events being applied to them.

Consider the example below:

// Model
class Model extends Backbone.Model {
    initialize() {
        this.collection = new Backbone.Collection()
    }

    on() {
        this.collection.on.apply( this.collection, arguments )
    }

    off() {
        this.collection.off.apply( this.collection, arguments )
    }
}

// View
class View extends Backbone.View {
    initialize() {
        this.listenTo( this.model, 'event-name', null )
    }
}

// Create an instance of Model and View
const model = new Model()
new View( { model } )

// Remove callbacks from model
model.off();

A TypeError will now be thrown at model.off, as when the model’s callbacks are removed, Backbone attempts to remove the set of listeners applied to the model as well. These sets of listeners are no longer on the model, but instead are on the model’s collection.

The reason for this is because Backbone now uses the listened object’s public on method when applying the listenedTo event, and in the example above, the on event will be applied to model.collection. A simple fix to this error is to instead pass model.collection as the object to be listened to.

For a full list of changes in this release, see the Backbone Changelog. For reference on this update, see the Trac ticket #47478.

Props @adamsilverstein and @desrosj for peer review.

#5-3, #dev-notes, #external-libraries