Knockout.js与多个Select2绑定 [英] Knockout.js binding with multiple Select2

查看:141
本文介绍了Knockout.js与多个Select2绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是什么时候我将我的Select2与具有Knockout View模型的Multiple绑定在一起。选择其中一个选项后,数据将第二次丢失

My Question is when ever I bind my Select2 with Multiple with Knockout View Model. After selecting one of the options, the data is lost for the second time

KnockOutCode

KnockOutCode

$(window).load(function () {

ko.bindingHandlers.select2 = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor(),
            lookupKey = allBindings.lookupKey;
        $(element).select2(obj);
        if (lookupKey) {
            var value = ko.utils.unwrapObservable(allBindings.value);
            $(element).select2('data', ko.utils.arrayFirst(obj.data.results, function (item) {
                return item[lookupKey] === value;
            }));
        }

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

ko.applyBindings(new ViewModel());
function ViewModel() {
    var self = this;

    self.MetricsModel = ko.observableArray([]);

    GetMetrics();

    function GetMetrics() {
        $.ajax({
            url: '/Admin/GetMetrics',
            type: "POST",
            dataType: "json",
            success: function (returndata) {
                self.MetricsModel(returndata);
            },
            error: function () {
                alert("eRROR GET Applications");
            }
        });
    };

}
$("#application-select-metrics").select2();    
}    

HTML文件

    <select multiple="multiple" id="application-select-metrics" class="form-control" data-bind="options: MetricsModel, optionsText: 'Metrics_Name', OptionsValue:'Metrics_ID', optionsCaption: 'Choose...', select2: {}"></select>
@*<select multiple="multiple" id="application-select-metrics" class="form-control">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>*@

请注意评论的部分,即硬编码值工作,它允许我选择多个值,并使用Knockout它第一次工作,我得到一个列表填充,但在选择一次后,第二次数据丢失。

Please note that the commented sections, i.e, hardcoded values works, and it allows me to select multiple values, and using Knockout it works for the first time, i get a list populated, but after selecting once, for the second time the data is lost.

请帮忙,

谢谢,

编辑:
如上所述通过Hanes,我编辑了代码,并引入了自定义绑定,但它仍然不起作用,我不认为自定义绑定的更新部分工作正常,因为下拉填充一次但无法第二次绑定。任何帮助都将很高兴。

As mentioned by Hanes, I've edited the code, and introduced custom binding, but still it does not work, I dont think the update section of the custom binding is working properly,as the drop down populate once but fails to bind for the second time. Any help would be gladly appreciated.

推荐答案

@rniemeyer不久前把它扔到一个JSFiddle上,可以帮助你:

@rniemeyer threw this up on a JSFiddle not too long ago that should help you out:

http://jsfiddle.net/rniemeyer/R8UF5/

在更新值时使用以下绑定和几个小提琴:

Use the following binding combined with a couple fiddles for when a value is updated:

ko.bindingHandlers.select2 = {
  init: function(element, valueAccessor, allBindingsAccessor) {
    var obj = valueAccessor(),
      allBindings = allBindingsAccessor(),
      lookupKey = allBindings.lookupKey;

    setTimeout(function() { 
      $(element).select2(obj);
    }, 0);

    if (lookupKey) {
      var value = ko.utils.unwrapObservable(allBindings.value);
      $(element).select2('data', ko.utils.arrayFirst(obj.data.results, function(item) {
        return item[lookupKey] === value;
      }));
    }

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

这篇关于Knockout.js与多个Select2绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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