Search code examples
knockout.jslogical-operatorsknockout-mvc

How to change click event of button


I'm trying to change click event of button. It is possible or not. I want to check button text it text is "Save" then save event call else if text is "Update" then update event call.

Here JSFIDDLE

View

 <input type="button" data-bind="click: $root.save ,value: Save" />

ViewModel

function AppViewModel() {
    var self = this;
    self.Save = ko.observable("Save");

    self.save = function () {
        self.Save("Update");  
    }

    self.update = function () {
        alert('click');
        //change button text here       
    }
}

ko.applyBindings(new AppViewModel());

Solution

  • You could try using single function for both actions:

    <input type="button" data-bind="click: $root.doAction ,value: Save" />
    
    self.doAction = function () {
      if (self.Save() == "Update") {
        self.Save("Save");
      } else if (self.Save() == "Save") {
        self.Save("Update");
      }
    }
    

    http://jsfiddle.net/norbiu/d4kkg/9/