2

在主干模型中,对于嵌套视图,是否可以在初始化函数中触发事件?我基于此示例的当前代码:https ://stackoverflow.com/a/8523075/2345124并已将其更新为骨干网 1.0.0。这是我的初始化函数,用于模型:

var Edit = Backbone.Model.extend({
    initialize: function() {
        this.trigger('marquee:add');

        this.on('change', function(){
            this.trigger('marquee:add');
        });
    }
    ...
}

我正在尝试在模型初始化时调用方法 renderMarquee:

var EditRow = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.model, "change", this.render);   // works
        this.listenTo(this.model, "marquee:add", this.renderMarquee);  // only called when changed, but not when initially created
    ...
}

renderMarquee在模型更改时调用,但在初始化时不调用'change' 事件按预期工作(调用 this.render)。有什么想法吗?

谢谢!

4

2 回答 2

1

我目前面临类似的问题。我需要在模型的初始化方法中触发更改事件。我查看了主干代码,它揭示了为什么没有发生这种情况:

var Model = Backbone.Model = function(attributes, options) {
    ...
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments); 
  };

在和清空set之前执行将模型状态设置为“没有任何变化”。initializethis.change

为了覆盖行为,我将以下代码添加到我的初始化方法中。

initialize: function(attributes, options) {
  ...
  this.changed = attributes;
  this.trigger('change');
  for (attr_name in attributes) {
    this.trigger('change:' + attr_name);
  }
},

我手动触发所有更改事件,这对我来说很重要,因为继承模型可能会绑定到changeor change:attrxy。但这还不够,因为如果我只是触发事件,该changedAttributes()方法将返回,false因此我还设置this.changed了当前属性。

于 2014-06-25T13:38:52.737 回答
0

This doesn't make a lot of sense because you are initializing the model somewhere prior to doing the view.listenTo call. Unfortunately, you don't really have a choice in that matter.

You are probably going to want to move the event handling to a Backbone.Collection which already has built in events you can listen on for adding/removing.

于 2013-05-03T00:07:32.960 回答