Change event doesn't trigger when Knockout updates value

孤街浪徒 提交于 2019-12-21 07:17:45

问题


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 event isn't fired. Simplified Fiddle of my problem. Is it possible to fire the change event when Knockout updates the value of my textarea?


回答1:


Rather than trying to force Knockout to work with change events you can setup a subscription on the underlying observable. Like this: http://jsfiddle.net/EZC9E/1/

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



回答2:


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


来源:https://stackoverflow.com/questions/11134769/change-event-doesnt-trigger-when-knockout-updates-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!