Skip to content
Permalink
Browse files

Enabling Dependency Injection for client side models bound to Aurelia…

… enhanced razor views
  • Loading branch information...
deap82 committed Sep 24, 2017
1 parent ba04575 commit 11a6ce9fb71a0a6e3f6176a5715e7e5d51dddfba
@@ -55,7 +55,8 @@ public override void Process(TagHelperContext context, TagHelperOutput output)
SystemJS.import('app/core/aurelia-enhancer').then(function(enhancer) {{
SystemJS.import('{Module}').then(function(module) {{
var data = {jsonData};
var clientModel = module.create(data);
var diMetaData = module.createMetaData();
var clientModel = enhancer.createViewModel(diMetaData, data);
enhancer.enhance(clientModel, document.getElementById('{elementId}'));
}});
}});
@@ -6,6 +6,26 @@ export function init(au: Aurelia): void {
aurelia = au;
}

export class AureliaEnhanceMetaData {
/**
* @param dataTypeName The name used to name the instance in Aurelia DI, as a convention use the name of the interface that the data object implements.
* @param clientModelType The type that should be created through Aurelia DI and used as client side model for the enhanced markup.
*/
constructor(public dataTypeName: string, public clientModelType: Function) {
}
}

export function createViewModel(metaData: AureliaEnhanceMetaData, data?: any): any {
if (data) {
aurelia.container.unregister(metaData.dataTypeName);
aurelia.use.instance(metaData.dataTypeName, data);
}

aurelia.use.transient(metaData.clientModelType);
let viewModel = aurelia.container.get(metaData.clientModelType);
return viewModel;
}

export function enhance(clientModel: any, element: HTMLElement): void {
let enhanceInstruction: EnhanceInstruction = {
container: aurelia.container,
@@ -1,13 +1,22 @@
export function create(data: HomePersonModel) {
return new HomePersonClientModel(data);
import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { AureliaEnhanceMetaData } from '../../core/aurelia-enhancer';

let dataKey = 'HomePersonModel';

export function createMetaData(data: HomePersonModel): AureliaEnhanceMetaData {
return new AureliaEnhanceMetaData(dataKey, HomePersonClientModel);
}

@inject(dataKey, Router)
class HomePersonClientModel {
data: HomePersonModel;
router: Router;
currentYear: number;

constructor(data: HomePersonModel) {
constructor(data: HomePersonModel, router: Router) {
this.data = data;
this.router = router;
this.currentYear = new Date().getFullYear();
}
}

0 comments on commit 11a6ce9

Please sign in to comment.
You can’t perform that action at this time.