金曜日, 2 月 13th, 2009 | Author: djodjo
XTemplateを利用してて困ったことがあります。
テンプレートに{hoge.honya.hoi}とドットをつないでオブジェクトにアクセスできないんです。
以下のようにテンプレートがあったとして
var data = {
itemA:{
name:'ほげほげ'
},
itemB:{
subitem:{
name:'ほげほげ'
}
}
}
this.tmpl = Ext.XTemplate.from('preview-tpl', {
compiled: true
});
tmpl.overwrite(panel.body, data);
テンプレート部分で、バインドしたオブジェクトにアクセスする部分で、下記の1はOKだが2の書き方だとエラーとなる。でも、せっかくオブジェクトで渡しているのでドットでつないでアクセスしたい。
1.{itemA.name}
2.{itemB.subitem.name}
これは、XTempleteのメソッドで変数をバインドするときのコードに問題あり。
なので、これをoverrideしてパッチ
Ext.override(Ext.XTemplate, {
compileTpl: function(tpl){
var fm = Ext.util.Format;
var useF = this.disableFormats !== true;
var sep = Ext.isGecko ? "+" : ",";
var fn = function(m, name, format, args, math){
if (name.substr(0, 4) == 'xtpl') {
return "'" + sep + 'this.applySubTemplate(' + name.substr(4) + ', values, parent, xindex, xcount)' + sep + "'";
}
var v;
if (name === '.') {
v = 'values';
} else if (name === '#') {
v = 'xindex';
} else if (name.indexOf('.') != -1) {
//v = name; ここがパッチ。あとはオリジナル
v = 'values.' + name;
} else {
v = "values['" + name + "']";
}
if (math) {
v = '(' + v + math + ')';
}
if (format && useF) {
args = args ? ',' + args : "";
if (format.substr(0, 5) != "this.") {
format = "fm." + format + '(';
} else {
format = 'this.call("' + format.substr(5) + '", ';
args = ", values";
}
} else {
args = '';
format = "(" + v + " === undefined ? '' : ";
}
return "'" + sep + format + v + args + ")" + sep + "'";
};
var codeFn = function(m, code){
return "'" + sep + '(' + code + ')' + sep + "'";
};
var body;
// branched to use + in gecko and [].join() in others
if (Ext.isGecko) {
body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
"';};";
} else {
body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
body.push("'].join('');};");
body = body.join('');
}
eval(body);
return this;
}
})
Category: ExtJS

