2016-08-23 73 views
1

如何使用Aurelia与Select2的数据绑定?它似乎与一个标准选择工作得很好。Aurelia和Select2更改事件

理想情况下,我想在select元素中使用change.delegate来调用我的View Model中的方法,这样我就可以访问我们注入的数据存储。

我可以让一个事件触发的唯一方法是连接()处理程序中的更改事件,但数据存储超出范围。

查看:

<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似乎不喜欢那样。

+0

如果你使用'新的事件(“变”,{气泡:真});' 'change.delegate'应该可以工作 –

回答

0

我看到,这个问题是老了,但我已经尝试过这样做,你在这里做同样的,和我结束了以下内容:

https://github.com/Kla3mus/select24aurelia

我不使用polyfill,或组件外的原始事件。我使用双向绑定选项和选定的值。也许这也适用于你?

这是写在打字稿,但它是几乎一样的JavaScript,所以我觉得你可以修改它:)