无需构造函数注入即可访问Aurelia的Dependency Injection系统

Vac*_*ano 4 javascript aurelia aurelia-binding aurelia-di

有没有办法在没有构造函数注入的情况下访问Aurelia的依赖注入系统.

我有一个叫做的课Box.我需要知道其中一个属性何时更改,以便我可以更新我的验证.我发现我可以使用bindingEngine.propertyObserver这个答案.

但我的实例Box是由BreezeJsAurelia 创建的.所以使用@inject(或@autoinject在我的情况下)获取实例bindingEngine是行不通的.

我看到aurelia.container.get会让我从Aurelia的DI框架中解决.但这需要Aurelia对象的当前实例.我能看到的唯一方法是...构造函数注入!

所以,要绕过构造函数注入,你需要...构造函数注入!

我希望我错过了一些东西,还有另一种方法可以获得bindingEngine没有构造函数注入的实例.

注意:现在我只需将我的变量转换为javascript属性并自行触发已更改的事件.但我知道这会让我陷入肮脏的检查...... :(

Jer*_*yow 6

如果您想知道breeze实体的属性何时更改,请使用以下entityAspect.propertyChanged事件:

http://breeze.github.io/doc-js/api-docs/classes/EntityAspect.html#event_propertyChanged

order.entityAspect.propertyChanged.subscribe(
function (propertyChangedArgs) {
    // this code will be executed anytime a property value changes on the 'order' entity.
    var entity = propertyChangedArgs.entity; // Note: entity === order
    var propertyNameChanged = propertyChangedArgs.propertyName;
    var oldValue = propertyChangedArgs.oldValue;
    var newValue = propertyChangedArgs.newValue;
});
Run Code Online (Sandbox Code Playgroud)

不推荐规避构造函数注入.它违反了依赖性倒置原则,但是有一种机制可以这样做:

main.js

export function configure(aurelia) {
  aurelia.container.makeGlobal();
  ...
}
Run Code Online (Sandbox Code Playgroud)

box.js

import {Container} from 'aurelia-dependency-injection';

let bindingEngine = Container.instance.get(BindingEngine);
Run Code Online (Sandbox Code Playgroud)