イベント駆動プログラミングはGOTO文を使っている気分になる

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(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 powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy