個人的に
どーやるんだろ、っておもってたことができたので、jQuery.proxy()のメモ。
説明が面倒だからコードで。
例えば最も単純に書くとこうなるとする
var message = 'hello.';
$('#button').click(function()
{
alert(message);
});
クラスにするとこうなる
var message='hello.';
var ExampleButtonController = function(element)
{
element.click(function()
{
alert(message);
});
}
new ExampleButtonController($('#button'));
messageをコンストラクタで渡そう
var ExampleButtonController = function(element,message)
{
element.click(function()
{
alert(message);
});
}
new ExampleButtonController($('#button'),'hello.');
でまあここまではいいけど、click()の引数の無名関数が再利用できないとかいけてないからクラスメソッドにしたい。(カプセル化は今は忘れる)
var ExampleButtonController = function(element,message)
{
element.click(this.onClick);
}
ExampleButtonController.prototype={
onClick:function()
{
alert(message);
}
};
new ExampleButtonController($('#button'),'hello.');
となるけど、onClickで参照してるmessageはスコープ外。ダメ。インスタンス変数にしよう。じゃあ
var ExampleButtonController = function(element,message)
{
this.message=message;
element.click(this.onClick);
}
ExampleButtonController.prototype={
onClick:function(event)
{
alert(this.message);
}
};
new ExampleButtonController($('#button'),'hello.');
でいいじゃないか、とみせかけてこれもダメ。
onClickのスコープのthisはAS3と違ってインスタンスじゃない。イベントのターゲット。AS2はこんなだったよね。
そこでjQuery.proxy()の登場で
var ExampleButtonController = function(element,message)
{
this.message=message;
element.click($.proxy(this.onClick,this));
}
ExampleButtonController.prototype={
onClick:function(event)
{
alert(this.message);
}
};
new ExampleButtonController($('#button'),'hello.');
と書くと、onClickのthisがインスタンスになる。jQuery.proxyをはさんで、thisを事前に指定する。
じゃあ今までthisで取得してたイベントのターゲットはどうすんのって言うとまあもちろんインスタンス変数に持っておいてもいいんだけどこれもASと一緒で(というかW3Cの仕様らしい)
var ExampleButtonController = function(element,message)
{
this.message=message;
element.click($.proxy(this.onClick,this));
}
ExampleButtonController.prototype={
onClick:function(event)
{
//これが、通常jQuery使ってる場合のthisにあたる
alert(event.currentTarget);
alert(this.message);
}
};
new ExampleButtonController($('#button'),'hello.');
event.currentTargetでとれます。
event.targetとかもあります。まあASといっしょですね。
ということで、jQuery.proxy()を使うと、イベントハンドラを無名関数じゃなくできるので慣れた書き方っぽくできますよと。いうかんじでした。
でもJSでのオブジェクト指向はまだまだ勉強不足。
継承とかも結局どれがいーのかかたまってないし。
むずかしー
