javascript Knockout.js 与多个 Select2 绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21131064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout.js binding with multiple Select2
提问by Ronak Jain
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
我的问题是当我将 Select2 与 Multiple with Knockout View Model 绑定时。选择其中一个选项后,数据第二次丢失
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 File
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>*@
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.
请注意,注释部分,即硬编码值有效,它允许我选择多个值,并且第一次使用 Knockout 时,我填充了一个列表,但是选择一次后,第二次数据是丢失。
Please help,
请帮忙,
Thanks,
谢谢,
EDIT: 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.
编辑:正如 Hanes 所提到的,我已经编辑了代码,并引入了自定义绑定,但它仍然不起作用,我不认为自定义绑定的更新部分工作正常,因为下拉填充一次但无法绑定第二次。任何帮助将不胜感激。
回答by crockpotveggies
@rniemeyer threw this up on a JSFiddle not too long ago that should help you out:
@rniemeyer 不久前在 JSFiddle 上提出了这个问题,应该可以帮助你:
http://jsfiddle.net/rniemeyer/R8UF5/
http://jsfiddle.net/rniemeyer/R8UF5/
His fiddle, updated
他的小提琴,更新
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');
}
};
回答by Hans Roerdinkholder
First, in response to the comments: your code was correct. The JSFiddle done by Jeroen introduced the error in the mocked ajax call: he returned an array of ints, not of objects with the correct attributes. The problem only occurs when the select2 is applied.
首先,回应评论:您的代码是正确的。Jeroen 完成的 JSFiddle 在模拟的 ajax 调用中引入了错误:他返回了一个整数数组,而不是具有正确属性的对象。该问题仅在应用 select2 时出现。
Cause
原因
You're applying select2, but select2 is not playing nice with Knockout. And why should it? It doesn't know anything about Knockout and your viewmodel, and it doesn't know how to play nice with it.
您正在应用 select2,但 select2 与 Knockout 的配合不佳。为什么要这样做?它对 Knockout 和您的视图模型一无所知,也不知道如何使用它。
Solution
解决方案
You need a knockout custom binding for the select2 control. A knockout custom binding is theway to create integration between your Knockout code and 3rd party plugins. To write and explain such a custom binding for you would be a bit too much for this answer, so instead I'll give you the following link: https://github.com/ivaynberg/select2/wiki/Knockout.js-Integration
您需要一个用于 select2 控件的剔除自定义绑定。淘汰赛自定义绑定是在您的淘汰赛代码和 3rd 方插件之间创建集成的方式。为你编写和解释这样的自定义绑定对于这个答案来说有点太多了,所以我会给你以下链接:https: //github.com/ivaynberg/select2/wiki/Knockout.js-Integration
There's a solution that will help you fix the problem. They also link to a JSFiddle, and all in all you should be able to find all you need there. If this one is too complex for you, you might try googling 'select2 knockout custom binding' and see if you can find something less complex.
有一个解决方案可以帮助您解决问题。它们还链接到 JSFiddle,总而言之,您应该能够在那里找到所需的一切。如果这个对你来说太复杂了,你可以尝试谷歌搜索“select2淘汰赛自定义绑定”,看看你是否能找到不那么复杂的东西。
A reference to the concept of Knockout custom bindings: http://knockoutjs.com/documentation/custom-bindings.html
对 Knockout 自定义绑定概念的引用:http: //knockoutjs.com/documentation/custom-bindings.html
Good luck!
祝你好运!