demo demo - 1 month ago 14
jQuery Question

Combine 2 Knockout directives with similar logic

I have button "Cancel". On click on which I should show confirmation dialog to ask if user realy want to lost filled in data (in case he made some changes), and just hide form in case he didn't make changes.

I have variable

canSave
, which helps to detect if there are some changes on form.

cancel
- method, which just clear all data and hide form.

This is what I've tried, but this didn't do anything.

<button data-bind="click: canSave ? function(){openConfirmation(!openConfirmation());} : cancel" type="reset" class="btn btn-default">Cancel</button>


Initial Code :

<button data-bind="toggleClick: openConfirmation" type="reset" class="btn btn-default">Cancel</button>


toggleClick
is custom directive to change toggle some boolean variable.

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


I've showed confirmation in save there are some changes... But here I've missed case case when no changes and user click on Cancel button (in my case nothing happens).

So how can I combine 2 directives -
click
(for case with no changes) and
toggleClick
(for case when there are some changes) ?

Thanks.

Answer

You can simply have a single function on click event and then inside the function compare if there is a change that needs to be asked.

Here is a simple example : 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 ());