5

我正在尝试使用自定义绑定显示通知 DIV,同时还通过 2 个 observables 调整该 DIV 的 CSS 和 HTML。

问题是,当我更改这两个可观察对象的值时,它也会出于某种原因触发自定义绑定。

模板:

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

4

1 回答 1

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

于 2013-06-06T15:50:50.467 回答