我有“取消”按钮。单击它我应该显示确认对话框以询问用户是否真的想要丢失填写的数据(以防他进行了一些更改),并且只是隐藏表单以防他没有进行更改。
我有变量canSave
,它有助于检测表单是否有一些变化。
cancel
- 方法,仅清除所有数据并隐藏表单。
这是我尝试过的方法,但没有任何效果。
<button data-bind="click: canSave ? function(){openConfirmation(!openConfirmation());} : cancel" type="reset" class="btn btn-default">Cancel</button>
初始代码:
<button data-bind="toggleClick: openConfirmation" type="reset" class="btn btn-default">Cancel</button>
toggleClick
是自定义指令,用于更改切换某些 bool 变量。
<!-- ko if: canSave -->
<confirmation-modal class="delete-confirm-popup" params="showDialog : openConfirmation, bodyHtml: 'Your changes will not be saved.<br/> Do you want to continue?', confirmCallBack: cancel"></confirmation-modal>
<!-- /ko -->
我在保存时显示了确认,有一些更改...但在这里我错过了没有更改并且用户单击“取消”按钮的情况(在我的情况下没有任何反应)。
那么我如何组合 2 个指令 - click
(对于没有更改的情况)和 toggleClick
(对于有一些更改的情况)?
谢谢。
最佳答案
您可以简单地在单击事件上使用一个函数,然后在函数内部比较是否需要询问更改。
这是一个简单的例子:https://jsfiddle.net/kyr6w2x3/110/
HTML:
<form data-bind="visible:ShowForm">
<input type="text" data-bind="textInput:Input">
<input type="button" value="Cancel" data-bind="click:CancelForm">
</form>
<div data-bind="text:Status">
</div>
JS:
var MainViewModel = function() {
var self = this;
self.Input = ko.observable();
self.Status = ko.observable();
self.ShowForm = ko.observable(true);
self.canSave = ko.observable(false);
self.Input.subscribe(function(newValue){
if(newValue){
self.canSave(true);
}
})
self.CancelForm = function(){
if(self.canSave()){
self.Status("there is a change that needs to be asked the user");
}else{
self.ShowForm(false);
self.Status("there is no change so the form got hidden")
}
}
};
ko.applyBindings(new MainViewModel ());
关于javascript - 结合具有相似逻辑的 2 个 Knockout 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40493029/