自定义绑定到可观察数组而不调用更新函数 [英] Custom bind to observable array not calling update function

查看:46
本文介绍了自定义绑定到可观察数组而不调用更新函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个非常简单的绑定:

I have this very simple binding:

ko.bindingHandlers.chosen = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        console.log("INIT");
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        console.log("IT WORKS!");
    }
};

用于选择:

<select data-bind="
        options: Options,
        chosen: Options
    "></select>

选项声明为:

this.Options = ko.observableArray(opt1);

并在必要时更新,如下所示:

And updated, when necessary, like this:

this.Options(newValues);

然而,IT WORKS被记录只有一次(当呈现选择列表时)并且再也不会。请参见此jsfiddle 。尝试按重新加载按钮:更新数组,重新呈现选择列表(耶!)但不调用自定义更新功能(不!)。我甚至试图强制 .valueHasMutated 但没有成功。

However, "IT WORKS" gets logged only one time (when the select list is rendered) and never again. See this jsfiddle. Try to press the "reload" button: the array is updated, the select list re-rendered (yay!) but the custom update function isn't called (nay!). I even tried to force .valueHasMutated but with no success.

我需要更新功能才能正常工作。为什么不发生这种情况?

I need the update function to work properly. Why isn't this happening?

推荐答案

由于您没有使用 valueAccessor,因此没有发生这种情况更新功能。如果您使用它,您将获得更新函数触发:

It isn't happening because you don't use valueAccessor in update function. If you used it you would get update function fired:

ko.bindingHandlers.chosen = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        console.log("INIT");
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = ko.unwrap(valueAccessor());
        console.log("IT WORKS!");
    }
};

这是更新的小提琴: http://jsfiddle.net/wzTg4/8/

这篇关于自定义绑定到可观察数组而不调用更新函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆