Backbone.js 集合更新插入? [英] Backbone.js collection upsert?

查看:15
本文介绍了Backbone.js 集合更新插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Backbone.js 构建一个应用程序.我的一些服务器端 API 将返回自特定时间以来所有新的或更改的模型.其中一些对象可能是我收藏的新对象,因此我可以添加它们.其他人可能已经存在,在这种情况下,我想更新现有模型.所以基本上我正在寻找 upsert(更新或插入)功能.

I'm building an app with Backbone.js. Some of my server-side APIs will return me all the new or changed models since a particular time. Some of those objects may be new to my collection so I can just add them. Others may already exist, in which case I'd like to update the existing model. So basically I'm looking for upsert (update-or-insert) functionality.

这类似于 0.9.0 中添加的 {add:true} 选项,只是我也想更新.

This is similar to the {add:true} option that was added in 0.9.0, except that I also want updating.

有没有一种简单/已知的方法来做到这一点?更新代码似乎并不难,但我不想重新发明轮子.

Is there an easy/known way to do this? It doesn't seem hard to update the code, but I don't want to reinvent a wheel.

推荐答案

注意:此答案是为 Backbone v0.9 编写的.从那时起,Backbone v1.0 发布了,其中包含了描述 collection.set() 方法这里.这可能是一个更好的解决方案.

NOTE: This answer was written for Backbone v0.9. Since then Backbone v1.0 has released, which contains the collection.set() method described here. That will likely be a better solution.

我在周末拼凑了我自己的版本.我会把它放在这里以防其他人找到这个线程,但我仍然很高兴看到可能存在的任何其他解决方案.

I threw together my own version of this over the weekend. I'll put it up here in case anybody else finds this thread, but I'd still be happy to see any other solutions that might be out there.

我通过修改 Backbone.js 源代码做到了这一点,这不一定是个好主意,但很容易.有两个变化,首先将这个函数添加到 Backbone.Collection 原型中:

I did this by modifying the Backbone.js source, which is not necessarily a great idea, but it was easy. There were two changes, first add this function to the Backbone.Collection prototype:

//**upsert** takes models and does an update-or-insert operation on them
//So models that already exist are updated, and new models are added
upsert: function (models, options) {
    var self = this;
    options || (options = {});
    models = _.isArray(models) ? models.slice() : [models];


   var addModels = [];
    _.each(models, function (newModel) {
        var n = self._prepareModel(newModel, options);
        var existingModel = self.get(n.id);
        if (existingModel) {
            existingModel.set(n, options);
        } else {
            addModels.push(n);
        }
    });

    if (!_.isEmpty(addModels)) {
    self.add(addModels, options);
    }
}

然后将Backbone.Collection.fetch()函数中的一行修改为:

Then modify one line in the Backbone.Collection.fetch() function to read:

collection[options.add ? 'add' : (options.upsert ? "upsert" : 'reset')](collection.parse(resp, xhr), options);

这允许您调用 fetch({upsert:true}) 来获取我正在寻找的行为.

This allows you to call fetch({upsert:true}) to get the behavior I was looking for.

这篇关于Backbone.js 集合更新插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆