Skip to content

Instantly share code, notes, and snippets.

@jdanyow
Forked from peisenmann/au-class.js
Last active March 6, 2016 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdanyow/9a081de1dd5b1140ccaa to your computer and use it in GitHub Desktop.
Save jdanyow/9a081de1dd5b1140ccaa to your computer and use it in GitHub Desktop.
Au-Class custom attribute for simplifying bound CSS declarations
<template>
<h1>${message}</h1>
</template>
export class App {
message = 'Hello World!';
}
import {customAttribute} from 'aurelia-framework';
/**
* The au-class custom attribute is intended to simplify aurelia binding code in the standard html class attribute.
*
* This is an unofficial community proposal to add to Aurelia (aurelia.io)
*
* Before:
<div class="base-class ${foo} ${someVMProp < 10 ? 'red' : ''} ${!otherVMProp ? 'blue' : ''}"></div>
* After:
<div au-class.bind="['base-class', foo, {red: someVMProp < 10, blue: !otherVMProp}]"></div>
*/
@customAttribute('au-class')
export class AuClass {
classes = new Set();
static inject = [Element];
constructor(element: Element) {
this.element = element;
}
valueChanged(newVal = {}) {
let newClasses = new Set(AuClass._extractClasses(newVal));
let removedClasses = [...this.classes].filter(x => !newClasses.has(x));
let addedClasses = [...newClasses].filter(x => !this.classes.has(x));
this.removeClasses(removedClasses);
this.addClasses(addedClasses);
this.classes = newClasses;
}
addClasses(classes) {
classes.forEach(c => this.element.classList.add(c))
}
removeClasses(classes) {
classes.forEach(c => this.element.classList.remove(c))
}
static _extractClasses(args) {
let classesFound;
if (args && typeof args === 'string') {
classesFound = [args];
}
if (Array.isArray(args)) {
classesFound = args.reduce((acc, arg) => acc.concat(AuClass._extractClasses(arg)), []);
}
else if (typeof args === 'object') {
classesFound = Object.keys(args).filter(p => args[p]);
}
return classesFound;
}
}
<!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());
}
/* styles */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment