0

In the following fiddle: http://jsfiddle.net/3Lqsx/2088/

I've bound the second button to a function that reverses the direction of the counter.

If I click the button, the new binding doesn't apply until after I click the first button once. It should take effect immediately.

How to I force this new binding to take effect immediately?

Code:

var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);

this.registerClick = function() {
    this.numberOfClicks(this.numberOfClicks() + 1);
};

this.changeClickBinding = function() {
     $('#clicker').attr('data-bind', 'click: function(){numberOfClicks(numberOfClicks() - 1)}');
};

this.resetClicks = function() {
    this.numberOfClicks(0);
};

this.hasClickedTooManyTimes = ko.computed(function() {
    return this.numberOfClicks() >= 3;
}, this);
};

ko.applyBindings(new ClickCounterViewModel());
4

1 回答 1

0

一般来说,在调用applyBindings. 该函数是 Knockout 用来评估data-bind属性中的代码的函数。如果您之后更改它们,您将获得的行为没有定义(据我所知)。

此外,您将 jQuery 和 Knockout 混合用于 DOM 更新和事件处理,这可能会导致以后的代码混乱。Knockout 可以为您处理所有这些:

var ClickCounterViewModel = function() {
  this.numberOfClicks = ko.observable(0);
  this.clickDirection = ko.observable(1);

  this.registerClick = function() {
    this.numberOfClicks(this.numberOfClicks() + this.clickDirection());
  };

  this.changeClickBinding = function() {
    this.clickDirection(this.clickDirection() * -1)
  };

  this.resetClicks = function() {
    this.numberOfClicks(0);
  };

  this.hasClickedTooManyTimes = ko.computed(function() {
    return this.numberOfClicks() >= 3;
  }, this);
};

ko.applyBindings(new ClickCounterViewModel());

我添加了一个新的 observableclickDirection来控制计数器是递增还是递减。该changeClickBinding函数现在只是翻转该数字。

于 2013-09-22T22:35:35.330 回答