2011-08-09 79 views
0

我有一個jQuery鉤子數組,在將數據加載到網格之前執行。但是,在一種情況下,我想刪除掛鉤,然後將其添加回來以備後用。無論我在做什麼都不是正確的...這可能是一個語法錯誤,因爲我對jQuery還是有點新鮮。任何幫助將不勝感激,謝謝!如何調用存儲在jQuery數組中的函數?

當前代碼:

var preLoad = this.opts.hooks.preLoad.pop(); 
//stuff happens 
//now I want to add the preLoad hook back 
this.opts.hooks.preLoad.push(function(report) { preLoad(report); }); 

編輯 原來,問題出在其它地方的代碼。不過,我仍然想知道如何最好地實現這一點。

+3

這是以任何方式與jQuery? – rid

+0

嗯,我想這只是更多的JavaScript語法 – stinkycheeseman

回答

2

你不能只是添加你刪除的功能嗎?

var preLoad = this.opts.hooks.preLoad.pop(); 
//stuff happens 
//now I want to add the preLoad hook back 
this.opts.hooks.preLoad.push(preLoad); 

而且你確定它總是要刪除陣列中的最後一個?

+0

是的,問題在於不幸的代碼中的其他地方。我一直在這樣做,它不工作,這導致我相信我必須在函數()中包裝preLoad,但我認爲編寫代碼的方式是將鉤子添加到錯誤的對象。我的錯! – stinkycheeseman

4

您可以像存儲在任何其他數組中的任何其他變量一樣訪問它。

this.opts.hooks.preLoad[0](myReport) 
2

這可能與您將函數返回堆棧時「canning」參數「report」的事實有關。

嘗試做這樣的:

var preLoad = this.opts.hooks.preLoad.pop(); 
//stuff happens 
//now I want to add the preLoad hook back 
this.opts.hooks.preLoad.push(preLoad); 

我在這裏http://jsfiddle.net/fWRez/

1

測試了你給我的例子無關使用jQuery,是純JavaScript。另外,要小心你在你的例子中所做的是......不對。試想一下:

var ReportManager { 
    ... 
    replace: function(report) { 
     var preLoad = this.opts.hooks.preLoad.pop(); 
     //stuff happens 
     //now I want to add the preLoad hook back 
     this.opts.hooks.preLoad.push(function(report) { preLoad(report); }); 
    } 
} 

如果執行此:

replace(null); 
replace({foo:'bar'}); 
replace(null); 

this.opts.hooks.preLoad陣列看起來像這樣:

Array(
    0: function(report) { return function(report) { return function(report) { ... } } } 
) 

因爲你是推裹進自己的功能每次執行你的代碼。我不知道爲什麼你需要poppush它又回來了,但這看起來很奇怪。

另外,Javascript是一個非常靈活的語言;這意味着你可以做很多奇怪的東西,如

"hello".concat(" world");   // -> 'hello world' 
0.toString();      // -> '0' 
(function(a) { return a; })("foo"); // -> 'foo' 
(function() { return false; })() || (function() { return true; })(); // -> true (executes both functions) 
(function(i) { return [i*2,i*3,i*4]; })(2)[1]; // -> 6 
$('selector')[0];     // ... 
// etc. 
相關問題