0

我的应用程序中有非常复杂的表单,具有更新功能,用户可以只更改几个字段,单击保存按钮将数据提交到服务器。我的应用程序使用主干、syphon、JQuery 和 underscoreJs。

仅使用这些可在我的应用程序中的多个页面使用的库来控制可以将哪些字段发送到服务器的最佳方法是什么?诸如可重用功能之类的东西会有所帮助。

我已经尝试过model.changedAttributes()似乎没有按预期工作的功能。大多数时候,它返回错误。我有以下代码,其中表单数据使用 siphon 进行序列化,然后将转换为我的应用程序特定格式以发送到 API。

formSave: function(e) {
    var data = changeToWriteApiFormat(Backbone.Syphon.serialize($(e.currentTarget).closest('form.event_form')[0]));
    this.model.clear();
    this.model.id = this.parentObj.model.id;

    this.model.set(data);

    if (this.model.isValid(true)) {
      this.model.save(removeObjIndexCollection(data), {
          url: this.model.url().replace(gc.readApiUrl, gc.publishApiUrl),
          patch: true,
          beforeSend: ToolsHelper.setPublishHeader,
          success: function(model, response) {
            $('#event_success').show();
            $('#event_failure').hide();
          },
          error: function(model, response) {
            $('#event_failure').show();
            $('#event_success').hide();
          }

        }
      }
4

1 回答 1

0

model.changedAttributes() 仅在您之前在 this.model 上设置了一些属性时才有效,但是因为您通过 this.model.clear(); 清除了它们;它会返回假。

此外,只有在 validate 返回有效时才会执行“保存”,您不必额外调用 isValid。

“patch:true” 属性是正确的,但只有在您设置了以前的值时才会起作用。

尝试这个:

formSave: function(e) {
    var data = changeToWriteApiFormat(Backbone.Syphon.serialize($(e.currentTarget).closest('form.event_form')[0]));

        this.parentObj.model.save(removeObjIndexCollection(data), {
           url: this.model.url().replace(gc.readApiUrl, gc.publishApiUrl),
           patch: true,
           beforeSend: ToolsHelper.setPublishHeader,
           success : function(model, response) {
               $('#event_success').show();
               $('#event_failure').hide();
           },
           error : function(model, response) {
               $('#event_failure').show();
               $('#event_success').hide();
           }

         }
}

编辑:这里是changedAttributes的一个例子:

var model = new Backbone.Model();

model.set({
    val1 : 'init',
    val2 : 'init'
});

// .. whatever

var newChangesFromForm = {
    val2 : "changed",
    val1 : 'init' // won't be set, because it's the same value
};
model.on('change', function() {
    var changes = model.changedAttributes();

    alert(JSON.stringify(changes));
});
model.set(newChangesFromForm);
于 2016-05-20T11:23:59.860 回答