jQuery Chosen在使用剔除js时不会更新选择选项 [英] jQuery Chosen doesn't update select options while working with knockout js

查看:273
本文介绍了jQuery Chosen在使用剔除js时不会更新选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作 jQuery选择

I am trying to make jQuery Chosen and KnockoutJS work at the same time.

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

The problem is "jQuery Chosen" refuses to update options list even though I've created custom binding for it.

以下是示例- http://jsfiddle.net/5fGAf/

我有两个可更改的选择-国家"和方法". 方法"选项列表取决于所选的国家.当我第一次选择国家/地区时,一切都完美.但是,当我想更改国家/地区时,即使更新了相应的剔除计算值,方法"选项列表也保持不变.

I have two changeable selects - "Country" and "Method". "Method" options list depends on country selected. When I select the country for the first time - everything works perfect. But when I want to change the country - "Method" options list remains the same, even though corresponding knockout computed value is updated.

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

If I manually run $(".chosen-select").trigger('chosen:updated') in the browser console - options list updates.

自定义绑定代码:

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)访问当前绑定的元素
  • KO 3.0绑定被独立触发.因为您的chosen绑定未连接到您的可观察阵列,所以您更改该阵列时update不会触发.
  • in your fiddle there is no .chosen-select so your update function does not find the select but anyway you should use $(element) to access the currently bound element
  • in KO 3.0 bindings are fired independently. Because your chosen binding is not connected to the your observable array your update won't fire when you change that array.

您可以通过在自定义绑定中显式声明对options绑定的依赖性来解决此更新"问题,但更好的解决方案是将其委派给它:

You can solve this "update" problem with explicitly declaring a dependency on the options binding in your custom binding but a better solution would be to delegate to it:

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绑定的地方使用它:

And use it where you would normally use the options binding:

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

演示 JSFiddle .

这篇关于jQuery Chosen在使用剔除js时不会更新选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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