gpt4 book ai didi

javascript - Knockout unwrap observable 无法按预期工作

转载 作者:行者123 更新时间:2023-12-02 15:08:53 26 4
gpt4 key购买 nike

我已经制作了一个图标自定义绑定(bind),如果我这样做,它就可以正常工作

<div data-bind="icon: 'icon-name'"></div>

我希望图标是可变的,因此在我的 View 模型中我有:

var element = {
icon: ko.computed(function() {
return 'icon-' + iconType();
}
}

在我的 html 中我有:

<div data-bind="icon: ko.utils.unwrapObservable(icon)"></div>

但这不起作用。请注意,如果我像这样之前插入另一个 div:

<div data-bind="text: ko.utils.unwrapObservable(icon)"></div>

我得到了一个 div,其名称与我想要的图标名称完全相同,可以说“icon-1”。
所以我的猜测是 unwrapObservable 没有给我所需格式的文本。

有什么想法可以解决这个问题吗?

图标绑定(bind):

ko.bindingHandlers.icon = {
init: function(element, valueAccessor) {
var icon = ko.unwrap(valueAccessor());
$(element).html(icons[icon]);
}
}

最佳答案

您需要处理 update 而不是 init ,当值发生变化时,计算结果会发生这种情况:

ko.bindingHandlers.icon = {
update: function(element, valueAccessor) {
var icon = ko.unwrap(valueAccessor());
$(element).html(icons[icon]);
}
}

然后您应该能够正常绑定(bind),而无需在绑定(bind)中包装值:

<div data-bind="icon: icon"></div>

关于initthe documentation说:

Knockout will call your init function once for each DOM element that you use the binding on. There are two main uses for init:

  1. To set any initial state for the DOM element
  2. To register any event handlers so that, for example, when the user clicks on or modifies the DOM element, you can change the state of the associated observable

IE 这里不需要,你可以通过 update 完成你需要的一切。

关于javascript - Knockout unwrap observable 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34924672/

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