Created
November 1, 2009 21:52
-
-
Save bradgessler/223746 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Polls the server for new JSON data at a defined interval. Requests are garunteed to not stack up on each other. | |
Example Usage: | |
var poller = $.poller({ | |
url: function(head){ | |
var base = '/messages/'; | |
return (head) ? (base + '?since_id=' + head.result.id) : base; | |
}, | |
receive: function(set){ | |
$(set).each(function(json){ | |
$('#messages').append('<div>' + json.message.id +' was received!</div>'); | |
}); | |
} | |
}); | |
poller.start(); | |
Ugliness | |
- The way head is handled seems inconsistent | |
- There has to be a better way to wrap a value into a function | |
- Not sure how "this" and "that" references are handled in jQuery | |
*/ | |
(function($){ | |
$.extend({ | |
poller: function poller(options){ | |
options = $.extend({ | |
interval: 1000, | |
head: function(set){ return set[0]; } | |
}, options); | |
// Wraps the URL into a function so we can handle pagination in cases where we need | |
// to build an URL based off of what is given in head. | |
if (typeof options.url != 'function'){ | |
var __url__ = options.url; | |
options.url = function wrappedUrl(head){ return __url__; }; | |
} | |
var head; | |
// This is our interupt if we want to stop polling | |
var polling = true; | |
// HACK Is 'that' the correct style in jQuery??? | |
var that = { | |
start: function start(){ | |
$.getJSON(options.url(head), function(set){ | |
head = options.head(set); | |
console.log('parseHead', head); | |
if (options.receive) { options.receive(set, that); } | |
if (polling) { | |
setTimeout(function(){ | |
$.poller(options).start(); | |
}, options.interval); | |
} | |
}); | |
return that; | |
}, | |
stop: function stop(){ | |
polling = false; | |
return that; | |
}, | |
options: options, | |
head: function(){ return head; } | |
}; | |
return that; | |
} | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment