突然之间,以下代码在针对 KnockoutJS 3.0 时不再有效。我该如何解决这个问题?
JavaScript:
ko.bindingHandlers.limitCharacters = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel)
{
element.value = element.value.substr(0, valueAccessor());
allBindingsAccessor().value(element.value.substr(0, valueAccessor()));
}
};
HTML:
<textarea data-bind="value: comment, valueUpdate: 'afterkeydown', limitCharacters: 20"></textarea>
参见 fiddle :http://jsfiddle.net/ReQrz/1/
最佳答案
在 KO 3.0 中,绑定(bind)是独立且有序的。您可以阅读更多相关信息 here ,这应该被认为是一个“重大变化”,来自上面的链接示例:
v2.x’s behavior about dependencies between bindings (described in the section about “Independent and ordered bindings” above), is an undocumented internal implementation detail so hopefully you aren’t relying on it. But if you are relying on that then obviously you will see a change of behavior because bindings are independent in v3 by design. You’ll need to stop relying on cross-binding dependencies, which by the way will make your code much cleaner and easier to understand.
因此您的绑定(bind)不再有效,因为它假设当您的 comment
属性发生更改时,它也会触发您的 limitCharacters
绑定(bind)到您的 limitCharacters
绑定(bind)与 comment
属性无关。
解决此问题的一种可能解决方案是,您需要通过使用 allBindingsAccessor() 访问其值,在
:update
处理程序中显式声明对 value
绑定(bind)的依赖.value();
ko.bindingHandlers.limitCharacters = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel)
{
var val = allBindingsAccessor().value();
allBindingsAccessor().value(val.substr(0, valueAccessor()));
}
};
演示 JSFiddle .
关于javascript - 自定义绑定(bind)在 KnockoutJS 3.0 中不再有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110433/