Created
October 8, 2013 07:32
-
-
Save seifsallam/6880977 to your computer and use it in GitHub Desktop.
LoadMoreMixin for EmberJS
This file contains hidden or 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
###* | |
# | |
# Loadmore Mixin | |
# It works with limit/skip & max_id | |
# | |
# SETUP: To Use it add this mixin to both View & Controller | |
# | |
# HOW IT WORKS: | |
# It binds the view to scroll, and if user scrolled to the | |
# bottom it sends modelName to controller. | |
# Controller then sets loadingMore to true (to be show | |
# Loading indicator) then it gets Model meta. As long as | |
# meta.count is not zero load more data. | |
# Load data based on paging type, and push results into | |
# ArrayController, and finally set loading more to false | |
# | |
# | |
### | |
App.LoadMore = Ember.Mixin.create( | |
loadingMore: false | |
# | |
# View | |
# | |
didInsertElement: -> | |
view = this | |
$(window).bind 'scroll', -> | |
view.didScroll() | |
# When this view is destroyed we need to unbind the scroll event. | |
willDestroyElement: -> | |
$(window).unbind 'scroll' | |
isScrolledToBottom: -> | |
distanceToTop = $(document).height() - $(window).height() | |
top = $(document).scrollTop() | |
top is distanceToTop | |
didScroll: -> | |
if @isScrolledToBottom() | |
model = @get('controller.model.type.typeKey') # Get Model (ex: post) | |
@get('controller').send('loadMore', model) | |
# | |
# Controller | |
# | |
startLoading: (model) -> | |
@set 'loadingMore', true | |
console.log "Loading more #{model}" | |
actions: | |
loadMore: (model) -> | |
return if @get 'loadingMore', true | |
@startLoading(model) | |
self = this | |
metadata = @store.metadataFor(model) | |
pushObjects = (data) -> | |
self.content.pushObjects data.content | |
if metadata.count is 0 | |
self.set 'endOfFeed', true | |
else | |
self.set 'loadingMore', false | |
if metadata.count is 0 | |
@set 'endOfFeed', true | |
else | |
type = @get 'currentFeed' | |
if @get('paging') is 'skip' | |
store = @store | |
@store.find(model, | |
skip: metadata.next_skip | |
type: type | |
).then pushObjects | |
else | |
@store.find(model, | |
max_id: metadata.max_id | |
type: type | |
).then pushObjects | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment