我有一个外部JavaScript库,可以在更改textarea时触发,格式化等等。
但是,当KnockoutJS将值设置为textarea时,不会触发更改事件。 Simplified Fiddle of my problem。当Knockout更新我的textarea的值时,是否可以触发更改事件?
答案 0 :(得分:9)
您可以在基础observable上设置订阅,而不是尝试强制Knockout处理更改事件。像这样:http://jsfiddle.net/EZC9E/1/
this.text.subscribe(function(newValue) {
alert('Text is changing to ' + newValue);
});
答案 1 :(得分:1)
您可以考虑将其包装到自定义Knockout Binding 中,而不是更改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');
});
}
}