Aurelia + Select2自定义元素未传播选定已更改
问题描述:
我在Aurelia中创建了自定义元素。Aurelia + Select2自定义元素未传播选定已更改
import {bindable, inject, customElement, bindingMode} from 'aurelia-framework';
import 'select2';
import * as $ from 'jquery';
import {BindingSignaler} from "aurelia-templating-resources";
@customElement('select2')
@inject(Element, BindingSignaler)
export class Select2CustomMultiselect {
@bindable name = null; // name/id of custom select
@bindable selected = null; // default selected values
@bindable ({defaultBindingMode: bindingMode.oneWay, attribute:"options"}) source:Array<{id:number, name:any}>= []; // array of options with id/name properties
@bindable placeholder = "";
@bindable allow_clear = true;
private $select2: $;
constructor(private element, private signaler:BindingSignaler) {
}
attached() {
let $select = $(this.element).find('select');
this.$select2 = $select.select2({theme: 'bootstrap', placeholder: this.placeholder});
// on any change, propagate it to underlying select to trigger two-way bind
this.$select2.on('change', (event) => {
if (event.originalEvent) { return; }
const select2Value = this.$select2.val();
if(select2Value == this.selected) { return; }
// dispatch to raw select within the custom element
var notice = new Event('change', {bubbles: true});
event.target.dispatchEvent(notice);
});
this.$select2.val(this.selected);//.trigger('change');
}
selectedChanged(newValue,oldValue){
console.log(newValue);
}
detached() {
$(this.element).find('select').select2('destroy');
}
}
而且它的模板:
<template>
<select value.two-way="selected" name.one-way="name" id.one-way="name" class="form-control" data-allow-clear.one-way="allow_clear" size="1">
<option></option>
<option repeat.for="src of source" model.bind="src.id">${src.name & t}</option>
</select>
</template>
我这样使用控制:
<select2 name="payingBy" selected.two-way="model.countryId & validate" options.bind="countries" placeholder="${'Select' & t}" allow_clear="true"></select2>
和型号是:
countries:Array<{id:number, name:string}> = [{id:1, name:"USA"}, {id:2, name:Canada'}];
model.countryId: number;
现在,一切工作正常,如果我更改选择并打开初始箱丁。 但是,如果我改变model.countryId从ie。 1到2,变化没有反映在选择控制中,控制仍像“1”一样显示“USA”。 因为'selected'属性是双向绑定的,我希望它在更改时更新select。但事实并非如此。为什么? 我在做什么错?
请帮
答
那是因为你使用的是data
版本,它期望的对象,但你已经设置你的选择只与id
值继续工作。所以你应该使用val
来传递id。
selectedChanged(newValue, oldValue) {
console.log(newValue);
if (this.select2) {
this.select2.select2({
val: newValue, // << changed this from data: newValue
theme: 'bootstrap',
placeholder: this.placeholder
});
}
+0
好的,改变了,但仍然不起作用。我也更新了运动员,所以你可以看到。 http://plnkr.co/edit/UTHR6f?p=preview – Luka
其实它确实更新了底层的select但不是select2 – Luka
我也做了一个plunker:http://plnkr.co/edit/UTHR6f?p=preview – Luka
这与此有关吗? http://stackoverflow.com/questions/19639951/how-do-i-change-selected-value-of-select2-dropdown-with-jqgrid – dpix