骨干做,而不是在更新PUT POST时使用组合键 [英] Backbone does POST instead of PUT on updates when composite key is used

查看:185
本文介绍了骨干做,而不是在更新PUT POST时使用组合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用在我的模型组合键和生成ID基于我的组合键:

I'm using a composite key in my model and generate the ID based on my composite key:

app.Assignment = Backbone.Model.extend({
    idAttribute : [ 'personId', 'jobId' ],
    parse : function(resp) {
        resp.id = resp.personId + "_" + resp.jobId;
        return resp;
    }
});

但主干仍然认为分配的所有实例都是新的,allthough我从API获取它们时设置​​id的解析方法。因此骨干确实没有删除并做了POST,而不是在更新PUT。我怎样才能解决这个或什么是正确的方式来做到这一点?

but Backbone still thinks that all instances of Assignment are new, allthough I'm setting the id in the parse method when fetching them from the API. As a result Backbone does no DELETEs and does a POST instead of PUT on updates. How can I work around this or what is the "right way" to do it?

更新:

看起来像this.id更换resp.id解决了这个问题。

Looks like replacing resp.id with this.id solves the issue.

推荐答案

一Backbone.Model的解析方法的结果传递到方法,它设置的属性的模型。困惑的你,我觉得问题的关键是,该模型的ID是不是的属性之一;这是它的属性之一

The results of the parse method of a Backbone.Model are passed to the set method, which sets the attributes of the model. The point of confusion for you I think is that the model's ID isn't one of it's attributes; it's one of its properties.

那么,什么情况是这样的:

So, what happens is this:


  1. 您的原始数据从服务器回来,并传递给解析

  2. 这相同的原始数据,现在增加了一个 ID 属性,被传递到设置

  3. 设置的外观和您的 idAttribute ['PERSONID','的jobId'] )和所有的原始数据的键的

  4. 由于没有这些密钥的匹配 idAttribute ,他们没有被用作模型的ID,这样你会得到你的问题。

  1. Your raw data comes back from the server and is passed to parse
  2. That same raw data, now augmented with a id attribute, is passed to set
  3. set looks and your idAttribute ([ 'personId', 'jobId' ]) and all of the keys in the raw data
  4. Since none of those keys match the idAttribute, none of them are used as the model's ID, and thus you get your problem.

您设定的 this.id 解决方案里面解析作品,但它可能会导致问题的道路,因为解析通常设计成在它的输入(原始数据),而不是修改模型本身操作;这部分被认为接下来会发生什么,当设置被调用。一个清洁的解决办法,而不是被做类似如下:

Your solution of setting this.id inside parse works, but it might cause problems down the road because parse is generally designed to operate on it's input (the raw data), not to modify the model itself; that part is supposed to happen next when set is called. A cleaner solution would instead be to do something like the following:

app.Assignment = Backbone.Model.extend({
    // note that no idAttribute is specified, leaving it as the default "id"
    parse : function(resp) {
        resp.id = resp.personId + "_" + resp.jobId;
        return resp;
    }
}

或者,如果你想有一个不同的ID属性...

Or, if you want a different ID attribute ...

app.Assignment = Backbone.Model.extend({
    idAttribute: 'personAndJobId',
    parse : function(resp) {
        resp.personAndJobId = resp.personId + "_" + resp.jobId;
        return resp;
    }
}

这篇关于骨干做,而不是在更新PUT POST时使用组合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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