如何利用 Aurelia 与 Select2 的数据绑定(bind)?它似乎与标准选择一起工作得很好。
理想情况下,我想在 select 元素中使用change.delegate 来调用 View 模型中的方法,这样我就可以访问我们正在注入(inject)的数据存储。
触发事件的唯一方法是在 Attached() 处理程序中连接更改事件,但数据存储会超出范围。
查看:
<template>
<label>Company:</label>
<!-- i would like to use change.delegate="change()" below -->
<select value.bind="selectedCompanies" multiple>
<option repeat.for="company of companies" model.bind="company.CompanyId">${company.CompanyName}</option>
</select>
</template>
查看模型:
import {inject, bindable} from 'aurelia-framework';
import {FilterCompanyData} from 'data/custom elements/filters/filterCompanyData';
import {UserStorage} from 'storage/userStorage';
@inject(Element, FilterCompanyData, UserStorage)
export class FilterCompanyCustomElement {
@bindable selectedCompanies;
constructor(element, filterCompanyData, userStorage) {
this.element = element;
this.filterCompanyData = filterCompanyData;
this.userStorage = userStorage;
this.companies = [];
}
bind(bindingContext, overrideContext) {
let userId = this.userStorage.userId;
return this.filterCompanyData
.getCompanies(userId)
.then(response => this.companies = response);
}
attached() {
var el = $(this.element).find('select');
var sel = el.select2({
closeOnSelect: false
});
// Is it possible to get rid of this?
sel.on('change', function (event) {
if (event.originalEvent) { return; }
// TODO add changed data to user storage
var IE = ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true));
var notice = IE ? new CustomEvent('change', { bubble: false }) : new Event('change', { bubble: false });
$(el)[0].dispatchEvent(notice);
});
}
detached() {
$(this.element).find('select').select2('destroy');
}
change() {
// I'd like to use this method from change.delegate
// TODO add changed data to user storage
}
}
顺便说一句,Aurelia 没有用于新事件的内置填充吗? IE似乎不喜欢这样。
最佳答案
我发现这个问题已经过时了,但我尝试做与您在这里所做的相同的事情,最终得到以下结果:
https://github.com/Kla3mus/select24aurelia
我不使用polyfill,也不使用组件外部的原始事件。我对选项和选定值使用双向绑定(bind)。也许这对你也有用?
它是用 TypeScript 编写的,但它几乎与 JavaScript 相同,所以我认为你可以修改它:)
关于javascript - Aurelia 和 Select2 更改事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39109682/