开发者

.setInterval() and Drupal.attachBehaviors are causing my js file to run multiple instances

I am delivering ajax content to a page and I need to reattach Drupal behaviors to that content. I am using the following jquery. The code polls the server every 5 seconds for data and displays it. 开发者_如何学JAVA

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.

When I try to add Drupal.attachBehaviors(), it appears to be relaunching new instances of my JS file. When I look in firebug, I see a new instance of my js file running, then 4, then 8, then 16, then 32. Before long, I have 100's of if the same .js file running and of course, the browser locks up. Thank you greatly for any insights.


It looks like you've solved your own problem.

Side note (too messy for a comment): please don't pass strings to setTimeout and setInterval; it's eval in disguise. Pass the function itself:

setInterval(god_geo_event, 5000);

or pass an anonymous function:

setInterval(function ()
{
    god_geo_event();
}, 5000); 


Pretty sure the answer will be that the function called by setInterval has (), when it should not. setInterval("god_geo_event()", 5000);

should be.

setInterval("god_geo_event", 5000);  

We are not passing the results to setInterval, we are passing the function call. Still need to test but I think this is the problem that has eluded hundreds on 3 different boards for thre three months.. Amazing.


Check that you call your function in the #document context.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜