Backbone.js的集合UPSERT? [英] Backbone.js collection upsert?

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

问题描述

我在建设有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添加,但我也想更新选项。

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

有一个简单/已知的方式做到这一点?它似乎并不难更新code,但我不想重新发明轮子。

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.

推荐答案

注:此答案骨干V0.9编写的。从那时起骨干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);

这允许你调用取({UPSERT:真})。来获得我一直在寻找的行为

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

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

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