简体   繁体   English

清除ko observable时清除select2 div

[英]Clear select2 div when the ko observable is cleared

I am having the following ko select2 binding: 我有以下ko select2绑定:

ko.bindingHandlers.select2 = {
    init: function (element, valueAccessor) {
        $(element).select2(valueAccessor());

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).select2('destroy');
        });
    }
};

Following is my input with select2 binding: 以下是我对select2绑定的input

<input type="text" class="form-control" data-bind="value: $root.Name, attr: { 'placeholder': 'Full Name' }, select2: { minimumInputLength: 1, query: $root.list_item, allowClear: true, multiple: true}">

Everything is working perfectly fine. 一切工作正常。 The problem I am facing is when I am clearing the Name observable through a Clear button, the values selected by the select2 div are not getting cleared. 我面临的问题是,当我通过“ Clear按钮清除“可观察到的Name ,不会清除由select2 div选择的值。 What change I have to do in the select2 ko binding to reflect the changes in the UI when the observable is cleared? 在清除observable时,我必须在select2 ko绑定中进行哪些更改以反映UI中的更改?

When Name is cleared, knockout clears also the value attribute of the input element. 清除Name后,敲除功能还将清除输入元素的value属性。

select2 plugin does not track this and does not update its inner value. select2插件不会对此进行跟踪,并且不会更新其内部值。 One solution is, in the custom binding handler, to subscribe to the value binding and clear select2 when the value is empty: 一种解决方案是,在自定义绑定处理程序中,订阅值绑定并在值为空时清除select2

ko.bindingHandlers.select2 = {
    init: function (element, valueAccessor, allBindings) {
        $(element).select2(valueAccessor());
        // if a value binding exists, subscribe to it 
        // to clear the select2 plugin when the value is empty
        var valueBindingAccessor = allBindings.get('value');
        if(valueBindingAccessor) {
            valueBindingAccessor.subscribe(function(val) {
                if(val == '') {
                    $(element).select2("val", "");
                }
            });
        }
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).select2('destroy');
        });
    }
}; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM