除了最初之外,是否可以触发自定义绑定更新? [英] Possible to fire custom binding update except initially?

查看:16
本文介绍了除了最初之外,是否可以触发自定义绑定更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个:

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

每次 observable 更改时都会触发警报,但在首次评估绑定时也会触发.除了最初之外,如何在每次更改时触发警报?

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?

推荐答案

这里有一个方法:保留一个元素数组,如果 update 不存在它的元素(这是第一次它运行),否则执行任何操作.由于您有一个自定义绑定处理程序,您可以将数组挂在它上面.

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>

这篇关于除了最初之外,是否可以触发自定义绑定更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆