2016-11-08 70 views
2

我有按鈕「取消」。點擊我應該顯示確認對話框,詢問用戶是否真的想丟失填充的數據(如果他做了一些更改),並且只是隱藏表單以防他沒有做出更改。Combine 2 Knockout指令與類似的邏輯

我有變量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 --> 

我已經表明證實的保存有一定的變化......但在這裏我已經錯過了案件情況時,沒有改變和取消按鈕用戶點擊(對我來說沒有任何反應)。

那麼我怎麼能結合2個指令 - click(沒有變化的情況下)和toggleClick(如果有一些變化的情況下)?

感謝。

回答

1

您可以簡單地在單擊事件上具有單個功能,然後在功能比較內部有需要詢問的變化。

下面是一個簡單的例子: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()); 
+1

是的,這似乎是最簡單的解決方案。日Thnx – demo