[英]Aurelia trying to load HTML from Select2?
所以我試圖在我的Aurelia應用程序中使用Select2。 我使用jspm install select2
安裝了Select2,在我的app.html
文件中,我需要使用<require from="select2/js/select2.min.js"></require>
Select2。 瀏覽器加載縮小的JS文件,但由於某種原因它也嘗試加載
http:// localhost:3003/jspm_packages/github/select2/select2@4.0.0/js/select2.min .html 。
為什么Aurelia嘗試加載我在<require>
元素中指定的同一JS文件的HTML副本? 我怎樣才能解決這個問題?
謝謝
<require from="...."></require>
是將視圖資源導入視圖。 查看資源是自定義元素或自定義屬性。 當您將<require from="select2/js/select2.min.js"></require>
到模板時,aurelia會加載模塊並認為它是自定義元素的視圖模型。 然后它會嘗試為它加載視圖,這就是為什么你看到加載.../select2.min.html
的嘗試
集成select2的“aurelia方式”是創建一個將select2應用於元素的自定義屬性。 像這樣的東西:
選擇2 -定制attribute.js
import {customAttribute, inject} from 'aurelia-framework';
import {DOM} from 'aurelia-pal';
import $ from 'jquery';
import 'select2'; // install the select2 jquery plugin
import 'select2/css/select2.min.css!' // ensure the select2 stylesheet has been loaded
@customAttribute('select2')
@inject(Element)
export class Select2CustomAttribute {
constructor(element) {
this.element = element;
}
attached() {
$(this.element)
.select2(this.value);
//.on('change', () => this.element.dispatchEvent(DOM.createCustomEvent('change')));
}
detached() {
$(this.element).select2('destroy');
}
}
然后,您將自定義屬性導入到視圖中,並像這樣使用它:
app.html
<require from="select2-custom-attribute"></require>
<select select2 value.bind="selectedState">
<option repeat.for="state of states" model.bind="state">${state.name}</option>
</select>
或者像這樣,如果你需要將一些選項傳遞給select2(這假設你的視圖模型有一個名為“options”的屬性,其中包含其文檔中描述的select2選項):
app.html
<require from="select2-custom-attribute"></require>
<select select2.bind="options" value.bind="selectedState">
<option repeat.for="state of states" model.bind="state">${state.name}</option>
</select>
這是一個有效的例子: https : //gist.run/?id = 0137059e029fc4b3ccd367e385f47b19
不幸的是,我無法使用jspm正確導入select2,即使使用此處列出的墊片也是如此。 如果遇到同樣的問題,則必須從上面的自定義屬性代碼中刪除與select2相關的import語句,並在文檔中加載帶有腳本/鏈接標記的select2 js和css。
為了完成,在Jeremy的解決方案中觸發change
事件會導致遞歸循環並導致異常以修復它我必須執行的操作:
attached() {
$(this.element)
.select2(this.value)
.on('change', evt => {
if (evt.originalEvent) { return; }
this.element.dispatchEvent(new Event('change'));
});
}
然后我可以這樣做:
<require from="select2-custom-attribute"></require>
<select select2.bind="options" value.bind="selectedState" change.delegate="changeCallback($event)">
<option repeat.for="state of states" model.bind="state">${state.name}</option>
</select>
changeCallback($event)
可以是你的vm
上的一個函數,例如
changeCallback(evt: Event): void {
console.log(evt);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.