用相似的逻辑组合2个Knockout指令

Combine 2 Knockout directives with similar logic

本文关键字:2个 Knockout 指令 组合 相似      更新时间:2023-09-26

我有一个"取消"按钮。点击它,我应该显示确认对话框,询问用户是否真的想要丢失填写的数据(如果他做了一些更改),只是隐藏表单,以防他没有做更改。

我有变量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是一个自定义指令来改变一些布尔变量的开关。

 <!-- 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 -->

我已经在保存中显示了一些更改的确认…但是这里我忽略了大小写,当没有更改,用户点击取消按钮(在我的情况下什么都没有发生)。

那么我如何结合两个指令- click(没有变化的情况下)和toggleClick(当有一些变化的情况下)?

谢谢。

你可以简单地为click event设置一个函数,然后在函数内部比较是否需要进行更改。

下面是一个简单的例子: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 ());