jQuery Chosen 在使用淘汰赛 js 时不会更新选择选项

2024-07-01

我正在努力使jQuery 选择 http://harvesthq.github.io/chosen/ and 淘汰赛 http://knockoutjs.com/同时工作。

问题是“jQuery Chosen”拒绝更新选项列表,即使我已经为其创建了自定义绑定。

这是例子 -http://jsfiddle.net/5fGAf/ http://jsfiddle.net/5fGAf/

我有两个可变的选择 - “国家”和“方法”。 “方法”选项列表取决于所选国家/地区。当我第一次选择国家时 - 一切都很完美。但是,当我想更改国家/地区时,“方法”选项列表保持不变,即使相应的淘汰计算值已更新。

如果我手动运行$(".chosen-select").trigger('chosen:updated')在浏览器控制台中 - 选项列表更新。

自定义绑定代码:

ko.bindingHandlers.chosen = {
  init: function(element) {             
    $(element).chosen({disable_search_threshold: 10});
  },
  update: function(element) {
    $(".chosen-select").trigger('chosen:updated');
  }
};

你有两个问题:

  • 你的小提琴里没有.chosen-select所以你的update函数没有找到select但无论如何你应该使用$(element)访问当前绑定的元素
  • in KO 3.0 绑定独立触发 http://knockoutjs.com/upgrade-notes/v3.0.0.html#bindings-are-now-refreshed-independently。因为你的chosen绑定未连接到您的可观察数组update当您更改该数组时不会触发。

您可以通过显式声明对options绑定在您的自定义绑定中,但更好的解决方案是委托给它:

ko.bindingHandlers.chosen = {
    init: function(element)  {
        ko.bindingHandlers.options.init(element);
        $(element).chosen({disable_search_threshold: 10});
    },
    update: function(element, valueAccessor, allBindings) {
        ko.bindingHandlers.options.update(element, valueAccessor, allBindings);
        $(element).trigger('chosen:updated');
    }
};

并在您通常使用的地方使用它options捆绑:

<select id="option1" class="form-control" 
    data-bind="chosen: payoutOptions, 
               optionsText: 'optionText', 
               optionsValue: 'optionValue', 
               value: activePayoutOption"></select>

Demo JSFiddle http://jsfiddle.net/VxMqV/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery Chosen 在使用淘汰赛 js 时不会更新选择选项 的相关文章

随机推荐