当挖空更新值时不会触发更改事件

Change event doesn't trigger when Knockout updates value

本文关键字:事件 更新      更新时间:2023-09-26

我有一个外部JavaScript库,它会在文本区域的更改时触发,格式化它,等等。

但是,当 KnockoutJS 将值设置为文本区域时,不会触发更改事件。简化我的问题。当 Knockout 更新我的文本区域的值时,是否可以触发更改事件?

与其试图强制 Knockout 处理变更事件,不如在底层可观察量上设置订阅。 像这样:http://jsfiddle.net/EZC9E/1/

this.text.subscribe(function(newValue) {
    alert('Text is changing to ' + newValue);
});        

与其更改 javascript 库,不如考虑将其包装到自定义挖空绑定中。无论如何,您可能已经需要为库使用自定义绑定,尤其是在使用动态生成/销毁元素的任何foreach绑定时。

获得自定义绑定后,您有一个非常方便的位置来触发"更改"。

ko.bindingHandlers.jQueryPluginFunctionCall = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        // Apply jQuery plugin to textarea
        $(element).jQueryPluginFunctionCall();
        // Subscribe to the value binding of the textarea, and trigger the change event.
        allBindingsAccessor().value.subscribe(function () {
            $(element).trigger('change');
        });
        // Clean up jQuery plugin on dispose
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            // This will be called when the element is removed by Knockout or
            // if some other part of your code calls ko.removeNode(element)
            $(element).jQueryPluginFunctionCall('destroy');
        });
    }
}