2012-08-13 74 views
0

我很新的jQuery和JavaScript的。我正在研究Splunk如何實現其某些模塊並且感到困惑。jQuery的嵌套綁定

這是一個帶很多的東西離開了示例代碼。

this.input.bind("focus",this.onInputFocus.bind(this)) 

this.input指用於SearchBar的文本框。後來,在該文件中,onInputFocus聲明

onInputFocus: function(evt) { 
    ... 
    ... 
    return true 
}, 

我知道了「this.input.bind」語句告訴當一個人點擊在文本框中,但我不明白.bind執行onInputFocus瀏覽器(這)在事件處理結束時。請向我解釋這個符號,以便我瞭解發生了什麼。

回答

1

「外」 bind被結合的事件處理程序,以使用jQuery的focus事件。

「內部」Function.bind正在創建綁定到特定上下文的函數(使this等於該函數被調用時的上下文)。這不需要框架(但需要現代瀏覽器)。

因此,在這種情況下,調用Function.bind是確保每一次input聚焦時,onInputFocus方法的情況下被設置爲this電流值(這可能是你使用的部件/組件)。這是必要的,因爲它通常是事件發生的元素。

The MDN article on Function.bind有一個很好的解釋。


爲了更好地說明是如何工作的,舉一個簡單的例子:

HTML:

​<button id="test" type="button">Test</button> 
<button id="test2" type="button">Test 2</button> 
<div id="target"></div> 

的JavaScript

var fill = function() { 
    $(this).css('background-color', 'yellow'); 
}; 
/* button#test will be colored yellow */ 
$("#test").bind("click", fill); 

/* div#target will be colored yellow */ 
$("#test2").bind("click", fill.bind($("#target"))); 

在第一事件綁定,fill被調用並this設置爲#test(因爲這是所單擊元素)。

在第二個,fill被再次調用,但this設置爲#target,因爲在Function.bind裏面的事件綁定的調用。

例子:http://jsfiddle.net/GK7L8/

+0

謝謝安德魯 - 更清晰 – 2012-08-13 00:52:33