KnockoutJS自定义绑定多次触发

时间:2013-06-06 15:37:07

标签: knockout.js knockout-2.0

我正在尝试使用acustom绑定显示通知DIV,同时还通过2个可观察对象调整DIV的CSS和HTML。

问题 是当我更改这两个observable的值时,它也会因某种原因触发自定义绑定。

模板:

<div class="alert top-alert" data-bind="fade: topMessageShow, css: topMessageType, html: topMessage"></div>

自定义处理程序:

ko.bindingHandlers.fade = {
  update: function resolveFade(element, valueAccessor, allBindingsAccessor) {
    if (ko.utils.unwrapObservable( valueAccessor() )) {
      $(element).hide().delay(300).fadeIn('slow');
    } else {
      // fade out the notification and reset it
      $(element).fadeOut('slow', function() {
        // reset those 2 observables that set class and HTML of the notification DIV
        MyClass.topMessageType('');
        MyClass.topMessage('');
      });
    }
  }
};

触发代码:

MyClass.topMessageType('alert-info');
MyClass.topMessage(msg);
MyClass.topMessageShow(true);

JSFiddle: http://jsfiddle.net/UrxXF/1/

1 个答案:

答案 0 :(得分:3)

这与所有绑定在一个元素上一起发生的事实有关。以下是描述当前行为的帖子:http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html。这实际上在KO 3.0中发生了变化,其中绑定在元素上独立维护。

您现在可以使用的一个选择是在computed函数中设置自己的init,如:

ko.bindingHandlers.fade = {
  init: function resolveFade(element, valueAccessor, allBindingsAccessor) {
      ko.computed({
         read: function() {
             /your logic goes here
         },
         disposeWhenNodeIsRemoved: element
      });
  }
};

使用这种技术,您可以模拟update函数,但允许它独立于元素上的其他绑定。唯一的小缺点是,您当前不会从绑定字符串中展开的可观察对象中获取任何依赖项(例如fade: topMessageShow()而不是fade: topMessageShow)。

相关问题