可能会触发自定义绑定更新(最初除外)? [英] Possible to fire custom binding update except initially?

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

问题描述

比方说我有这个:

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?

推荐答案

这里是一种方法:保留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天全站免登陆