gpt4 book ai didi

knockout.js - KnockoutJS 自定义绑定(bind)多次触发

转载 作者:行者123 更新时间:2023-12-04 20:46:39 25 4
gpt4 key购买 nike

我正在尝试使用自定义绑定(bind)显示通知 DIV,同时还通过 2 个 observables 调整该 DIV 的 CSS 和 HTML。

问题 是当我更改这两个可观察对象的值时,它也会出于某种原因触发自定义绑定(bind)。

模板:

<div class="alert top-alert" data-bind="fade: topMessageShow, css: topMessageType, html: topMessage"></div>

自定义处理程序:
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('');
});
}
}
};

触发代码:
MyClass.topMessageType('alert-info');
MyClass.topMessage(msg);
MyClass.topMessageShow(true);

JSFiddle: http://jsfiddle.net/UrxXF/1/

最佳答案

这与所有绑定(bind)在单个元素上一起触发的事实有关。这是描述当前行为的帖子:http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html .这实际上在 KO 3.0 中发生了变化,其中绑定(bind)在元素上独立维护。

您现在可以使用的一种选择是设置您自己的 computedinit像这样的功能:

ko.bindingHandlers.fade = {
init: function resolveFade(element, valueAccessor, allBindingsAccessor) {
ko.computed({
read: function() {
/your logic goes here
},
disposeWhenNodeIsRemoved: element
});
}
};

使用这种技术,您正在模拟 update函数,但允许它独立于元素上的其他绑定(bind)运行。唯一的小缺点是您目前不会从绑定(bind)字符串中解包的可观察对象中获得任何依赖项(例如 fade: topMessageShow() 而不是 fade: topMessageShow )。

关于knockout.js - KnockoutJS 自定义绑定(bind)多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16966337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com