我使用的是semantic-ui,它有自己内置的模态功能(见这里)。而不是编写所有的代码来利用这个特殊的功能在Aurelia,有没有一种方法挂钩到Aurelia -dialog插件的渲染管道,所以我可以使用配置Aurelia -dialog插件使用语义界面?
有。
Aurelia-dialog提供了一个抽象的Renderer接口,用于与渲染器进行交互。默认情况下,它将使用它提供的渲染器,但你可以通过配置对话框插件来覆盖它,像这样:
import {MyRenderer} from './my-renderer';
aurelia.use.plugin('aurelia-dialog', (config) => {
config.useRenderer(MyRenderer);
});
…其中MyRenderer
使用抽象的Renderer接口。在你的渲染器中,你需要实现三个方法:getDialogContainer
, showDialog
和hideDialog
。
一些警告-在showDialog
函数中,您需要创建showDialog
和hideDialog
方法,并将它们附加到作为参数传递的dialogController上。这确保了你的dialogController可以通过编程方式关闭对话框。
在你实现并注册了渲染器之后,对话框插件将使用你选择的UI工具包。
这是我对语义ui模态的解决方案(在TypeScript中),它不使用aurelia-dialog。
视图(/ui/dialogues/dialog-confirm.html):
<template>
<div class="ui modal small" ref="dialogElement">
<div class="header">${model.headerText}</div>
<div class="content">
<p>${model.messageText}</p>
</div>
<div class="actions">
<div class="ui approve button">${model.confirmText?model.confirmText:'OK'}</div>
<div class="ui cancel button">${model.cancelText?model.cancelText:'Cancel'}</div>
</div>
</div>
</template>
视图模型(/ui/dialogues/dialog-confirm.ts):
export class Dialog {
model;
done;
result;
dialogElement:HTMLElement;
activate(data) {
if( data ){
this.model = data.model;
this.done = data.done;
this.result = false;
}
}
bind(){
$(this.dialogElement)
.modal({
onApprove : ()=>{ this.result = true; },
onDeny : ()=>{ this.result = false; },
onHide : ()=>{ this.done(this.result); }
})
.modal('show');
}
}
Dialog类(/ui/Dialog/Dialog .ts):
import { inject } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
@inject(EventAggregator)
export class Dialog {
constructor(private eventAggregator) {
}
show(viewName: string, model) {
return new Promise( (resolve, reject) => {
this.eventAggregator.publish('showDialog', {
viewName: viewName,
model: model,
resolve: resolve
});
});
}
}
…将EventAggregator注入到你的App类中,并将其添加到attached()钩子中:
attached() {
this.eventAggregator.subscribe('showDialog', (event) => {
console.assert( !this.dialogData, "Only one dialog can be shown at any time." );
event.done = (result) => {
event.resolve(result);
this.dialogData = null;
}
this.dialogName = event.viewName;
this.dialogData = event;
});
}
…最后把这段添加到app.html:
<compose if.bind="dialogData" view-model="./ui/dialogs/${dialogName}" model.bind="dialogData" view="./ui/dialogs/${dialogName}.html">
</compose>
用法,您可以将任何模型-视图/视图对的名称作为第一个参数:
this.dialog.show('dialog-confirm',{
headerText:'Warning!',
messageText:'When you delete stuff - it is lost',
confirmText:'Delete',
cancelText:'I better not...'
}).then( function(result){
console.log( 'The result is: '+result )
});