一般情况下,通过Ext.XTemplate类描画页面时,css选择器都是指定好的,也就是固定不变的样式。
但如果页面的样式需要根据某些条件发生改变时,可以通过使用Ext.XTemplate类内建的变量和成员方法动态的改变样式。
Ext.XTemplat内建的对象有
- out: The output array into which the template is being appended (using
pushto laterjoin). - values: The values in the current scope. If you are using scope changing sub-templates, you can change what values is.
- parent: The scope (values) of the ancestor template.
- xindex: If you are in a looping template, the index of the loop you are in (1-based).
- xcount: If you are in a looping template, the total length of the array you are looping.
创建Ext.XTemplat对象需要指定html格式的字符串作为第一个参数,成员方法可以作为第二个参数config的内容。
new Ext.XTemplate( html, [config] ) : Ext.Template
new Ext.XTemplate(‘<tpl if="this.isGirl(name)"><div class="name">name:{name}<div></tpl>’,
{
isGirl : function(name){ return name=="Sara"}
})
用法可参照http://docs.sencha.com/touch/2-1/#!/api/Ext.XTemplate-method-constructor
下面这个例子是一个list view,需要根据itemId的不同显示不同的背景颜色。
默认情况下每个item会有一个背景颜色(红色),根据方法getItemColorById()
取得不同的颜色值,重设style属性,就可以起到动态改变的目的。
关键点:
1.在{[...]}之间的code,会在template的作用域内执行,所以通过this调用成员方法。
2.内置变量values,指一个record记录,如{ itemId:1,title: 'Item 1' }
Ext.define('MyListView', {
extend: 'Ext.dataview.List',
config: {
data: [
{ itemId:1,title: 'Item 1' },
{ itemId:2,title: 'Item 2' },
{ itemId:3,title: 'Item 3' },
{ itemId:4,title: 'Item 4' }
],
itemTpl : new Ext.XTemplate(
'<div class="item" style="background-color:{[this.getItemColorById(values.itemId)]}">{title}</div>',
{
getItemColorById : function(itemId){
return ColorUtil.getItemColorById(itemId); //call util 方法,作用是根据itemId返回颜色值,省略
}
}
)
}
});
//css
.item{
background-color:#ff0000; //红色
}
浙公网安备 33010602011771号