在敲除自定义绑定中,您如何知道哪个值触发了更新? [英] In a knockout custom binding, how do you know which value is triggering the update?

查看:43
本文介绍了在敲除自定义绑定中,您如何知道哪个值触发了更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

B"H

我正在开发一个基于剔除js的旧项目. 我正在尝试创建一个用于select2的自定义绑定,但是我遇到了一堵砖墙,试图找出哪些属性(值)发生了变化.

I am working on an old project based on knockout js. I am trying to create a custom binding (for select2), but I am running into a brick wall trying to figure out which attributes (values) are the ones that changed.

即我如何知道选项列表是否刚刚更改?还是所选的值?

i.e how do I know whether the list of options have just changed? Or the selected value?

如果值列表刚刚更改,那么我需要重构select2,将control值设置为null(否则默认情况下选择第一项).如果用户只是在列表中选择了一个项目,那么我真的不想做任何事情.绝对不重建整个控件或将控件值设置为null.但是我找不到任何方法可以查看哪些值已更改.

If the list of values have just changed then I need to reconstruct the select2, an set the controls value to null (otherwise the first item is selected by default). If the user just selected an item in the list, then I don't really want to do anything. Definitely not reconstruct the entire control or set the controls vale to null. But I can not find any way to see which values have changed.

推荐答案

在淘汰赛中每个可观察到的都具有订阅方式,所以如果您具有

Each observable in Knockout has subscribe methood, so if u have

var myProp = ko.observable();

u可以订阅此道具的更改,并在那里做所有必要的事情:

u can subscribe for changes of this prop and do all nessesary things there:

myProp.subscribe(function(newValue){
  console.log("value of prop changed to " + newValue);
});

我们确实通过以下方式为jquery选择的插件实现了自定义选择绑定:

We did implement custom select binding for jquery chosen plugin in following way:

    ko.bindingHandlers.chosen =
    {
    init: function (element, valueAccessor, allBindings) {
        var values = valueAccessor(),
            $element = $(element);
        $element.chosen(ko.toJS(values));

        if (ko.isObservable(values.enable)) {
            values.enable.subscribe(function (value) {
                $element.prop('disabled', !value).trigger("chosen:updated");
            });
        }

        // trigger chosen:updated event when the bound value or options changes

        ['value', 'selectedOption', 'options'].forEach(function (e) {
            var bv = allBindings.get(e);
            if (ko.isObservable(bv))
                bv.subscribe(function () { $(element).trigger('chosen:updated'); });
        });

        var prop = allBindings.get('value');
        $element.off('change');
        $element.on('change', function (obj, event) {
            if (!event || !prop) {
                return;
            }
            if (typeof (prop()) == "number" && !isNaN(Number(event.selected))) {
                prop(Number(event.selected));
            } else {
                prop(event.selected);
            }
        });
    },
    update: function (element) {
        $(element).trigger('chosen:updated');
    }
};

这篇关于在敲除自定义绑定中,您如何知道哪个值触发了更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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