gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:24:27 25 4
gpt4 key购买 nike

我在 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;

现在,如果我更改选择和初始绑定(bind),一切正常。
但是,如果我从 ie 更改 model.countryId。从 1 到 2,变化没有反射(reflect)在选择控件中,控件仍然显示“美国”,就像选择 1 一样。
因为'selected'属性是双向绑定(bind)的,所以我希望它在更改时更新选择。但事实并非如此。为什么?
我究竟做错了什么?

请帮忙

最佳答案

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

而且效果很好。

关于binding - Aurelia + Select2 自定义元素未传播选定更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42576039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com