※proxy
代理事件的東西有四種方式
※第一個參數是functon,第二個參數是context(物件)
$(function(){
var me = {
type: "me",
test: function(event) {
$(event.target).css("background-color", "red");
$("div").append(this.type + "<br>" );
$("button").unbind("click", this.test);
}
};
var you = {
type: "you",
test: function(event) {
$("div").append(this.type + " ");
}
};
$("button")
.on("click", $.proxy(me.test, me)) // 只執行一次,因為被unbind了
.on("click", $.proxy(you.test, you)) // you-->都是自己的,很好理解
.on("click", $.proxy(you.test, me)) // me-->右邊是me,type抓的是me的
.on("click", you.test); // button-->按鈕的type
});
----------
<button type="button">Test</button>
<div></div>
※
※第一個參數是context(物件),第二個參數是string
$(function(){
var obj = {
name: "John",
xxx: function() {
$("p").append(this.name);
$("button").off("click", obj.test);
}
};
$("button").on("click", $.proxy(obj, "xxx"));
});
----------
<button>Test</button>
<p></p>
※第二個參數要對應到第一個參數物件裡的名字才有效
※其他方式
第三種和第四種方式是給第三個參數(可以給很多,類似java的「…」),是給第二個參數用的這裡以第二個參數是物件為例
$(function(){
var me = {
type: "dog",
test: function(one, two, event) {
$("p")
.append(one.type + '<br />') // cat
.append(two.type + '<br />') // fish
.append(event.type + '<br />') // click
.append(this.type + '<br />') // dog
.append(event.target.type + '<br />'); // submit
}
};
var you = {type: "cat"};
var they = {type: "fish"};
$("button").on("click", $.proxy(me.test, me, you, they));
});
----------
<button>Test</button>
<p></p>
※event.target.type 這個我不懂
沒有留言:
張貼留言