janmvtrinidad janmvtrinidad - 22 days ago 29
Javascript Question

Aurelia css binding with function

What would be the right way to allow using

function
instead of adding code inside class bind just like this line
<div class.bind="isSuccess ? 'success' : 'error'">${message}</div>
in app.html? This kind of example when using in knockout will update respectively the class binding even though the observable is inside a function.

Here's an example: https://gist.run?id=d2b120bcd3d6a8157f4d4c9bf247988b

app.html

<template>
<div class.bind="getColor()">${message}</div>
<div class.bind="isSuccess ? 'success' : 'error'">${message}</div>

<button click.delegate="toggleColor()">toggle color</button>
</template>


app.js

export class App {
message = 'hello worlds';
isSuccess = false;
toggleColor() {
this.isSuccess = !this.isSuccess;
}

getColor() {
return this.isSuccess ? 'success' : 'error';
}
}


index.html

<!doctype html>
<html>
<head>
<title>Aurelia</title>
<link rel="stylesheet" href="https://gist.host/run/1479356763275/style.css">
<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>


style.css

/* Styles go here */

.success {
background-color: green;
}

.error {
background-color: red;
}

Answer

You should use a getter function when binding to computed properties. For instance:

JS

import {computedFrom} from 'aurelia-framework';

export class App {
  message = 'hello worlds';
  isSuccess = false;
  toggleColor() {
    this.isSuccess = !this.isSuccess;
  }

  @computedFrom('isSuccess') //use @computedFrom to avoid dirty-checking
  get getColor() {
    return this.isSuccess ? 'success' : 'error';
  }
}

HTML

<div class.bind="getColor">${message}</div>