In a knockout custom binding, how do you know which value is triggering the update?

扶醉桌前 提交于 2019-12-24 07:45:25

问题


B"H

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?

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.


回答1:


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

var myProp = ko.observable();

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);
});

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');
    }
};


来源:https://stackoverflow.com/questions/50788706/in-a-knockout-custom-binding-how-do-you-know-which-value-is-triggering-the-upda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!