【问题标题】:Listen in Backbone view to nested Backbone Relational model events在 Backbone 视图中侦听嵌套的 Backbone 关系模型事件
【发布时间】:2013-12-05 11:41:50
【问题描述】:

假设我有一个代表人群的 Backbone Relational 模型 - 它有一个相关的 People 集合,每个模型类型都是 Person:

CrowdModel = Backbone.RelationalModel.extend({
     relations: [{
        type: Backbone.HasMany,
        key: 'People',
        relatedModel: 'PersonModel',
        collectionType: 'Backbone.Collection'
     }]
});

每个人都有一个相关的孩子集合,一个孩子也是模型类型的人:

PersonModel = Backbone.RelationalModel.extend({
    relations: [{
        type: Backbone.HasMany,
        key: 'Children',
        relatedModel: 'PersonModel',
        collectionType: 'Backbone.Collection'
    }]
});

现在,在我看来,我想在任何模型上收听更改事件 - 我们称之为“Hungry”。

CrowdView = Backbone.View.extend({
    initialize: function () {
        this.listenTo(this.model.get("People"), 'change:Hungry', this.hungryChange);
    },
    hungryChange: function(model, val, options) {
       if(val) console.log("Somebody's hungry!");
    }
});

如果任何人饿了,这将触发,但我正在寻找一种方法来监听任何孩子的饥饿事件。有什么办法可以把它冒泡吗?

jsfiddle 在这里:http://jsfiddle.net/fnj58/1/

抱歉,这个人为的例子 - 这确实与表示复选框树的模型有关,但这种方式更容易描述。

【问题讨论】:

    标签: backbone.js backbone-relational


    【解决方案1】:

    你应该从 Person 中冒泡事件。

    在 CrowdView 初始化函数中为 childHungry 添加处理程序

    CrowdView = Backbone.View.extend({
              ....
      initialize: function () {
        this.listenTo(this.model.get("People"), 'childHungry', function(){
          console.log("Someone's child is hungry");
        });// listening to child hungry
        this.listenTo(this.model.get("People"), 'change:Hungry', this.hungryChange);
      },
    });
    

    人物模型应该倾听他的孩子并触发他有一个饥饿的孩子

    PersonModel = Backbone.RelationalModel.extend({
          .... 
      initialize: function(){
        this.listenTo(this.get("Children"), 'change:Hungry', this.childHungry);
      },
      childHungry: function(){
        this.trigger("childHungry");
      }
    

    顺便说一下:如果你不想让 Crowd 区分一个孩子饿了还是一个人饿了,你也可以只触发 change:Hungry 上面的 childHungry 函数并保持你的 versiono CrowdView (见http://jsfiddle.net/fnj58/2/

    【讨论】:

    • 如此简单。谢谢。我过去使用过全局 events.trigger,甚至没有意识到您可以从模型触发自定义事件,所以也感谢您向我敞开心扉!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多