KnockoutJS - 点击事件后的数据绑定

时间:2017-12-22 14:58:56

标签: knockout.js knockout-2.0 knockout-mvc

我想在点击事件后更新First#或Second#文本。 当我从输入字段中聚焦时,它现在更新。

这是a link

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

1 个答案:

答案 0 :(得分:1)

使用observables的重点是跟踪你的变化:例如,在更改输入时,文本会发生变化等。

如果您不想进行此自动跟踪,则需要使用一些临时变量来存储输入值并在click事件中手动更改您的observable:

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);
   };
 };

并将输入字段绑定到这些临时变量:

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

演示:JSFiddle