Change event doesn't trigger when Knockout updates value

后端 未结 2 1913
闹比i
闹比i 2021-02-19 13:09

I have an external javascript library which triggers on the change of a textarea, formats it, etc.

However, when KnockoutJS sets the value to the textarea, the change ev

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 13:54

    Instead of changing the javascript library, you might consider wrapping it into a Custom Knockout Binding. You may already need to use a custom binding for your library anyway, especially if you're using any foreach bindings that generate/destroy elements dynamically.

    Once you've got the custom binding, you have a very convenient place to trigger 'change' from.

    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');
            });
        }
    }
    

提交回复
热议问题