2
我正在將select2插件集成到aurelia中,並且在綁定從ajax調用接收的數據時遇到問題,並且在自定義元素呈現後需要幾秒鐘。在aurelia中集成select2插件
import 'select2'
import 'select2/css/select2.css!'
import {
bindable,
bindingMode,
customElement,
inject
} from 'aurelia-framework'
import $ from 'jquery'
@customElement('select2')
@inject(Element)
export class CustomSelect {
@bindable name = null
@bindable({ defaultBindingMode: bindingMode.twoWay }) selected = {}
@bindable options = []
@bindable labelField = "label"
@bindable valueField = "value"
constructor(element) {
this.element = element
}
bind() {
this.isComplexModel = this.options && this.options.length > 1 && (typeof this.options[0] !== "string" && typeof this.options[0] !== "number")
this.translateModel()
this.selectedValue = this.options[0].value
this.selectedValue = !this.selected ? this.selectedValue : this.selected[this.valueField]
}
attached() {
$(this.element).find('select')
.val(this.selectedValue)
.select2()
.on('change', (event) => {
if (this.isComplexModel) {
this.selected = event.currentTarget.selectedOptions[0].model
} else {
this.selected = event.currentTarget.selectedOptions[0].model.value
}
let changeEvent
if (window.CustomEvent) {
changeEvent = new CustomEvent('change', {
detail: {
value: event.target.value
},
bubbles: true
})
} else {
changeEvent = document.createEvent('CustomEvent')
changeEvent.initCustomEvent('change', true, true, {
detail: {
value: event.target.value
}
})
}
$(this.element).val(event.target.value)
this.element.dispatchEvent(changeEvent)
})
}
translateModel() {
if (this.isComplexModel) {
this.options = this.options.map((option) => $.extend(option, {"label": option[this.labelField], "value": option[this.valueField]}))
} else {
this.options = this.options.map((option) => $.extend({}, {"label": option, "value": option}))
}
}
}
<template>
<select name.bind="name" id.bind="name">
<option repeat.for="option of options" value.bind="option.value" model.bind="option">${option.label}</option>
</select>
</template>
在這段代碼中,只連接被調用一次(在這一點上,提供的選項是不確定的),我無法找到任何方式來更新最新的數據選擇2這我從API獲取。
我需要你的幫助,使這個自定義元素可以工作,當選項改變其狀態。提前致謝!
運行您的示例會拋出一個錯誤,也許您可以添加一個更新的示例[此處](https://gist.run/?id=a2986a73fe6e27b68e16c0c285ce03d2)來演示該場景。 – janmvtrinidad