Backbone.js模型事件未触发

时间:2011-11-04 02:26:37

标签: javascript backbone.js

我有以下视图文件:

var BucketTransferView = Backbone.View.extend(
{
initialize: function(args)
{
    _.bindAll(this);
    this.from_bucket = args.from_bucket;
    this.to_bucket = args.to_bucket;
},
events:
{
    'click input[type="submit"]' : 'handleSubmit',
},
render: function()
{
    $(this.el).html(ich.template_transfer_bucket(this.model.toJSON()));
    return this;
},
handleSubmit: function(e)
{
    that = this;

    this.model.save(
        {
            date: 1234567890,
            amount: this.$('#amount').val(),
            from_bucket_id: this.from_bucket.get('id'),
            to_bucket_id: this.to_bucket.get('id')
        },
        {
            success: function()
            {
                // recalculate all bucket balances
                window.app.model.buckets.trigger(
                    'refresh',
                    [that.to_bucket.get('id'), that.from_bucket.get('id')]
                );
            }
        }
    );
    $.colorbox.close();
}
});

我的存储桶集合有这种刷新方法:

refresh: function(buckets)
{
    that = this;
    _.each(buckets, function(bucket)
    {
        that.get(bucket).fetch();
    });
}

我的问题是,当fetch()发生并更改集合的模型时,它不会触发其中具有相同模型的其他视图类中的更改事件。视图的模型具有相同的cid,因此我认为它会触发。

这不会发生什么原因?

1 个答案:

答案 0 :(得分:2)

Fetch将创建新的模型对象。任何绑定到集合的视图都应绑定到集合的重置事件并重新呈现。视图的模型仍然具有相同的cid,因为它们持有对旧版本模型的引用。如果你查看buckets集合,它可能有不同的cids。

我的建议是渲染存储桶,您应该渲染所有子视图并保留对这些视图的引用。然后在重置事件上,删除所有子视图并重新渲染它们。

initialize: function()
{
    this.collection.bind('reset', this.render);
    this._childViews = [];
},

render: function()
{
    _(this._childViews).each(function(viewToRemove){
        view.remove();
    }, this);

    this.collection.each(function(model){
        var childView = new ChildView({
            model: model
        });
        this._childViews.push(childView);
    }, this)
}

我希望这适合你,或者至少让你朝着正确的方向前进。

相关问题