Created
December 12, 2012 00:14
-
-
Save ktusznio/4263661 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
Threadflip.InfiniteScrollCollection = | |
infiniteScroll: (options) -> | |
success = options.success || -> | |
offset = options.offset || 400 | |
enabled = false | |
start = (params = {}) -> | |
unless enabled | |
# Bind to the scroll event. | |
$(window).scroll onScroll | |
enabled = true | |
if params.fetch is true | |
fetchNextPage params | |
stop = -> | |
if enabled | |
$(window).unbind "scroll", onScroll | |
enabled = false | |
fetchNextPage = (params = {}) -> | |
_.extend params, | |
add: true | |
success: onSuccess | |
@fetchNextPage params | |
fetchNextPage = _.bind(fetchNextPage, @) | |
isEnabled = -> enabled | |
onScroll = -> | |
if $(window).scrollTop() >= $(document).height() - $(window).height() - offset | |
fetchNextPage() | |
onScroll = _.bind(onScroll, @) | |
onSuccess = (collection, response) -> | |
rawNewItems = response[collection.jsonRoot()] | |
newItems = [] | |
for rawItem in rawNewItems | |
newItem = new collection.model(rawItem) | |
newItems.push newItem | |
# Pass new items to the success handler. | |
success collection, newItems | |
# Export a command responder. | |
commands = {start, stop, isEnabled} | |
@infiniteScroll = (command, params) -> | |
if _.isString(command) | |
commands[command]? params |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment