主干模型.save()会终止所有与事件的绑定

Backbone Model.save() kills all bindings to events

本文关键字:事件 绑定 终止 模型 save      更新时间:2023-09-26

我一直在一个新项目中使用Backbone,到目前为止我很喜欢它,但我遇到了一个似乎无法绕过的障碍。

在不试图解释我的整个域模型的情况下,我发现当你保存一个模型时,响应会从服务器返回并再次被解析,从而创建新的子对象,从而破坏我之前在对象上设置的事件绑定。

例如,如果我在ContentCollection从服务器返回时保存它(它是一个主干。模型而不是集合),则会解析响应并在this.contentItems中创建一个新的集合,这会破坏我在this.contentItems上的所有绑定。有什么办法绕过这个吗?告诉主干网不要以某种方式解析响应?从原始列表中提取绑定,然后将它们重新附加到新列表?

App.ContentCollection = Backbone.Model.extend({
    urlRoot: '/collection',
    initialize: function() {
    },
    parse: function(resp, xhr) {
        this.contentItems = new App.ContentList(resp.items)
        this.subscriptions = new App.SubscriptionList(resp.subscriptions)
        return resp
    },
    remove: function(model){
        this.contentItems.remove(model)
        this.save({'removeContentId':model.attributes.id})
    },
    setPrimaryContent: function(model){
        this.save({'setPrimaryContent':model.attributes.id})
    }
})

以前有人碰到过这个吗?

我认为这里的问题是使用parse()方法的方式。Backbone只是希望此方法接收服务器响应并返回属性的哈希-而不是以任何方式更改对象。因此,Backbone在save()中调用this.parse(),并不期望有任何副作用——但按照覆盖.parse()的方式,在调用函数时会更改模型。

我过去处理这个用例的方法是在第一次调用fetch()时初始化集合,类似于:

App.ContentCollection = Backbone.Model.extend({
    initialize: function() {
        this.bind('change', initCollections, this);
    },
    initCollections: function() {
        this.contentItems = new App.ContentList(resp.items);
        this.subscriptions = new App.SubscriptionList(resp.subscriptions);
        // now you probably want to unbind it,
        // so it only gets called once
        this.unbind('change', initCollections, this)
    },
    // etc
});