Skip to content

Instantly share code, notes, and snippets.

@davismj
Last active August 7, 2017 10:42
Show Gist options
  • Select an option

  • Save davismj/0b635ea18c9e04d27360187cd2642379 to your computer and use it in GitHub Desktop.

Select an option

Save davismj/0b635ea18c9e04d27360187cd2642379 to your computer and use it in GitHub Desktop.
Customizing the Aurelia dependency injection behaviors
// MyModel is a class that represents a database object.
export class MyModel {
name;
address;
telephone;
constructor(obj) {
this.name = obj.name;
this.address = obj.address;
this.telephone = obj.telephone;
}
}
import { Factory, inject } from 'aurelia-framework'; // or 'aurelia-dependency-injection';
import { MyModel } from './myModel';
import { State } from './state';
// Factory.of tells the Aurelia DI container that you're not looking for an instantiated object, but a constructor such that you can
// manually instantiate objects. This is particularly useful when you need to create multiple instances of an object or when you
// need to manually pass arguments to the constructor or both.
@inject(Factory.of(MyModel), State)
export class MyViewModel {
models = [];
constructor(myModelFactory, state) {
this.createMyModel(obj) => {
const myModel = myModelFactory(obj);
models.push(myModel);
return myModel;
}
this.state = state;
state.mode = 'edit';
state.currentMyModel = {
name: '',
address: '',
telephone: ''
};
state.update();
}
}
import { transient } from 'aurelia-framework'; // or 'aurelia-dependency-injection';
// State is an object that tracks the state of an object. You can set arbitrary values on the State object and track changes.
// Every time we inject the State class we want a new object instantiated, to prevent the state of one object from interfering
// with the state of another object. Therefore, we use the `transient` decorator to tell Aurelia to create a new instance every
// time it is injected.
@transient()
export class State {
constructor() {
let originalState;
this.update = () => originalState = clone(this);
this.revert = () => Object.assign(this, originalState);
Object.defineProperty(this, 'isDirty', {
get: () => JSON.stringify(this) !== JSON.stringify(originalState)
});
this.update();
}
}
// deep copy
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment