【发布时间】:2016-08-19 11:59:27
【问题描述】:
我正在构建一个 Aurelia 应用程序,它为每种类型的数据对象使用“模型”。
我所有的模型看起来都是这样的:
export class Item {
id = null;
name = '';
description = '';
constructor (data) {
Object.assign(this, data);
}
}
我后来创建了这样的对象:
export class SomeViewModel {
activate () {
this.myItem = new Item({
name: 'My Item!',
description: 'This is my item. It will be initialized with these properties.'
});
}
}
我从阅读的一篇文章中获得了Object.assign() 位,它运行良好。它允许我使用来自服务器的数据创建新项目,或者如果我想要一个空项目,我根本不传递任何内容。
现在我已经到了需要我的模型能够访问另一个类的地步,所以我正在使用 Aurelia 的依赖注入,如下所示:
import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';
@inject(Router)
export class Item {
id = null;
name = '';
description = '';
constructor (router, data) {
this.router = router;
Object.assign(this, data);
}
get permalink () {
return window.location.protocol + '//' + window.location.host + this.router.generate('item', {itemId: this.id});
}
}
现在我的问题是这样的;如何创建new Item() 而不自己传递Router?我猜想将参数顺序切换到constructor() 可以解决问题,但这似乎不适用于 Aurelia?
而且我不想每次创建新项目时都这样做:
import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';
@inject(Router)
export class SomeViewModel {
constructor (router) {
this.router = router;
}
activate () {
this.myItem = new Item(this.router, {
name: 'My Item!',
description: 'This is my item. It will be initialized with these properties.'
});
}
}
肯定有更好的方法来解决这个问题?
【问题讨论】:
-
只是一个想法:创建一个可以传递(注入)的项目工厂服务,您可以调用它来创建新项目。
标签: javascript mvvm dependency-injection aurelia