2011-02-22 46 views
0

我將ajax內容傳遞到頁面,我需要將Drupal行爲重新附加到該內容。我正在使用下面的jQuery。該代碼每5秒查詢一次數據並顯示它。.setInterval()和Drupal.attachBehaviors導致我的js文件運行多個實例

Drupal.behaviors.god_geo = function(context) { 
setInterval("god_geo_event()", 5000); // call god_geo_event() every 5 seconds 
}; 

/** 
* A Function to fetch quotes from the server and display in the designated 
* area. 
*/ 
function god_geo_event(){ 
$.getJSON(Drupal.settings.god_geo.json_url, function(data) { 
    if(!data.status || data.status == 0) { 
     $("#god_geo_occupants-text").html(data.event.occupants); 
     Drupal.attachBehaviors("#god_geo_occupants-text"); //THIS CRASHES BROWSER. 
    } 
}); //end inline function. 

當我嘗試添加Drupal.attachBehaviors()時,它似乎是重新啓動我的JS文件的新實例。當我查看螢火蟲時,我看到我的js文件的一個新實例正在運行,然後是4,然後是8,然後是16,然後是32.不久之後,如果有相同的.js文件運行,並且當前瀏覽器鎖定向上。非常感謝你的任何見解。

+0

我想我有它。只需回答。 – 2011-02-23 12:22:42

回答

0

很確定的答案是,setInterval調用的函數有(),當它不應該。 setInterval(「god_geo_event()」,5000);

應該是。

setInterval("god_geo_event", 5000); 

我們沒有將結果傳遞給setInterval,我們正在傳遞函數調用。仍然需要測試,但我認爲這是三個月內在三個不同的電路板上數以百計的問題。驚人的。

+0

你應該接受你自己的答案。 – 2011-06-04 04:24:14

1

看起來你已經解決了你自己的問題。

附註(太麻煩的評論):請不要將字符串傳遞給setTimeoutsetInterval;它是僞裝的eval。通過函數本身:

setInterval(god_geo_event, 5000); 

或傳遞一個匿名函數:

您致電功能在#document方面
setInterval(function() 
{ 
    god_geo_event(); 
}, 5000); 
0

檢查。

Drupal.behaviors.god_geo = function(context) { 
    setInterval(function() { 
    if ($(context).length && $(context)[0].nodeName == '#document') { 
     god_geo_event(); 
    } 
    }, 5000); 
};