Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

knockout.js - Possible to fire custom binding update except initially?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...