Skip to content

Instantly share code, notes, and snippets.

@jdanyow
Last active February 8, 2018 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jdanyow/1a84e0a466fb928aa075 to your computer and use it in GitHub Desktop.
Save jdanyow/1a84e0a466fb928aa075 to your computer and use it in GitHub Desktop.
Aurelia Dependency Injection: OptionalParent resolver
<template>
<require from="myelem"></require>
<myelem name.bind="'outer'">
<h3>inside myelem</h3>
<myelem name.bind="'inner'">
<h4>inside inside ... </h4>
</myelem>
</myelem>
</template>
export class App {
}
<!doctype html>
<html>
<head>
<title>Aurelia</title>
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body aurelia-app="main">
<h1>Loading...</h1>
<script src="https://cdn.rawgit.com/jdanyow/aurelia-bundle/v1.0.3/jspm_packages/system.js"></script>
<script src="https://cdn.rawgit.com/jdanyow/aurelia-bundle/v1.0.3/config.js"></script>
<script>
System.import('aurelia-bootstrapper');
</script>
</body>
</html>
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging();
aurelia.start().then(a => a.setRoot());
}
import {
customElement,
inlineView,
bindable,
inject
} from 'aurelia-framework';
import {OptionalParent} from './optional-parent';
@inject(OptionalParent.of(MyElem))
@customElement("myelem")
@inlineView("<template><content></content></template>")
export class MyElem {
@bindable name;
constructor(parent) {
this.parent = parent;
}
bind(bindingContext) {
console.log(`My name is "${this.name}".`);
console.log('My bindingContext is:');
console.log(bindingContext);
console.log('My parent is:');
console.log(this.parent);
}
}
import {resolver} from 'aurelia-dependency-injection';
@resolver()
export class OptionalParent {
constructor(key) {
this.key = key;
}
get(container) {
if (container.parent && container.parent.hasResolver(this.key, false)) {
return container.parent.get(this.key)
}
return null;
}
static of(key) {
return new OptionalParent(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment