イベント駆動プログラミングはGOTO文を使っている気分になる
· 1 min read
(function($, global, undefined){
'use strict';
var lscache,
Mustache,
processing = {},
generateCacheKey = function(path){
return 'fetched:' + path;
},
fetchTemplate = function(path){
console.debug('fetchTemplate');
var key = generateCacheKey(path);
$.get(path, function(template){
console.debug('run $.get');
lscache.set(key, template, 1);
delete processing[key];
$(global).triggerHandler(key); // fetch完了イベントを発行
});
},
renderOnEvent = function(e){
console.debug('renderOnEvent');
var args = Array.prototype.slice.apply(e.data);
render.apply(this, args);
},
render = function(path, args, cb){
console.debug('render');
var key = generateCacheKey(path);
var template = lscache.get(key);
if (template) {
return cb(Mustache.render(template, args));
}
else {
$(global).one(key, arguments, renderOnEvent);// fetch完了時のイベントを受信した時にもう一度実行する
if (!processing[key]) {
processing[key] = true;
fetchTemplate(path);// keyになるfetchをしていない場合はfetchする
}
}
},
setVars = function(){
// localize
lscache = global.lscache || console.error('not ready `lscache.js`. hint : `bower install lscache`.');
Mustache = global.Mustache || console.error('not ready `mustache.js`. hint : `bower install mustache`.');
},
init = function(){
setVars();
return {
'render': render
};
};
global.templates = init();
}(jQuery, this));
1
2
3
4
5
|
// コールバックの場合
templates.render('templates/sns.mst', fbObj, function(content){ $this.append(content) });
// jQueryオブジェクトの場合は、引数の順序はこんな感じ?メソッド名も変えておかないとねぇ
templates.renderTo($this, 'templates/sns.mst', fbObj);
|
1
|
$.templates('templates/sns.mst', fbObj).appendTo($this);
|
Comments
comments powered by Disqus