How can I “bubble up” events on nested Backbone collections?

后端 未结 1 1947
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 16:56

I have a Backbone app that uses nested collections (at least that\'s how I think they\'re called).

In my particular case there are tabs

相关标签:
1条回答
  • 2021-01-17 17:41

    A change event is triggered by Backbone when an attribute changes via set. The event is then also triggered on the collection, as you have seen. But, the value of your subtabs attribute is not changing at all, it is still the same object you created in defaults. If you used tab.set('subtabs', new Subtabs); you would get a change:subtabs event, but you don't want to do that.

    I think you would have to do something in your code to trigger a new event on your Tab model.

    // Tab Model
    var Tab = Backbone.Model.extend({
        defaults: { label: undefined, subtabs: new Subtabs},
        initialize: function(){
            // listen for change in subtabs collection.
            this.get('subtabs').on('change', this.subtabsChanged, this);
        },
        subtabsChanged: function(model) {
            // trigger new event.
            this.trigger('subtab:change', this, model);
        }
    });
    

    Then you could listen for the event:

    tabs.on('subtab:change', function(tab, subtab) { 
        console.log(tab.get('label'));
        console.log(subtab.get('label'));
    });
    

    This will work, I think. But I guess I am wondering why you would listen to your Tabs collection for a change in the Subtabs. In most cases, it might be better to just listen for the change event on your Subtabs collection itself.

    tab.get('subtabs').on('change', function(model){
        // do something with model, which is a Subtab.
    });
    

    EDIT: http://jsfiddle.net/phoenecke/DvHqH/1/

    0 讨论(0)
提交回复
热议问题