Skip to content

Instantly share code, notes, and snippets.

@banyan
Created February 15, 2010 15:24
Show Gist options
  • Select an option

  • Save banyan/304723 to your computer and use it in GitHub Desktop.

Select an option

Save banyan/304723 to your computer and use it in GitHub Desktop.
// jQuery 1.4 jQuery.proxy に関してのまとめ
//
// 1, $.proxy を使わない
var obj = {
name: "John",
test: function() {
console.log(this); // => <input class="buttons" type="button" value="buttons_1"> (this は bind された .buttons の element)
alert(this.name); // => ''
}
};
$(".buttons").click(obj.test);
// 2, $.proxy を使う
var obj = {
name: "John",
test: function() {
console.log(this); // => Object name=John (this は $.proxy で渡した Object 自身)
alert(this.name); // => 'John'
}
};
$(".buttons").click($.proxy(obj, 'test'));
// 3, $.proxy を使い bind された要素も取得
var obj = {
name: "John",
test: function(event) {
console.log(event.currentTarget); // => <input class="buttons" type="button" value="buttons_1"> (event.currentTarget として bind された要素を取得する)
console.log(this); // => Object name=John (this は $.proxy で渡した Object 自身)
$(event.currentTarget).unbind("click", obj.test);
}
};
$(".buttons").click($.proxy(obj, 'test'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment