Backbone的save方法不会发送未定义的属性。

3

我有以下代码:

     this.myModel.save(this.patchAttributes, {
        //Ignored if saving new record; will send a POST
        patch: true,
        success: function() {
               success();
            }
        },
        error: function() {
                error();
        }
    });

如果我的patchAttributes中有一个类似于fieldName:undefined的条目,那么我将无法在PATCH请求的请求头中看到它。

这正是应该的。由于该属性未定义,因此没有值可发送。 - Stephen Thomas
@StephenThomas,你能否给我发送一个 Backbone 文档链接,其中包含这个内容?非常感谢。 - budhavarapu ranga
2个回答

3

这是因为Backbone在发送数据之前对其进行了JSON.stringify操作。JSON规范不允许使用undefined标记。因此,任何值为undefined的属性都将被省略在JSON字符串中。

JSON.stringify({ foo: undefined });
// The output is "{}"

应该使用 null,而不是 undefined,因为 null 是 JSON 规范的一部分:

JSON.stringify({ foo: null });
// The output is "{"foo":null}"

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接