Skip to content

Instantly share code, notes, and snippets.

@ktusznio
Created December 12, 2012 00:14
Show Gist options
  • Save ktusznio/4263661 to your computer and use it in GitHub Desktop.
Save ktusznio/4263661 to your computer and use it in GitHub Desktop.
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