Possible to fire custom binding update except initially?

情到浓时终转凉″ 提交于 2019-11-28 10:38:57

问题


Let's say I have this:

ko.bindingHandlers.test= {
    update: function (element, valueAccessor) {
        alert("Test");
    }
};

The alert fires every time an observable is changed, but also initally when the binding is first evaluated. How can I make the alert fire on every change except initially?


回答1:


Here's one way: keep an array of elements that the update populates with its element if it's not there (which is the first time it runs) and otherwise does whatever action. Since you've got a custom binding handler, you can just hang the array off of that.

ko.bindingHandlers.test = {
  update: function(element, valueAccessor) {
    var seenElements = ko.bindingHandlers.test.seen,
      val = valueAccessor()();
    if (seenElements.indexOf(element) >= 0) {
      alert("Test");
    } else {
      seenElements.push(element);
    }
  }
};
ko.bindingHandlers.test.seen = [];

var vm = {
  alertOn: ko.observable(0),
  raiseAlert: function() {
    vm.alertOn.notifySubscribers();
  }
};
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="test:alertOn"></div>
<button data-bind="click:raiseAlert">Update</button>



回答2:


How can I make the alert fire on every change except initially?

Knockout will call the update callback initially when the binding is applied to an element and track any dependencies (observables/computeds) that you access. When any of these dependencies change, the update callback will be called once again.

I don't think it is possible to fire only by changes and not in initially.

You can create a workaround to fit with your scenario by adding change event tied up with your element inside init.

init: function(element, valueAccessor) {
   // element should be the element you want to attach change event.
   $(element).on('change', function (value)
   {
      // do your stuff.
    });
}


来源:https://stackoverflow.com/questions/31985620/possible-to-fire-custom-binding-update-except-initially

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!