bloody-jquery-plugins icon indicating copy to clipboard operation
bloody-jquery-plugins copied to clipboard

Fixed case where an error occurs if a handle unsubscribes in the middle of a publish

Open bentruyman opened this issue 14 years ago • 3 comments

You can see where it errors here: http://jsfiddle.net/EG4CL/

This is happening due to the way jQuery's each method is implemented. In this case, jQuery caches the length property in the for loop it uses to iterate over the items. When splice is used, that array (of course) is shortened but jQuery is still going to try to keep iterating using the original length.

When that happens (in jQuery), this becomes window and not the callback the user wants:

cache[topic] && d.each(cache[topic], function(){
  this.apply(d, args || []);
});

bentruyman avatar Oct 29 '10 18:10 bentruyman

Basically, the fix I came up with is to lookup the length property of the callbacks array every iteration in the for loop.

bentruyman avatar Oct 29 '10 18:10 bentruyman

half tempted to just rip $.each use out of there and for(;;;) that shit.

phiggins42 avatar Mar 09 '11 13:03 phiggins42

There still is a problem with this solution. You prevent the said errors, but one of the subscription may not fire. Say cache[topic][0] removes itself. on the next iteration of the loop cache[topic][1] will already be cache[topic][0] and therefore it will not fire.

eladzlot avatar Jun 20 '12 21:06 eladzlot