2010年 02月 21日

JSDeferred Deferred.chain

http://lab.hisasann.com/addCommand/index.html を見ていて、next().next() 以外に、こういう風に書けても別にいいよなぁと思ったので実装を書いてみた。next().next() はめんどい割とめんどいし

git master HEAD には今のところ Deferred.chain() として入ってる。これと Deferred.connect() の変数バインドを組み合せて、addCommand.js のデモ相当をしてみた。

それっぽいとこを抜きだすと

Deferred.define();

var img1 = $("#img1"),
	img2 = $("#img2"),
	img3 = $("#img3");
(function() {
	var callee  = arguments.callee;

	var animate = function (target, prop, speed, easing) {
		return Deferred.connect(target, "animate", { args: [ prop, speed, easing ] });
	};

	Deferred.chain(
		animate(img1, {
			opacity: 0, top: 90 + "px", left: 260 + "px"
			}, 1000, "easeInOutCirc"),
		animate(img2, {
			opacity: 0, top: 170 + "px", left: 450 + "px"
			}, 1000, "easeInOutCirc"),
		animate(img3, {
			opacity: 0, top: 260 + "px", left: 620 + "px"
			}, 1000, "easeInOutCirc"),
		[
			animate(img1, {
				opacity: 1, top: 0 + "px", left: 0 + "px"
				}, 1000, "easeInBack"),
			animate(img2, {
				opacity: 1, top: 0 + "px", left: 0 + "px"
				}, 1000, "easeInBack"),
			animate(img3, {
				opacity: 1, top: 0 + "px", left: 0 + "px"
				}, 1000, "easeInBack")
		],
		function () {
			return wait(0.5).next(callee);
		},
		function error (e) {
			alert(e);
		}
	);
})();

となっていて、デモのコードとほぼ同じになる。エラーをキャッチする関数には function error() としておくルールがある。

キモは animate() を実行した時点ではアニメーションは実行されず、アニメーションを実行する関数を返すだけのところです。(Deferred.connect は関数を返す関数です)

便利なので入れたい気もするけど、うまく書かないと混乱するのでむずかしい。