标签:
define(function(){ function ScrollMoreInfo($wraper , loadDataFunc , json_ids , perNum , tpl_info) { this.$wraper = $wraper; this.loadDataFunc = loadDataFunc; this.originIds = json_ids; this.tpl = tpl_info; this.isAppendIng = false; this.perNum = perNum; this.leftData = []; } ScrollMoreInfo.prototype = new Hnb.event(); $.extend(ScrollMoreInfo.prototype , { init: function(){ var self = this; self.initData(); self.register(); }, initData: function(){ var self = this; self.start = self.originIds.length; self.isEnd = false; self.idRef = {}; for(var i in self.originIds) { if(self.originIds[i]){ self.idRef[self.originIds[i] + "_"] = true; } } }, register: function(){ var self = this; $(window).scroll(function(){ var height = $(window).height(); var top = $(window).scrollTop(); var bodyHeight = $("#id_top_wrap").height(); if(height + top > bodyHeight - 100) { //加载数据... self.appendMoreData(); } }); $(window).trigger("scroll"); }, appendMoreData: function(){ var self = this; if(self.isAppendIng){ return; } if(self.leftData.length >= self.perNum){ var arr_data = self.leftData.splice(0 , self.perNum); self.renderData(arr_data); } else if(self.isEnd) { if(self.leftData.length == 0){ self.renderNoMore(); return; } var arr_data = self.leftData.splice(0 , self.perNum); self.renderData(arr_data); if(self.leftData.length == 0){ self.renderNoMore(); } } else { //加载更多数据 self.isAppendIng = true; self._loadData().fail(function(){ self.isEnd = true; }).always(function(){ self.isAppendIng = false; self.appendMoreData(); }); } }, // 尾部图片(no-more-data / data-loading)的展示 renderNoMore: function(){ var self = this; self.$wraper.find(".c-data-no-more").removeClass("dn"); self.$wraper.find(".c-data-loading").addClass("dn"); }, // 数据模板渲染 renderData: function(arr_data){ var self = this; var html = Hnb.ui.tmpl(self.tpl , { arr_infoList : arr_data }); self.$wraper.find(".c-data-loading").before(html); self.trigger("after:render:more:data"); }, // 数据加载 _loadData: function(){ var self = this; var defer = $.Deferred(); self.loadDataFunc(self.start , self.perNum).done(function(json_msg){ if(json_msg.state){ //失败,将现有数据展示到页面,设置为结束 defer.reject(-1); } else { if(json_msg.data.infoList.length < self.perNum){ self.isEnd = true; } self._storeData(json_msg.data.infoList); defer.resolve(); } }).fail(function(){ defer.reject(-1); }); // 数据读取起点 self.start += self.perNum; return defer; }, // 当加载的数据小于每页的长度时,先存储起来 _storeData: function(arr_data){ var self = this; for(var i in arr_data) { if(arr_data[i].id && !self.idRef[arr_data[i].id + "_"]) { self.leftData.push(arr_data[i]); self.idRef[arr_data[i].id + "_"] = true; } } } }); return { create: function($wraper , loadDataFunc , json_dataInit , perNum , tpl_info){ var obj = new ScrollMoreInfo($wraper , loadDataFunc , json_dataInit , perNum , tpl_info); obj.init(); return obj; } } });
[require-js]向下滑动ajax加载的javascript实现
标签:
原文地址:http://www.cnblogs.com/shuman/p/5109899.html