我正在使用Select2库来实现被询问的功能。
我有2个选择:第一个用于国家选择,第二个用于区域选择。 每当国家/地区选择更改为其他值时,第二个(区域)必须根据该国家/地区更新区域。
从原型区域原型制作的类中,选择我添加原始国家/地区的观察者
Event.observe(this.countrySelect, 'change', this.update.bind(this));
国家和地区选择有不同的原型类。
如果没有Select2,一切正常,捕获更改并执行更新功能。
但是当我在country select元素上初始化select2时,它只会监听select 2中的onChange事件并死掉。我可以看到原始元素上有两个听众。
尝试使用trigger,triggerHandler强制执行第二个侦听器,但不能正常工作。
有人可以给我一个想法吗?
//编辑 - 添加了更多代码
// Html
<select id="countries"></<select>
<script type="text/javascript">
new CountrySelect('#countries',jsonCountries);
</script>
<select id="regions"></select>
<script type="text/javascript">
new RegionsSelect('#regions','#countries',jsonCountriesRegions);
</script>
<script type="text/javascript">
CountrySelect = Class.create();
CountrySelect.prototype = {
initialize: function(countryElement,countries) {
// Initializations here
},
selectize: function() {
var transformedSelectObject = jQuery(this.countryElement).select2();
jQuery(transformedSelectObject).change(function(event) {
// The code below is not correct. Enters infinite loop
jQuery(this.countryElement).triggerHandler('change');
});
},
update: function() {
// Updates selector of country
this.selectize();
}
}
RegionsSelect= Class.create();
RegionsSelect.prototype = {
initialize: function(countryElement,regionElement,countriesWithMappedRegions) {
// Initializations here
Event.observe(this.countryElement, 'change', this.update.bind(this));
},
selectize: function() {
var transformedSelectObject = jQuery(this.regionElement).select2();
},
update: function() {
// Updates selector of regions
this.selectize();
}
}
</script>