Skip to content

Instantly share code, notes, and snippets.

@qtuan
Created May 4, 2016 09:37
Show Gist options
  • Save qtuan/8240ccbe8be8fdf9684a0a660b9b0aa2 to your computer and use it in GitHub Desktop.
Save qtuan/8240ccbe8be8fdf9684a0a660b9b0aa2 to your computer and use it in GitHub Desktop.
state.js
<template>
<require from="naive-if"></require>
<div naive-if="new,run">Hello world!</div>
<button click.delegate="cycleState()">Change state</button>
</template>
import {inject} from 'aurelia-framework';
import {State} from './state';
@inject(State)
export class App {
constructor(state) {
this.i = 0;
this.states = ['new', 'run', 'unknown'];
this.state = state;
}
cycleState() {
this.i = (this.i + 1) % this.states.length;
this.state.value = this.states[this.i];
}
}
<!doctype html>
<html>
<head>
<title>Aurelia</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body aurelia-app>
<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>
import {BoundViewFactory, ViewSlot, customAttribute, templateController, inject} from 'aurelia-framework';
import {BindingEngine} from 'aurelia-binding';
import {State} from './state';
@customAttribute('naive-if')
@templateController
@inject(BoundViewFactory, ViewSlot, BindingEngine, State)
export class NaiveIf {
constructor(viewFactory, viewSlot, bindingEngine, state) {
this.show = false;
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.bindingEngine = bindingEngine;
this.state = state;
}
bind() {
this.updateView();
this.subscription = this.bindingEngine.propertyObserver(this.state, 'value')
.subscribe((newValue, oldValue) => this.updateView());
}
unbind() {
if (this.subscription) this.subscription.dispose();
}
valueChanged(newValue) {
this.updateView();
}
updateView() {
let isShowing = this.show;
let showStates = this.value.split(',');
this.show = showStates.indexOf(this.state.value) != -1;
if (this.show && !isShowing) {
let view = this.viewFactory.create();
this.viewSlot.add(view);
} else if (!this.show && isShowing) {
this.viewSlot.removeAll();
}
}
}
export class State {
constructor() {
this.value = 'unknown';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment