Created
December 30, 2010 07:23
-
-
Save mumoshu/759553 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
/** | |
* アプリケーション全体で共有するデータを保持したり、変更を通知する | |
*/ | |
function Registry() { | |
} | |
Registry.prototype.put = function(key, value) { | |
this[key] = value; | |
// jQueryのcustom eventで、リスナに値の変化を通知 | |
// 参考: http://api.jquery.com/trigger/ | |
// 注意: $(this).trigger('put', /* */); はNG。trigger()がput()に再帰するのでスタック溢れます! | |
// triggerするイベント名(ここでいうchange)と、prototypeに定義するメソッド名(ここでいうput)は異なるようにすべし。 | |
$(this).trigger('change', [key, value]); | |
}; | |
Registry.prototype.get = function(key) { | |
return this[key]; | |
}; | |
window.Registry = Registry; | |
})(jQuery); | |
(function($) { | |
var COUNT_KEY = "count"; | |
/** | |
* tickするたびにRegistryに保持されている値を1ずつカウントアップする | |
*/ | |
function Ticker(registry) { | |
this.registry = registry; | |
} | |
/** | |
* カウントアップする | |
* カウント数はRegistryに保存する | |
*/ | |
Ticker.prototype.tick = function() { | |
this.setCount((this.getCount() || 0) + 1); | |
}; | |
/** | |
* カウント数をセットする。 | |
* カウント数はRegistryに保存する。 | |
* 基本的には内部で利用。 | |
* 初期値のセットをする場合は外部から呼んでもOK。 | |
*/ | |
Ticker.prototype.setCount = function(value) { | |
this.registry.put(COUNT_KEY, value); | |
return this; | |
}; | |
/** | |
* 現在のカウント数を返す | |
* カウント数はRegistryから取得する。 | |
*/ | |
Ticker.prototype.getCount = function() { | |
return this.registry.get(COUNT_KEY); | |
}; | |
window.Ticker = Ticker; | |
})(jQuery); | |
(function($) { | |
var registry = new Registry(); | |
// registryの値の変更をregistryの外で検知する例。 | |
// jQueryのcustom eventで、registryに対して値の変更リスナを登録するイメージ | |
$(registry).bind('change', function(event, key, value) { | |
console.log("registryの値が変化しました。key=" + key + ", value=" + value); | |
}); | |
// カウント保持のためRegistryをinject | |
var ticker = new Ticker(registry); | |
// 1秒毎にregistryの値を変化させる | |
// コンソールには1秒毎にlogが出力される | |
window.setInterval($.proxy(ticker.tick, ticker), 1000); | |
// 依存関係はこんな感じ Ticker -> Registry <- Logger | |
// - Registryが普段グローバル変数に入れてたようなアプリケーション全体で共有する変数を保持 | |
// - TickerがRegistryに値を入れる | |
// - RegistryがLoggerに値の変更を通知する | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment