demo demo - 10 months ago 44
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

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

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

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 -
(for case with no changes) and
(for case when there are some changes) ?


Answer Source

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 :


<form data-bind="visible:ShowForm">
  <input type="text" data-bind="textInput:Input">
  <input type="button" value="Cancel" data-bind="click:CancelForm">

<div data-bind="text:Status">



 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.CancelForm = function(){
          self.Status("there is a change that needs to be asked the user");
            self.Status("there is no change so the form got hidden")
 ko.applyBindings(new MainViewModel ());