powerbuoy
powerbuoy

Reputation: 12838

Dependency Injection Constructor that takes arguments

I'm building an Aurelia app that uses "Models" for every type of data object.

All my Models look something like this:

export class Item {
    id = null;
    name = '';
    description = '';

    constructor (data) {
        Object.assign(this, data);
    }
}

And I later create objects like this:

export class SomeViewModel {
    activate () {
        this.myItem = new Item({
            name: 'My Item!', 
            description: 'This is my item. It will be initialized with these properties.'
        });
    }
}

I got the Object.assign() bit from an article I read and it works really well. It allows me to create new items using data from the server, or if I want an empty Item I simply don't pass in anything.

Now I've reached a point where I need my model to have access to another class so I'm using Aurelia's Dependency Injection like this:

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});
    }
}

Now my problem is this; how do I create a new Item() without passing in the Router myself? I guess switching the order of argument to constructor() would do the trick but that doesn't seem to work with Aurelia?

And I don't want to have to do this every time I create a new Item:

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.'
        });
    }
}

Surely there must be a better way to solve this?

Upvotes: 1

Views: 1006

Answers (1)

Jeremy Danyow
Jeremy Danyow

Reputation: 26406

Use the Factory resolver. Here's an example: https://gist.run?id=46642ac54893186067e7cd890d6722a3**

import {inject, Factory} from 'aurelia-dependency-injection';
import {MyModel} from './my-model';

@inject(Factory.of(MyModel))
export class App {
  message = 'Hello World!';

  constructor(createModel) {
    let model = createModel('my data');
  }
}

my-model.js

import {inject} from 'aurelia-dependency-injection';
import {EventAggregator} from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class MyModel {
  constructor(eventAggregator, data) {
    console.log(eventAggregator, data);
  }
}

Upvotes: 2

Related Questions