Zat*_*ter 5 knockout-2.0 knockout.js
我正在尝试使用acustom绑定显示通知DIV,同时还通过2个observable调整DIV的CSS和HTML.
该问题是,当我改变这些观测2的值,这也激发了自定义绑定,以及由于某种原因.
模板:
<div class="alert top-alert" data-bind="fade: topMessageShow, css: topMessageType, html: topMessage"></div>
Run Code Online (Sandbox Code Playgroud)
自定义处理程序:
ko.bindingHandlers.fade = {
update: function resolveFade(element, valueAccessor, allBindingsAccessor) {
if (ko.utils.unwrapObservable( valueAccessor() )) {
$(element).hide().delay(300).fadeIn('slow');
} else {
// fade out the notification and reset it
$(element).fadeOut('slow', function() {
// reset those 2 observables that set class and HTML of the notification DIV
MyClass.topMessageType('');
MyClass.topMessage('');
});
}
}
};
Run Code Online (Sandbox Code Playgroud)
触发代码:
MyClass.topMessageType('alert-info');
MyClass.topMessage(msg);
MyClass.topMessageShow(true);
Run Code Online (Sandbox Code Playgroud)
JSFiddle: http ://jsfiddle.net/UrxXF/1/
这与所有绑定在单个元素上一起触发这一事实有关。这是描述当前行为的帖子:http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html。这实际上在 KO 3.0 中发生了变化,其中绑定在元素上独立维护。
computed
您现在可以使用的一种选择是在函数中设置您自己的选择,init
例如:
ko.bindingHandlers.fade = {
init: function resolveFade(element, valueAccessor, allBindingsAccessor) {
ko.computed({
read: function() {
/your logic goes here
},
disposeWhenNodeIsRemoved: element
});
}
};
Run Code Online (Sandbox Code Playgroud)
使用这种技术,您可以模拟该update
函数,但允许它独立于元素上的其他绑定而运行。唯一的小缺点是,您当前无法从绑定字符串中解包的可观察对象获得任何依赖项(例如fade: topMessageShow()
而不是fade: topMessageShow
)。
归档时间: |
|
查看次数: |
2022 次 |
最近记录: |