3

我现在正在测试用于双向数据绑定的骨干stickit。有没有办法恢复更改,例如,在通过表单编辑模型数据时,用户按下取消按钮,如下图所示

在此处输入图像描述

当我们在表格中输入时,模型似乎是即时更改的。我想要的是当用户按下取消按钮时,模型将恢复到其原始值。

我读到了 updateModel ,它需要一个真实的值来确认模型更新。但是,我的编辑视图 [cancel-event] 如何触发updateModel 函数的错误值,以便模型不会使用文本字段值更新。

我需要像全局变量这样的东西吗?

//global variable
var updateModelTitle = true;

//backbone stickit bindings
  bindings: {
    '#title': {
      observe: 'title',
      updateModel: 'confirmUpdate'
    }
  },
  confirmUpdate: function(val, event, options) {
    return updateModelTitle;
  }

//cancel button event click event
updateModelTitle = false;

提前感谢您的帮助。

4

3 回答 3

2

试试 Backbone.Stickit 的姊妹项目:Backbone.trackit

于 2015-06-15T14:24:53.147 回答
0

这是我对这个问题的解决方案。我没有在骨干stickit config上做任何事情。如果用户单击取消按钮,我所做的是使用模型 ID 并从 restful 服务器获取原始数据。然后使用来自服务器的数据通过stickit 2方式绑定恢复模型更改。

    canceledit: function() {
        var modelIndex = this.model.get('index');
        var modelId = this.model.get('id');

        this.$el.fadeOut(500, function() {

            var fetchTask = new App.Models.Task({ id: modelId });

            fetchTask.fetch({
                wait: true,
                success: function(model, response, options) {
                    var title = model.get("title");
                    var task = App.Collections.tasksCollection.at(modelIndex);
                    task.set({title : title});
                },
                error: function(model, response, options) {
                    console.log('An error occured while fetching the data...');
                }
            });

            this.remove();
        });
    }

如果您有不需要从服务器获取数据以通过主干网恢复模型更改的解决方案,请发布您的答案。stickit

更新 - 基于杰克建议的第二个解决方案 - 没有 REST 调用

//create global variable for model collection index and title properties
App.Global.modelTaskCurrentTitle = "";
App.Global.modelTaskIndex = -1;

//in edit view render function
//capture info needed
App.Global.modelTaskIndex = this.model.get('index');
App.Global.modelTaskCurrentTitle = this.model.get('title');

//in cancel function for edit-view
//or any view that need to remove edit-view to prevent zombie-edit-view
//and also reverting model changes by stickit in edit-view

//revert stickit changes
var task = App.Collections.tasksCollection.at(App.Global.modelTaskIndex);
task.set({title : App.Global.modelTaskCurrentTitle});

//remove edit view
App.Views.editTaskView.remove();
于 2015-06-15T12:42:21.437 回答
0

我会用

bindings: {
  '#title': {
    observe: 'title',
    event: ['change']
    updateModel: function(val, event, options) {
      if (val)
        return val;
    }
  }
}

<form>
<input id="title" type="text">
<button type="Cancel" data-action="destroy-view">
<button type="submit">OK</button>
</form>

所以模型属性只会在提交时改变。

于 2015-06-20T16:29:01.950 回答