jQueryでprototype.jsのbindみたいなの
jQueryでスコープを維持したままイベントリスナーを実行するのってどうすればいいんだろと思ってたんですが、bind()ってのがあるんですね。
var Sample = function() { this.initialize.apply(this, arguments); } Sample.prototype = { initialize: function() { this.message = "Hello world."; $("#foo").bind("click", {obj: this}, this.show); }, show: function(event) { var self = event.data.obj; $("#bar").html(self.message); } } $(function() { new Sample(); });
bind()の第二引数にオブジェクトで指定することができて、イベントリスナー側で受け取れます。
なので、thisを指定して受け取ればスコープ内のデータを使うことができます。
これに早く気づいていれば!
こんなの作っていちいち「$("#foo").click(applyFunc(this, this.show));」とかやってた。
var applyFunc = function(fn, context) { return function() { fn.apply(context, arguments); } }
ドキュメントよーく見ないとダメですね。。。