且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

I&QUOT如何;冒泡"嵌套骨干藏品事件?

更新时间:2023-02-12 19:11:24

A 更改事件是由骨干当通过属性的变化设置触发。该事件随后也引发了收藏,你都看到了。但是,你的子标签页属性的值是不会改变的话,那还是你在默认创建的同一个对象 。如果你使用 tab.set(子选项卡,新的子选项卡); ,你会得到一个的变化:子标签页事件,但你并不想这样做。

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.

我认为你将不得不做一些事情在你的code以触发标签模型的新事件。

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'));
});

这会的工作,我想。但我想,我想知道为什么要听你的Tabs集合在子选项卡的变化。在大多数情况下,它可能会更好,只是听你的子选项卡集合本身变化的事件。

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.
});

编辑: http://jsfiddle.net/phoenecke/DvHqH/1/