动态更改 KNOCKOUT .js 中单击绑定的处理程序



我得到了以下绑定,就像一个魅力:

<button class="flatButton buttonPin" data-bind="click:EnterPinMode">Add pin</button>

在我的视图模型中,我像这样定义处理程序:

self.EnterPinMode = function(data,event)
{
    //Doing several things here
    //....
}

现在,假设我想在第一次单击该按钮后更改该按钮的行为......我该怎么做?我已经很容易地更改按钮文本:

self.EnterPinMode = function(data,event)
{
    //Doing several things here
    //....
    var curButton = $(event.target);
    curButton.text("Cancel");
}    

但是更改按钮行为呢?如果我通过 jQuery 设置了这个处理程序,那将不是问题,但是有没有办法"替换"该控件上的单击绑定,以便现在它将调用ExitPinMode处理程序。鉴于 KNOCKOUT 仅适用于声明性绑定(至少没有插件......),我对这是否可行有一些怀疑,但我认为值得一问。

请注意,我

实际上需要某种 3 种切换方式,为了示例,我只是将其简化为"正常"切换。

我认为使用视图模型专用的hasBeenClicked标志很好,并且可能是最好的解决方案。

如果你真的想换掉处理程序,这应该很容易,不过,像这样:

function enterPinMode() {
    //Doing several things here
    //....
    var curButton = $(event.target);
    curButton.text("Cancel");
    //set click handler to a step 2 function
    self.pinAction = exitPinMode;
}
function exitPinMode() {
    //....
}
self.pinAction = enterPinMode;

也许最简单的解决方案之一是添加一个布尔值,例如在开头设置为 false,然后将其设置为 true。

例:

  self.hasBeenClicked  = false;
  self.EnterPinMode = function(data,event)
  {
   if (!self.hasBeenClicked )
     {
      var curButton = $(event.target);
      curButton.text("Cancel");
      self.hasBeenClicked = true;
     }
   else
     {
       //behaviour an a second click
     }
  }    

希望对您有所帮助!

你可以

试试这个

var vm = function () {
    var self = this;
    var nextState = 'firstState';
    var states = {
       firstState: function () {
           nextState = 'secondState';
           //Do stuff
       },
       secondState: function () {
           nextState = 'thirdState';
           //Do stuff
       },
       thirdState: function () {
           nextState = 'firstState';
           //Do stuff
       }
   }
   self.EnterPinMode = function () {
       states[nextState].call();
   }
}

关于 MVVM,您应该首先记住的是,您正在设计一个对象来表示您的视图。如果您的视图将具有不同的状态,那么让您的视图模型了解这些状态并知道在什么状态下该做什么并没有错。坚持使用 MVVM。你不会失望的。

最新更新