平々毎々 (Hey hey, My my)
rock and roll can never die
2008年10月10日金曜日
JavaScriptでMVPパターン(jQuery編)
昨日の
「JavaScriptでMVPパターン(ぷよぷよ編)」
ではアニメーションできてないのが嫌だったので、今日はアニメーションを書いてみた。
jQueryでアニメーションしながらMVPパターン
モデルはこんな感じ。start()で開始。next()で状態遷移し、オブザーバーに通知。
var model = { observers: new Array(), position: null, queue: null, running: false, start: function(q) { if (this.running) return; this.running = true; this.queue = q; this.next(); }, stop: function() { this.position = null; this.queue = null; this.running = false; }, next: function() { if (!this.running) return; try { if (this.queue.length == 0) { this.stop(); return; } this.position = this.queue.shift(); } catch(e) { this.stop(); return; } this.notify(); }, notify: function() { for(var i = 0; i < this.observers.length; i++) { try { this.observers[i].update(); } catch(e) { } } } };
ビューはこんな感じ。jQueryを使っている。update()の中でアニメーションを開始し、コールバック関数はプレゼンターを呼び出すようにしている。
window.onload = function() { view = { update: function() { var p = model.position; $('#cat').animate( {left: p.x, top: p.y}, {duration: 'slow', complete: presenter.next} ); } }; model.observers.push(view); $('#button1').click(presenter.click); }
プレゼンターはすごく短い。こんなのでもプレゼンターと言うのか?
var presenter = { click: function() { model.start([ {x:280,y:0}, {x:15,y:180}, {x:500,y:100}, {x:0,y:0} ]); }, next: function() { model.next(); } };
MVPパターンを何か勘違いしてるだろうか?
0 件のコメント:
コメントを投稿
次の投稿
前の投稿
ホーム
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿