Aurelia Syntax inject Styles


#1

I’ve noticed for some time now 2 different types of inject declarations.

Most common method

import { inject } from 'aurelia-framework';
import { Foo } from 'my-other-class';

@inject(Foo)
export class MyClass {
    constructor(foo) {
         this.foo = foo;
    }
}

Older method

import { Foo } from 'my-other-class';

export class MyClass {
    static inject = [Foo];
    constructor(foo) {
         this.foo = foo;
    }
}

I believe the older method is probably just a pre babel decorator support way of DI. Is there any advantages to using this over the decorator method? I ask since I still see some post snippets using this method still and wondered if this is just due to that being what one is used to or because there’s some advantage. I’ve also noticed a few snippets in posts using @useView when there didn’t appear any need since the view had the same name and location of the viewmodel.


#2

I prefer the static member since it is more clean and I don’t have to import anything.
As well decorators are as far as I know not anymore in the ECMAScript standard. So without babel this won’t work as well. Also I think a static member is more readable.

But this is just my opinion :slight_smile:


#3

With regards to useview its useful when you create reusable components, eg Plugins. The reason is that the consumers might override the default convention and with the decorator you make sure that the proper template is still found


#4

What you prefer more in TS?

  • autoinject
    or
  • inject

#5

Autoinject all the things + custom resolvers for weird Edge cases (eg requiring electron backend code in Aurelia renderer)


#6

@autoinject for everything except when I’m injecting Element in Typescript and have to use @inject.

Is there another way?


#7

Thanks @fragsalat, that’s what I was looking for. I didn’t know that it was pulled out of the next version. Perhaps it will be pulled back in the one after that. I personally like using them, not just for inject. I did read where they are looking to do releases every year?? I’m all for new and cool stuff but that might get a little crazy for developers to maintain, which ones we can use and can’t, whether you have the right babel version, etc.


#8

If you want to use the @autoinject with DOM.Element in Typescript, follow the example bellow:

@autoinject
export class MyClass {
constructor(private element: Element) {}
}


#9

That didn’t work in TypeScript last time I checked.

See this comment.


#10

I’m using it on my current project.


#11

@timfish If you’re using webpack make sure to

import {DOM} from "aurelia-pal"

and inject DOM.Element instead


#12

I’m using systemjs/jspm and started the project over a year ago. When I tried @autoinject months ago it wasn’t working. Typescript and Aurelia have seen quite a few updates since then so I’ll have to have to test it.