什麼是推薦的方式來傳遞緩存的jQuery引用,例如$domContainer
在var $domContainer = $('#container');
作爲回調功能,如果功能是在$(document).ready()
之前和之外定義的?將jQuery引用傳遞給回調函數或插件的標準方法
實施例:
<script src="/plugins.js"></script>
在可重複使用的功能這個外部文件
function rowAction (event) { // how do I get context here?
// how can I access $domTable and $domFilters
// I can access $(event.target) and traverse the dom
// back to $domTable, but $domTable is not defined
// in the external file, although a reference is cached
// in the local scope of $(document).ready();
// likewise, $domTable could be accessed through event.delegateTarget
// however, how can I pass $domFilters, and other vars?
}
在主腳本
<script src="/scripts.js"></script>
標準文件準備
$(document).ready(function(){
// Cached References
var $domFilters = $('#form .filter'), // more than 1 reference returned
$domTable = $('#results'); // 1 reference returned
$domTable.on('click','.menu',rowAction);// reference function in plugins.js
// how do I pass $domFilters to rowAction to avoid dom lookups?
// I could pass $domFilters to a plugin like $(...).plugin({f:$domFilters});
// if it had optional arguments, but if it's not a plugin, what's the
// equivalent way to do it?
});
這樣做的方式是使用內聯函數來包裝回調函數名稱?
任何指向標準做法的指針都會受到歡迎。
嗨詹姆斯,在這個特定的情況下,'event.delegateTarget'是一個完美的答案,但總的來說,你將如何去傳遞額外的緩存變量。我使用了一個不好的例子,因爲在這種情況下jQuery已經有了一個直接的引用(我不知道這個),但是我更常用的思路是,如果我有其他緩存變量,這通常是這種情況。我會用更相關的上下文來更新這個問題。 – MyStream 2013-03-21 09:36:37
嗨,詹姆斯,在這種情況下,我們不是在$ domFilters上執行操作,但我們需要將它傳遞給引用的外部函數。因此,例如,$ domFilters將包含對象的引用,這些對象具有我們想要在外部函數中讀取的值。然而,我們想要做的是在需要時將參考傳遞給外部函數。 .each()不會那樣做,因爲調用應該發生在事件上。 – MyStream 2013-03-21 10:12:29
您的外部功能是否設置爲處理集合?你只有一個事件參數,除非它正在訪問參數arraytype,例如'Array.prototype.slice.call(arguments,1);',那麼你可以不用額外的參數。 – 2013-03-21 10:21:48