Aurelia + Select2自定义元素未传播选定已更改

时间:2017-03-03 10:11:01

标签: binding aurelia select2 custom-element aurelia-framework

我在Aurelia创建了一个自定义元素。

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;

现在,如果我更改select和on initial binding,一切正常。 但是,如果我从ie更改model.countryId。如图1至图2所示,更改未反映在选择控件中,控件仍显示&#34; USA&#34;如同1一样被选中。 因为选择了&#39;属性是双向绑定我希望它在更改时更新选择。但事实并非如此。为什么? 我做错了什么?

请帮忙

2 个答案:

答案 0 :(得分:3)

好的,我在这篇帖子中实现了它:Custom Select2 Aurelia component

它完美无缺。

答案 1 :(得分:1)

这是因为您正在使用期望对象的data版本,但您已将select设置为仅使用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
      });
    }