Search code examples
knockout.jsknockout-2.0knockout-mvc

KnockoutJS - Data Binding After Click Event


I would like to update the First# or Second# text after click event. It's now update when I focus out from input fields.

Here's a link.

function ViewModel () {
    self.this;
    self.var1 = ko.observable(50);
    self.var2 = ko.observable(60);
....
}
var vm = new ViewModel();
ko.applyBindings(vm);

Solution

  • The whole point of using observables is to track the changes for you: e.g when changing the input the text changes etc.

    If you don't want this automatic tracking you need to use some temporary variable to store the input values and change your observables manually in the click event:

    function ViewModel() {
       var self = this;
       self.var1 = ko.observable(50);
       self.var2 = ko.observable(60);
       self.temp1 = ko.observable(self.var1())
       self.temp2 = ko.observable(self.var2())
    
       this.addition = function() {
         self.var1(Number(self.temp1()));
         self.var2(Number(self.temp2()));
    
         this.var3 = self.var1() + self.var2();
         alert("Addition is = " + this.var3);
       };
     };
    

    And bind your input fields to these temporary variables:

    <p>First #: <span data-bind="text: var1"> </span></p>
    <p>Sectond #: <span data-bind="text: var2"> </span></p>
    
    <p>Enter first #:
      <input data-bind="value: temp1" />
    </p>
    <p>Enter second #:
      <input data-bind="value: temp2" />
    </p>
    <p>
    
    <button type="submit" data-bind="click: addition">Click here for addition</button>
    </p>
    

    Demo: JSFiddle.