Panda Noir

JavaScript の限界を究めるブログでした。最近はいろんな分野を幅広めに書いてます。

jQueryを(多少は)マシに書けるFWを作った

jQuery、遊びツール作る分には重宝するのですが、やはりこのレベルでもつらく感じるのでフレームワークを作ってみました。

コード全容

なんとたったの9行!でも手抜きしたわけではありません。

const jQueryFW = opt => {
    for(const key of Object.keys(opt.util))
        opt.util[key] = opt.util[key].bind(opt, jQuery);
    opt.$S = opt.state, opt.$U = opt.util;
    jQuery($ => {
        for (const method of ['initState', 'init', 'initEventListener'])
            if (opt[method]) opt[method]($);
    });
};

簡単な使い方

こんな感じで使います。

<div id="count"></div>
<button id="increase">+1</button>
<button id="increase2">+2</button>
<button id="decrease">-1</button>
jQueryFW({
    state: {
        count: 0
    },
    util: {
        increase($, count = 1) {
            this.state.count += count;
        },
        decrease($, count = 1) {
            this.state.count -= count;
        },
        show($) {
            $('#count').text(this.state.count);
        }
    },
    init($) {
        this.util.show();
    },
    initEventListener($) {
        $('#increase').on('click', () => {
            this.util.increase();
            this.util.show();
        });
        $('#increase2').on('click', () => {
            this.util.increase(2);
            this.util.show();
        });
        $('#decrease').on('click', () => {
            this.util.decrease();
            this.util.show();
        });
    }
});

コンセプト

ずばり「イベントリスナの貼り付けとロジックの分割」です。「関数に名前付けて分離するだけじゃダメなの?」と思うかもしれません。しかしこれだとjQuery($ => {})の中がどんどん肥大化します。

経験したことありますよね。「グローバルスコープを汚染したくない」のと「$window.$から取りたくない」からです。具体的には次のようなコードです。

jQuery($ => {
    const f = (e) => {
        $('#text').text('clicked');
        // ここの$をwindow.$から取りたくないから
        // f()をjQuery()の外に置けない
    };
    const g = e => { /* ... */ };
    const h = e => { /* ... */ };
    // わかりやすいように分割したはずが、どんどん関数が増えていって
    // どれがどれのハンドラかわからなくなってしまう
    $('#hoge').on('click', f);
    $('#fuga').on('click', g);
    $('#piyo').on('click', h);
});

そこで、第一引数で$を受け取る関数を定義してやって、.bindでその引数にjQueryを束縛する、という手法をとっています。ついでにstateへアクセスするためにthisにも加工を加えてあります。

使ってみた感じ、結構つかいやすかったです。やっぱりイベントハンドラー関数の中を簡単に分割できるのは楽です。

このフレームワークでつくったもの

つくった、というか書き直したものですが。

pandanoir.net