2016-11-17 67 views
0

什麼是允許使用function而不是在類綁定中添加代碼的正確方法,就像這條線在app.html中的<div class.bind="isSuccess ? 'success' : 'error'">${message}</div>?在knockout中使用這種示例將分別更新類的綁定,即使observable屬於函數內部。Aurelia css與函數的綁定

下面是一個例子: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; 
} 

回答

2

結合計算性能時,應使用一個getter函數。例如:

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> 
+0

它[作品(https://gist.run/?id=b939325a584a979c2e6ad28f02290a24)。謝謝。 – janmvtrinidad