2015-06-15 63 views
3

我现在正在测试双向数据绑定的backbone骨架。有没有办法恢复的变更,例如,当通过表单编辑模型数据,用户按下取消按钮,如PIC下面backbone backbone stickit - 还原模型更改

enter image description here

似乎模型上的改变在我们输入表单时飞行。我想要的是当用户按下取消按钮时,模型将恢复到其原始值。

我读了updateModel需要一个真正的值来确认模型更新。但是怎么能我的编辑视图[取消事件]触发假值的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; 

在此先感谢您的帮助。

回答

0

这是我解决这个问题的方法。我在骨干网络配置中做任何事情。我所做的就是使用模型ID,如果用户点击取消按钮,则从宁静服务器获取原始数据。然后使用来自服务器的数据通过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(); 
     }); 
    } 

请发表你的答案,如果你有解决方案,不从服务器需要获取数据通过backbone.stickit恢复模型的变化

更新 - 基于杰克2号建议的解决方案 - 没有休息调用

//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(); 
+0

类似的东西(但避免到​​服务器之旅),如果有一些操作将视图置于* edit *模式,那么您可以做的是制作模型的本地副本,然后使用它重置你的模型,当他们按下取消,或者你做相反的事情,并通过该模型*细节/编辑*视图,当他们按保存使用,以更新您的模型。 – Jack

+0

我用你的建议编辑答案,谢谢 –

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> 

所以model属性只会在提交时才会改变。