Search code examples
javascriptbackbone.js

Backbone - What is the best way to listen to 2 models?


I'm working on a project and I was curious as to what is the best way to listen to 2 objects that are used in the same function?

For example:

this.model1 = someModel();
this.model2 = someModel();

this.listenTo(this.model1, "sync", this.someFunction); // how can I get listenTo to listen for both changes before calling the function?
this.listenTo(this.model2, "sync", this.someFunction);

someFunction: function() {
    this.sumValue = (this.model1.get('value') + this.model2.get('value));
}

Thanks for your help!


Solution

  • Create a base model and inherit from your other models:

        var DataModel = Backbone.Model.extend({
            // ToDo
        });
    
        var FileModel = DataModel.extend({
            // ToDo
        });
    
        var FolderModel = DataModel.extend({
            // ToDo
        });
    

    Make the model type of the collection same base model:

        var DataCollection = Backbone.Collection.extend({
            model: DataModel
        });