自定义表达式(方法)
对于上一章的代码来说:
data : {
country : {
name : 'China',
temperature : 'cold',
rainfall : 'excessive',
population : '120000000',
capital : {
name : 'beijing',
lat : 501,
lon : 299
}
}
}
可以像JS一样,定义的属性可以是一个函数(也就是对应的方法),在模板中调用这个方法对传入的数据进行处理,比如说可以再data中定义一个format的方法对数字进行处理:
data : {
country : {
name : 'China',
temperature : 'cold',
rainfall : 'excessive',
population : '120000000',
capital : {
name : 'beijing',
lat : 501,
lon : 299
}
}
format: function ( num ) {
if ( num > 1000000000 ) return ( num / 1000000000 ).toFixed( 1 ) + ' billion';
if ( num > 1000000 ) return ( num / 1000000 ).toFixed( 1 ) + ' million';
if ( num > 1000 ) return ( Math.floor( num / 1000 ) ) + ',' + ( num % 1000 );
return num;
}
}
在模板中使用这个方法只需要直接在常规的Mustaches中增加这个方法,将被处理的变量用括号括起来即可:
<p>Its population is {{format(population)}} and its capital is {{name}} and locates at {{lat}} and {{lon}}.</p>
最后的结果将120000000显示为120.0 million
JavaScript toFixed() 方法把 Number 四舍五入为指定小数位数的数字。
NumberObject.toFixed(num)
num必需,规定小数的位数,是 0 ~ 20 之间的值,包括 0 和 >20,如果省略了该参数,将用 0 代替。
数学表达式
可以再模板的变量中直接使用数学表达式进行计算
// 模板
<p>{{format(price * quantity)}}</p>
// JS文件
var ractive1 = new Ractive({
el : '#container',
template : '#template',
data : {
price : 0.22,
quantity : 2,
format : function(num){
if(num<1){
return (
'¥' + num.toFixed(2)
)
}
return (
'^^^^' + num
)
}
}
});
//结果是¥ 0.44
之所以模板可以进行表达式的运算,是因为当模板被解析时,表达式中的变量都被定义了。当渲染时,绑定了这些变量的表达式也会创建一个函数去计算表达式的结果(无论何时,RactiveJS都会复用函数,无论是{{a+b}}还是{{x+y}}都共享一个函数)。
当变量的值发生改变,表达式会重新计算,并更新DOM
颜色混合的例子
<div id="container"></div>
<script type="text/ractive" id="template">
<div style='background-color : red; width : {{red*100}}%; height:50px'></div>
<div style='background-color : green; width : {{green*100}}%; height:50px'></div>
<div style='background-color : blue; width : {{blue*100}}%; height:50px'></div>
<div style='background-color : rgb({{Math.round(red * 255)}}, {{Math.round(green * 255)}}, {{Math.round(blue * 255)}}; height:50px'></div>
</script>
<script>
var ractive1 = new Ractive({
el : '#container',
template : '#template',
data : {
red : 0.5,
green : 0.5,
blue : 0.5
}
});
</script>
上面的代码中:
1. 用red等同时表示了div的宽度和颜色的比例
2. 最后一个混合颜色的div的rgb值必须是整数,所以使用了Math.round()方法;
3. 通过ractive1可以更改颜色值,想要动态效果,可以使用.animate()方法:
ractive1.animate('red', '0.4')
Math对象是JS内置对象的一种,其他的众多的内置对象比如Data、encodeURI、JSON都可以在表达式中使用,详细的文档在此。
模板对象的表达式不包括赋值操作(包括++和–)、new、delete或者void,也不使用函数字面量。