避免“fetch()”将模型属性标记为已更改

Avoid `fetch()` marking model attributes as changed

本文关键字:属性 记为 模型 fetch 避免      更新时间:2023-09-26

我在用户设置配置文件表单中使用Backbone。我获取模型并将其信息呈现到表单中。当我保存模型时,将发送所有参数,而不是用户更改的参数。

首先,我获取模式并将其呈现在视图上:

// Fetch model and render on view
user = new User({ id: 123 });
user.fetch().done(function () {
    view.render();
});

当用户更改字段时,我使用"set()"方法更新了模型:

"change .email": function () {
    this.model.set("email", this.email.val());
}

稍后在视图代码中,我保存在单击事件上(使用 patch: true):

"click .save": function () {
    console.log(this.model.changedAttributes());  // Shows all the model attributes
    this.model.save({ patch: true }); // Sends all the model attributes
 }

如何避免在用于初始化模型fetch后更改主干标记?

这个技巧将解决你的问题:

model.fetch({context:model}).done(function () {
  this.set({});
  view.render();
});