pagination.js 37.8 KB
Newer Older
S
Initial  
superRaytin 已提交
1
/*
2
 * pagination.js 2.0.7
S
Initial  
superRaytin 已提交
3 4 5
 * A jQuery plugin to provide simple yet fully customisable pagination.
 * https://github.com/superRaytin/paginationjs
 *
S
superRaytin 已提交
6
 * Homepage: http://paginationjs.com
7
 *
S
superRaytin 已提交
8
 * Copyright 2014-2100, superRaytin
S
Initial  
superRaytin 已提交
9 10 11
 * Released under the MIT license.
 */

S
superRaytin 已提交
12
(function(global, $) {
S
Initial  
superRaytin 已提交
13

S
superRaytin 已提交
14
    if (typeof $ === 'undefined') {
S
Initial  
superRaytin 已提交
15 16 17 18 19 20 21 22 23 24
        throwError('Pagination requires jQuery.');
    }

    var pluginName = 'pagination';

    var pluginHookMethod = 'addHook';

    var eventPrefix = '__pagination-';

    // Conflict, use backup
S
superRaytin 已提交
25
    if ($.fn.pagination) {
S
Initial  
superRaytin 已提交
26 27 28
        pluginName = 'pagination2';
    }

S
superRaytin 已提交
29
    $.fn[pluginName] = function(options) {
S
Initial  
superRaytin 已提交
30

S
superRaytin 已提交
31
        if (typeof options === 'undefined') {
S
Initial  
superRaytin 已提交
32 33 34 35 36 37 38
            return this;
        }

        var container = $(this);

        var pagination = {

S
superRaytin 已提交
39
            initialize: function() {
S
Initial  
superRaytin 已提交
40 41 42
                var self = this;

                // Save attributes of current instance
S
superRaytin 已提交
43
                if (!container.data('pagination')) {
S
Initial  
superRaytin 已提交
44 45 46 47
                    container.data('pagination', {});
                }

                // Before initialize
S
superRaytin 已提交
48
                if (self.callHook('beforeInit') === false) return;
S
Initial  
superRaytin 已提交
49 50

                // If pagination has been initialized, destroy it
S
superRaytin 已提交
51
                if (container.data('pagination').initialized) {
S
Initial  
superRaytin 已提交
52 53 54
                    $('.paginationjs', container).remove();
                }

S
superRaytin 已提交
55 56 57
                // Whether to disable Pagination at the initialization
                self.disabled = !!attributes.disabled;

S
Initial  
superRaytin 已提交
58 59 60 61 62 63 64
                // Passed to the callback function
                var model = self.model = {
                    pageRange: attributes.pageRange,
                    pageSize: attributes.pageSize
                };

                // "dataSource"`s type is unknown, parse it to find true data
S
superRaytin 已提交
65
                self.parseDataSource(attributes.dataSource, function(dataSource) {
S
Initial  
superRaytin 已提交
66

L
leon.shi 已提交
67
                    // Whether pagination is sync mode
68
                    self.sync = Helpers.isArray(dataSource);
S
superRaytin 已提交
69
                    if (self.sync) {
S
Initial  
superRaytin 已提交
70 71 72 73 74 75 76
                        model.totalNumber = attributes.totalNumber = dataSource.length;
                    }

                    // Obtain the total number of pages
                    model.totalPage = self.getTotalPage();

                    // Less than one page
S
superRaytin 已提交
77 78
                    if (attributes.hideWhenLessThanOnePage) {
                        if (model.totalPage <= 1) return;
79
                    }
S
Initial  
superRaytin 已提交
80 81 82 83

                    var el = self.render(true);

                    // Extra className
S
superRaytin 已提交
84
                    if (attributes.className) {
S
Initial  
superRaytin 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98
                        el.addClass(attributes.className);
                    }

                    model.el = el;

                    // Load template
                    container[attributes.position === 'bottom' ? 'append' : 'prepend'](el);

                    // Binding events
                    self.observer();

                    // initialized flag
                    container.data('pagination').initialized = true;

S
superRaytin 已提交
99
                    // After initialized
S
Initial  
superRaytin 已提交
100 101 102 103 104 105
                    self.callHook('afterInit', el);

                });

            },

S
superRaytin 已提交
106
            render: function(isBoot) {
S
Initial  
superRaytin 已提交
107 108 109 110

                var self = this;
                var model = self.model;
                var el = model.el || $('<div class="paginationjs"></div>');
S
superRaytin 已提交
111
                var isForced = isBoot !== true;
S
Initial  
superRaytin 已提交
112

S
superRaytin 已提交
113 114
                // Before render
                self.callHook('beforeRender', isForced);
S
Initial  
superRaytin 已提交
115 116 117 118 119 120 121 122

                var currentPage = model.pageNumber || attributes.pageNumber;
                var pageRange = attributes.pageRange;
                var totalPage = model.totalPage;

                var rangeStart = currentPage - pageRange;
                var rangeEnd = currentPage + pageRange;

S
superRaytin 已提交
123
                if (rangeEnd > totalPage) {
S
Initial  
superRaytin 已提交
124 125 126 127 128
                    rangeEnd = totalPage;
                    rangeStart = totalPage - pageRange * 2;
                    rangeStart = rangeStart < 1 ? 1 : rangeStart;
                }

S
superRaytin 已提交
129
                if (rangeStart <= 1) {
S
Initial  
superRaytin 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142
                    rangeStart = 1;

                    rangeEnd = Math.min(pageRange * 2 + 1, totalPage);
                }

                el.html(self.createTemplate({
                    currentPage: currentPage,
                    pageRange: pageRange,
                    totalPage: totalPage,
                    rangeStart: rangeStart,
                    rangeEnd: rangeEnd
                }));

S
superRaytin 已提交
143 144
                // After render
                self.callHook('afterRender', isForced);
S
Initial  
superRaytin 已提交
145 146 147 148 149

                return el;
            },

            // Create template
S
superRaytin 已提交
150
            createTemplate: function(args) {
S
Initial  
superRaytin 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

                var self = this;
                var currentPage = args.currentPage;
                var totalPage = args.totalPage;
                var rangeStart = args.rangeStart;
                var rangeEnd = args.rangeEnd;

                var totalNumber = attributes.totalNumber;

                var showPrevious = attributes.showPrevious;
                var showNext = attributes.showNext;
                var showPageNumbers = attributes.showPageNumbers;
                var showNavigator = attributes.showNavigator;
                var showGoInput = attributes.showGoInput;
                var showGoButton = attributes.showGoButton;

                var pageLink = attributes.pageLink;
                var prevText = attributes.prevText;
                var nextText = attributes.nextText;
                var ellipsisText = attributes.ellipsisText;
                var goButtonText = attributes.goButtonText;

                var classPrefix = attributes.classPrefix;
                var activeClassName = attributes.activeClassName;
                var disableClassName = attributes.disableClassName;
                var ulClassName = attributes.ulClassName;

                var formatNavigator = $.isFunction(attributes.formatNavigator) ? attributes.formatNavigator() : attributes.formatNavigator;
                var formatGoInput = $.isFunction(attributes.formatGoInput) ? attributes.formatGoInput() : attributes.formatGoInput;
                var formatGoButton = $.isFunction(attributes.formatGoButton) ? attributes.formatGoButton() : attributes.formatGoButton;

S
superRaytin 已提交
182 183 184
                var autoHidePrevious = $.isFunction(attributes.autoHidePrevious) ? attributes.autoHidePrevious() : attributes.autoHidePrevious;
                var autoHideNext = $.isFunction(attributes.autoHideNext) ? attributes.autoHideNext() : attributes.autoHideNext;

S
Initial  
superRaytin 已提交
185 186 187 188 189 190 191 192 193
                var header = $.isFunction(attributes.header) ? attributes.header() : attributes.header;
                var footer = $.isFunction(attributes.footer) ? attributes.footer() : attributes.footer;

                var html = '';
                var goInput = '<input type="text" class="J-paginationjs-go-pagenumber">';
                var goButton = '<input type="button" class="J-paginationjs-go-button" value="'+ goButtonText +'">';
                var formattedString;
                var i;

S
superRaytin 已提交
194
                if (header) {
S
Initial  
superRaytin 已提交
195 196 197 198 199 200 201 202 203 204

                    formattedString = self.replaceVariables(header, {
                        currentPage: currentPage,
                        totalPage: totalPage,
                        totalNumber: totalNumber
                    });

                    html += formattedString;
                }

S
superRaytin 已提交
205
                if (showPrevious || showPageNumbers || showNext) {
S
Initial  
superRaytin 已提交
206 207 208

                    html += '<div class="paginationjs-pages">';

S
superRaytin 已提交
209
                    if (ulClassName) {
S
Initial  
superRaytin 已提交
210 211 212 213 214 215
                        html += '<ul class="'+ ulClassName +'">';
                    }
                    else{
                        html += '<ul>';
                    }

S
superRaytin 已提交
216
                    // Previous page button
S
superRaytin 已提交
217 218 219
                    if (showPrevious) {
                        if (currentPage === 1) {
                            if (!autoHidePrevious) {
S
superRaytin 已提交
220 221
                                html += '<li class="'+ classPrefix +'-prev '+ disableClassName +'"><a>'+ prevText +'<\/a><\/li>';
                            }
S
Initial  
superRaytin 已提交
222 223 224 225 226 227 228
                        }
                        else{
                            html += '<li class="'+ classPrefix +'-prev J-paginationjs-previous" data-num="'+ (currentPage - 1) +'" title="Previous page"><a href="'+ pageLink +'">'+ prevText +'<\/a><\/li>';
                        }
                    }

                    // Page numbers
S
superRaytin 已提交
229 230 231 232
                    if (showPageNumbers) {
                        if (rangeStart <= 3) {
                            for(i = 1; i < rangeStart; i++) {
                                if (i == currentPage) {
S
Initial  
superRaytin 已提交
233 234 235 236 237 238 239 240
                                    html += '<li class="'+ classPrefix +'-page J-paginationjs-page '+ activeClassName +'" data-num="'+ i +'"><a>'+ i +'<\/a><\/li>';
                                }
                                else{
                                    html += '<li class="'+ classPrefix +'-page J-paginationjs-page" data-num="'+ i +'"><a href="'+ pageLink +'">'+ i +'<\/a><\/li>';
                                }
                            }
                        }
                        else{
S
superRaytin 已提交
241
                            if (attributes.showFirstOnEllipsisShow) {
242
                                html += '<li class="'+ classPrefix +'-page '+ classPrefix +'-first J-paginationjs-page" data-num="1"><a href="'+ pageLink +'">1<\/a><\/li>';
S
Initial  
superRaytin 已提交
243 244 245 246 247 248
                            }

                            html += '<li class="'+ classPrefix +'-ellipsis '+ disableClassName +'"><a>'+ ellipsisText +'<\/a><\/li>';
                        }

                        // Main loop
S
superRaytin 已提交
249 250
                        for(i = rangeStart; i <= rangeEnd; i++) {
                            if (i == currentPage) {
S
Initial  
superRaytin 已提交
251 252 253 254 255 256 257
                                html += '<li class="'+ classPrefix +'-page J-paginationjs-page '+ activeClassName +'" data-num="'+ i +'"><a>'+ i +'<\/a><\/li>';
                            }
                            else{
                                html += '<li class="'+ classPrefix +'-page J-paginationjs-page" data-num="'+ i +'"><a href="'+ pageLink +'">'+ i +'<\/a><\/li>';
                            }
                        }

S
superRaytin 已提交
258 259
                        if (rangeEnd >= totalPage - 2) {
                            for(i = rangeEnd + 1; i <= totalPage; i++) {
S
Initial  
superRaytin 已提交
260 261 262 263 264 265
                                html += '<li class="'+ classPrefix +'-page J-paginationjs-page" data-num="'+ i +'"><a href="'+ pageLink +'">'+ i +'<\/a><\/li>';
                            }
                        }
                        else{
                            html += '<li class="'+ classPrefix +'-ellipsis '+ disableClassName +'"><a>'+ ellipsisText +'<\/a><\/li>';

S
superRaytin 已提交
266
                            if (attributes.showLastOnEllipsisShow) {
267
                                html += '<li class="'+ classPrefix +'-page '+ classPrefix +'-last J-paginationjs-page" data-num="'+ totalPage +'"><a href="'+ pageLink +'">'+ totalPage +'<\/a><\/li>';
S
Initial  
superRaytin 已提交
268 269 270 271
                            }
                        }
                    }

S
superRaytin 已提交
272
                    // Next page button
S
superRaytin 已提交
273 274 275
                    if (showNext) {
                        if (currentPage == totalPage) {
                            if (!autoHideNext) {
S
superRaytin 已提交
276 277
                                html += '<li class="'+ classPrefix +'-next '+ disableClassName +'"><a>'+ nextText +'<\/a><\/li>';
                            }
S
Initial  
superRaytin 已提交
278 279 280 281 282 283 284 285 286 287 288
                        }
                        else{
                            html += '<li class="'+ classPrefix +'-next J-paginationjs-next" data-num="'+ (currentPage + 1) +'" title="Next page"><a href="'+ pageLink +'">'+ nextText +'<\/a><\/li>';
                        }
                    }

                    html += '<\/ul><\/div>';

                }

                // Navigator
S
superRaytin 已提交
289
                if (showNavigator) {
S
Initial  
superRaytin 已提交
290

S
superRaytin 已提交
291
                    if (formatNavigator) {
S
Initial  
superRaytin 已提交
292 293 294 295 296 297 298 299 300 301 302 303

                        formattedString = self.replaceVariables(formatNavigator, {
                            currentPage: currentPage,
                            totalPage: totalPage,
                            totalNumber: totalNumber
                        });

                        html += '<div class="'+ classPrefix +'-nav J-paginationjs-nav">'+ formattedString +'<\/div>';
                    }
                }

                // Go input
S
superRaytin 已提交
304
                if (showGoInput) {
S
Initial  
superRaytin 已提交
305

S
superRaytin 已提交
306
                    if (formatGoInput) {
S
Initial  
superRaytin 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319

                        formattedString = self.replaceVariables(formatGoInput, {
                            currentPage: currentPage,
                            totalPage: totalPage,
                            totalNumber: totalNumber,
                            input: goInput
                        });

                        html += '<div class="'+ classPrefix +'-go-input">'+ formattedString +'</div>';
                    }
                }

                // Go button
S
superRaytin 已提交
320
                if (showGoButton) {
S
Initial  
superRaytin 已提交
321

S
superRaytin 已提交
322
                    if (formatGoButton) {
S
Initial  
superRaytin 已提交
323 324 325 326 327 328 329 330 331 332 333 334

                        formattedString = self.replaceVariables(formatGoButton, {
                            currentPage: currentPage,
                            totalPage: totalPage,
                            totalNumber: totalNumber,
                            button: goButton
                        });

                        html += '<div class="'+ classPrefix +'-go-button">'+ formattedString +'</div>';
                    }
                }

S
superRaytin 已提交
335
                if (footer) {
S
Initial  
superRaytin 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349

                    formattedString = self.replaceVariables(footer, {
                        currentPage: currentPage,
                        totalPage: totalPage,
                        totalNumber: totalNumber
                    });

                    html += formattedString;
                }

                return html;
            },

            // Go to the specified page
S
superRaytin 已提交
350
            go: function(number, callback) {
S
Initial  
superRaytin 已提交
351 352 353 354

                var self = this;
                var model = self.model;

S
superRaytin 已提交
355
                if (self.disabled) return;
S
Initial  
superRaytin 已提交
356 357 358 359 360 361 362 363

                var pageNumber = number;
                var pageSize = attributes.pageSize;
                var totalPage = model.totalPage;

                pageNumber = parseInt(pageNumber);

                // Page number out of bounds
S
superRaytin 已提交
364
                if (!pageNumber || pageNumber < 1 || pageNumber > totalPage) return;
S
Initial  
superRaytin 已提交
365

L
leon.shi 已提交
366
                // Sync mode
S
superRaytin 已提交
367
                if (self.sync) {
S
Initial  
superRaytin 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
                    render(self.getDataSegment(pageNumber));
                    return;
                }

                var postData = {};
                var alias = attributes.alias || {};

                postData[alias.pageSize ? alias.pageSize : 'pageSize'] = pageSize;
                postData[alias.pageNumber ? alias.pageNumber : 'pageNumber'] = pageNumber;

                var formatAjaxParams = {
                    type: 'get',
                    cache: false,
                    data: {},
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                    dataType: 'json',
                    async: true
                };

                $.extend(true, formatAjaxParams, attributes.ajax);
                $.extend(formatAjaxParams.data || {}, postData);

                formatAjaxParams.url = attributes.dataSource;
S
superRaytin 已提交
391
                formatAjaxParams.success = function(response) {
S
Initial  
superRaytin 已提交
392 393
                    render(self.filterDataByLocator(response));
                };
S
superRaytin 已提交
394
                formatAjaxParams.error = function(jqXHR, textStatus, errorThrown) {
S
Initial  
superRaytin 已提交
395
                    attributes.formatAjaxError && attributes.formatAjaxError(jqXHR, textStatus, errorThrown);
S
superRaytin 已提交
396
                    self.enable();
S
Initial  
superRaytin 已提交
397 398
                };

S
superRaytin 已提交
399
                self.disable();
S
Initial  
superRaytin 已提交
400 401 402

                $.ajax(formatAjaxParams);

S
superRaytin 已提交
403
                function render(data) {
羽牧 已提交
404 405

                    // Before paging
S
superRaytin 已提交
406
                    if (self.callHook('beforePaging', pageNumber) === false) return false;
羽牧 已提交
407

S
Initial  
superRaytin 已提交
408 409 410 411 412 413 414
                    // Pagination direction
                    model.direction = typeof model.pageNumber === 'undefined' ? 0 : (pageNumber > model.pageNumber ? 1 : -1);

                    model.pageNumber = pageNumber;

                    self.render();

S
superRaytin 已提交
415
                    if (self.disabled && !self.sync) {
S
superRaytin 已提交
416 417
                        // enable
                        self.enable();
S
Initial  
superRaytin 已提交
418 419 420 421 422 423
                    }

                    // cache model data
                    container.data('pagination').model = model;

                    // format result before execute callback
S
superRaytin 已提交
424
                    if ($.isFunction(attributes.formatResult)) {
S
Initial  
superRaytin 已提交
425
                        var cloneData = $.extend(true, [], data);
S
superRaytin 已提交
426
                        if (!Helpers.isArray(data = attributes.formatResult(cloneData))) {
S
Initial  
superRaytin 已提交
427 428 429 430 431 432 433 434 435 436
                            data = cloneData;
                        }
                    }

                    container.data('pagination').currentPageData = data;

                    // callback
                    self.doCallback(data, callback);

                    // After pageing
羽牧 已提交
437
                    self.callHook('afterPaging', pageNumber);
S
Initial  
superRaytin 已提交
438 439

                    // Already the first page
S
superRaytin 已提交
440
                    if (pageNumber == 1) {
S
Initial  
superRaytin 已提交
441 442 443 444
                        self.callHook('afterIsFirstPage');
                    }

                    // Already the last page
S
superRaytin 已提交
445
                    if (pageNumber == model.totalPage) {
S
Initial  
superRaytin 已提交
446 447 448 449 450 451
                        self.callHook('afterIsLastPage');
                    }

                }
            },

S
superRaytin 已提交
452
            doCallback: function(data, customCallback) {
S
Initial  
superRaytin 已提交
453 454 455 456 457 458 459 460 461 462 463
                var self = this;
                var model = self.model;

                if ($.isFunction(customCallback)) {
                    customCallback(data, model);
                }
                else if ($.isFunction(attributes.callback)) {
                    attributes.callback(data, model);
                }
            },

S
superRaytin 已提交
464
            destroy: function() {
S
Initial  
superRaytin 已提交
465 466

                // Before destroy
S
superRaytin 已提交
467
                if (this.callHook('beforeDestroy') === false) return;
S
Initial  
superRaytin 已提交
468 469 470 471 472 473 474 475 476 477 478

                this.model.el.remove();
                container.off();

                // Remove style element
                $('#paginationjs-style').remove();

                // After destroy
                this.callHook('afterDestroy');
            },

S
superRaytin 已提交
479
            previous: function(callback) {
S
Initial  
superRaytin 已提交
480 481 482
                this.go(this.model.pageNumber - 1, callback);
            },

S
superRaytin 已提交
483
            next: function(callback) {
S
Initial  
superRaytin 已提交
484 485 486
                this.go(this.model.pageNumber + 1, callback);
            },

S
superRaytin 已提交
487
            disable: function() {
S
Initial  
superRaytin 已提交
488 489 490
                var self = this;
                var source = self.sync ? 'sync' : 'async';

S
superRaytin 已提交
491
                // Before disable
S
superRaytin 已提交
492
                if (self.callHook('beforeDisable', source) === false) return;
S
Initial  
superRaytin 已提交
493

S
superRaytin 已提交
494 495
                self.disabled = true;
                self.model.disabled = true;
S
Initial  
superRaytin 已提交
496

S
superRaytin 已提交
497 498
                // After disable
                self.callHook('afterDisable', source);
S
Initial  
superRaytin 已提交
499 500
            },

S
superRaytin 已提交
501
            enable: function() {
S
Initial  
superRaytin 已提交
502 503 504
                var self = this;
                var source = self.sync ? 'sync' : 'async';

S
superRaytin 已提交
505
                // Before enable
S
superRaytin 已提交
506
                if (self.callHook('beforeEnable', source) === false) return;
S
Initial  
superRaytin 已提交
507

S
superRaytin 已提交
508 509
                self.disabled = false;
                self.model.disabled = false;
S
Initial  
superRaytin 已提交
510

S
superRaytin 已提交
511 512 513 514
                // After enable
                self.callHook('afterEnable', source);
            },

S
superRaytin 已提交
515 516 517 518 519
            refresh: function(callback) {
                this.go(this.model.pageNumber, callback);
            },

            show: function() {
520 521
                var self = this;

S
superRaytin 已提交
522
                if (self.model.el.is(':visible')) return;
S
superRaytin 已提交
523

524
                self.model.el.show();
S
superRaytin 已提交
525 526
            },

S
superRaytin 已提交
527
            hide: function() {
528 529
                var self = this;

S
superRaytin 已提交
530
                if (!self.model.el.is(':visible')) return;
S
superRaytin 已提交
531

532
                self.model.el.hide();
S
Initial  
superRaytin 已提交
533 534 535
            },

            // Replace the variables of template
S
superRaytin 已提交
536
            replaceVariables: function(template, variables) {
S
Initial  
superRaytin 已提交
537 538 539

                var formattedString;

S
superRaytin 已提交
540
                for(var key in variables) {
S
Initial  
superRaytin 已提交
541 542 543 544 545 546 547 548 549 550
                    var value = variables[key];
                    var regexp = new RegExp('<%=\\s*'+ key +'\\s*%>', 'img');

                    formattedString = (formattedString || template).replace(regexp, value);
                }

                return formattedString;
            },

            // Get data segments
S
superRaytin 已提交
551
            getDataSegment: function(number) {
S
Initial  
superRaytin 已提交
552 553 554 555 556 557 558 559 560 561 562
                var pageSize = attributes.pageSize;
                var dataSource = attributes.dataSource;
                var totalNumber = attributes.totalNumber;

                var start = pageSize * (number - 1) + 1;
                var end = Math.min(number * pageSize, totalNumber);

                return dataSource.slice(start - 1, end);
            },

            // Get total page
S
superRaytin 已提交
563
            getTotalPage: function() {
S
Initial  
superRaytin 已提交
564 565 566 567
                return Math.ceil(attributes.totalNumber / attributes.pageSize);
            },

            // Get locator
S
superRaytin 已提交
568
            getLocator: function(locator) {
S
Initial  
superRaytin 已提交
569 570
                var result;

S
superRaytin 已提交
571
                if (typeof locator === 'string') {
S
Initial  
superRaytin 已提交
572 573
                    result = locator;
                }
S
superRaytin 已提交
574
                else if ($.isFunction(locator)) {
S
Initial  
superRaytin 已提交
575 576 577 578 579 580 581 582 583 584
                    result = locator();
                }
                else{
                    throwError('"locator" is incorrect. (String | Function)');
                }

                return result;
            },

            // Filter data by "locator"
S
superRaytin 已提交
585
            filterDataByLocator: function(dataSource) {
S
Initial  
superRaytin 已提交
586 587 588 589 590

                var locator = this.getLocator(attributes.locator);
                var filteredData;

                // Data source is an Object, use "locator" to locate the true data
S
superRaytin 已提交
591
                if (Helpers.isObject(dataSource)) {
S
Initial  
superRaytin 已提交
592
                    try{
S
superRaytin 已提交
593
                        $.each(locator.split('.'), function(index, item) {
S
Initial  
superRaytin 已提交
594 595 596
                            filteredData = (filteredData ? filteredData : dataSource)[item];
                        });
                    }
S
superRaytin 已提交
597
                    catch(e) {}
S
Initial  
superRaytin 已提交
598

S
superRaytin 已提交
599
                    if (!filteredData) {
S
Initial  
superRaytin 已提交
600 601
                        throwError('dataSource.'+ locator +' is undefined.');
                    }
S
superRaytin 已提交
602
                    else if (!Helpers.isArray(filteredData)) {
S
Initial  
superRaytin 已提交
603 604 605 606 607 608 609 610
                        throwError('dataSource.'+ locator +' must be an Array.');
                    }
                }

                return filteredData || dataSource;
            },

            // Parse dataSource
S
superRaytin 已提交
611
            parseDataSource: function(dataSource, callback) {
S
Initial  
superRaytin 已提交
612 613 614 615

                var self = this;
                var args = arguments;

S
superRaytin 已提交
616
                if (Helpers.isObject(dataSource)) {
S
Initial  
superRaytin 已提交
617 618
                    callback(attributes.dataSource = self.filterDataByLocator(dataSource));
                }
S
superRaytin 已提交
619
                else if (Helpers.isArray(dataSource)) {
S
Initial  
superRaytin 已提交
620 621
                    callback(attributes.dataSource = dataSource);
                }
S
superRaytin 已提交
622 623 624
                else if ($.isFunction(dataSource)) {
                    attributes.dataSource(function(data) {
                        if ($.isFunction(data)) {
S
Initial  
superRaytin 已提交
625 626 627 628 629 630
                            throwError('Unexpect parameter of the "done" Function.');
                        }

                        args.callee.call(self, data, callback);
                    });
                }
S
superRaytin 已提交
631 632
                else if (typeof dataSource === 'string') {
                    if (/^https?|file:/.test(dataSource)) {
S
Initial  
superRaytin 已提交
633 634 635 636 637 638 639 640 641 642
                        attributes.ajaxDataType = 'jsonp';
                    }

                    callback(dataSource);
                }
                else{
                    throwError('Unexpect data type of the "dataSource".');
                }
            },

S
superRaytin 已提交
643
            callHook: function(hook) {
S
Initial  
superRaytin 已提交
644 645 646 647 648 649
                var paginationData = container.data('pagination');
                var result;

                var args = Array.prototype.slice.apply(arguments);
                args.shift();

S
superRaytin 已提交
650 651
                if (attributes[hook] && $.isFunction(attributes[hook])) {
                    if (attributes[hook].apply(global, args) === false) {
S
Initial  
superRaytin 已提交
652 653 654 655
                        result = false;
                    }
                }

S
superRaytin 已提交
656 657 658
                if (paginationData.hooks && paginationData.hooks[hook]) {
                    $.each(paginationData.hooks[hook], function(index, item) {
                        if (item.apply(global, args) === false) {
S
Initial  
superRaytin 已提交
659 660 661 662 663 664 665 666
                            result = false;
                        }
                    });
                }

                return result !== false;
            },

S
superRaytin 已提交
667
            observer: function() {
S
Initial  
superRaytin 已提交
668 669 670 671 672

                var self = this;
                var el = self.model.el;

                // Go to page
S
superRaytin 已提交
673
                container.on(eventPrefix + 'go', function(event, pageNumber, done) {
S
Initial  
superRaytin 已提交
674 675 676

                    pageNumber = parseInt($.trim(pageNumber));

S
superRaytin 已提交
677
                    if (!pageNumber) return;
S
Initial  
superRaytin 已提交
678

S
superRaytin 已提交
679
                    if (!$.isNumeric(pageNumber)) {
S
Initial  
superRaytin 已提交
680 681 682 683 684 685 686
                        throwError('"pageNumber" is incorrect. (Number)');
                    }

                    self.go(pageNumber, done);
                });

                // Page click
S
superRaytin 已提交
687
                el.delegate('.J-paginationjs-page', 'click', function(event) {
S
Initial  
superRaytin 已提交
688 689 690
                    var current = $(event.currentTarget);
                    var pageNumber = $.trim(current.attr('data-num'));

S
superRaytin 已提交
691
                    if (!pageNumber || current.hasClass(attributes.disableClassName) || current.hasClass(attributes.activeClassName)) return;
S
Initial  
superRaytin 已提交
692 693

                    // Before page button clicked
S
superRaytin 已提交
694
                    if (self.callHook('beforePageOnClick', event, pageNumber) === false) return false;
S
Initial  
superRaytin 已提交
695 696 697 698

                    self.go(pageNumber);

                    // After page button clicked
羽牧 已提交
699
                    self.callHook('afterPageOnClick', event, pageNumber);
S
Initial  
superRaytin 已提交
700

S
superRaytin 已提交
701
                    if (!attributes.pageLink) return false;
S
Initial  
superRaytin 已提交
702 703 704
                });

                // Previous click
S
superRaytin 已提交
705
                el.delegate('.J-paginationjs-previous', 'click', function(event) {
S
Initial  
superRaytin 已提交
706 707 708
                    var current = $(event.currentTarget);
                    var pageNumber = $.trim(current.attr('data-num'));

S
superRaytin 已提交
709
                    if (!pageNumber || current.hasClass(attributes.disableClassName)) return;
S
Initial  
superRaytin 已提交
710 711

                    // Before previous clicked
S
superRaytin 已提交
712
                    if (self.callHook('beforePreviousOnClick', event, pageNumber) === false) return false;
S
Initial  
superRaytin 已提交
713 714 715 716

                    self.go(pageNumber);

                    // After previous clicked
羽牧 已提交
717
                    self.callHook('afterPreviousOnClick', event, pageNumber);
S
Initial  
superRaytin 已提交
718

S
superRaytin 已提交
719
                    if (!attributes.pageLink) return false;
S
Initial  
superRaytin 已提交
720 721 722
                });

                // Next click
S
superRaytin 已提交
723
                el.delegate('.J-paginationjs-next', 'click', function(event) {
S
Initial  
superRaytin 已提交
724 725 726
                    var current = $(event.currentTarget);
                    var pageNumber = $.trim(current.attr('data-num'));

S
superRaytin 已提交
727
                    if (!pageNumber || current.hasClass(attributes.disableClassName)) return;
S
Initial  
superRaytin 已提交
728 729

                    // Before next clicked
S
superRaytin 已提交
730
                    if (self.callHook('beforeNextOnClick', event, pageNumber) === false) return false;
S
Initial  
superRaytin 已提交
731 732 733 734

                    self.go(pageNumber);

                    // After next clicked
羽牧 已提交
735
                    self.callHook('afterNextOnClick', event, pageNumber);
S
Initial  
superRaytin 已提交
736

S
superRaytin 已提交
737
                    if (!attributes.pageLink) return false;
S
Initial  
superRaytin 已提交
738 739 740
                });

                // Go button click
S
superRaytin 已提交
741
                el.delegate('.J-paginationjs-go-button', 'click', function() {
S
Initial  
superRaytin 已提交
742 743 744
                    var pageNumber = $('.J-paginationjs-go-pagenumber', el).val();

                    // Before Go button clicked
S
superRaytin 已提交
745
                    if (self.callHook('beforeGoButtonOnClick', event, pageNumber) === false) return false;
S
Initial  
superRaytin 已提交
746 747 748 749 750 751 752 753

                    container.trigger(eventPrefix + 'go', pageNumber);

                    // After Go button clicked
                    self.callHook('afterGoButtonOnClick', event, pageNumber);
                });

                // go input enter
S
superRaytin 已提交
754 755
                el.delegate('.J-paginationjs-go-pagenumber', 'keyup', function(event) {
                    if (event.which === 13) {
S
Initial  
superRaytin 已提交
756 757 758
                        var pageNumber = $(event.currentTarget).val();

                        // Before Go input enter
S
superRaytin 已提交
759
                        if (self.callHook('beforeGoInputOnEnter', event, pageNumber) === false) return false;
S
Initial  
superRaytin 已提交
760 761 762 763 764 765 766 767 768 769 770 771

                        container.trigger(eventPrefix + 'go', pageNumber);

                        // Regains focus
                        $('.J-paginationjs-go-pagenumber', el).focus();

                        // After Go input enter
                        self.callHook('afterGoInputOnEnter', event, pageNumber);
                    }
                });

                // Previous page
S
superRaytin 已提交
772
                container.on(eventPrefix + 'previous', function(event, done) {
S
Initial  
superRaytin 已提交
773 774 775 776
                    self.previous(done);
                });

                // Next page
S
superRaytin 已提交
777
                container.on(eventPrefix + 'next', function(event, done) {
S
Initial  
superRaytin 已提交
778 779 780
                    self.next(done);
                });

S
superRaytin 已提交
781
                // Disable
S
superRaytin 已提交
782
                container.on(eventPrefix + 'disable', function() {
S
superRaytin 已提交
783 784 785 786
                    self.disable();
                });

                // Enable
S
superRaytin 已提交
787
                container.on(eventPrefix + 'enable', function() {
S
superRaytin 已提交
788
                    self.enable();
S
Initial  
superRaytin 已提交
789 790
                });

S
superRaytin 已提交
791 792 793 794 795
                // Refresh
                container.on(eventPrefix + 'refresh', function(event, done) {
                    self.refresh(done);
                });

S
superRaytin 已提交
796
                // Show
S
superRaytin 已提交
797
                container.on(eventPrefix + 'show', function() {
S
superRaytin 已提交
798 799 800 801
                    self.show();
                });

                // Hide
S
superRaytin 已提交
802
                container.on(eventPrefix + 'hide', function() {
S
superRaytin 已提交
803
                    self.hide();
S
Initial  
superRaytin 已提交
804 805 806
                });

                // Destroy
S
superRaytin 已提交
807
                container.on(eventPrefix + 'destroy', function() {
S
Initial  
superRaytin 已提交
808 809 810
                    self.destroy();
                });

L
leon.shi 已提交
811
                // Whether to load the default page
S
superRaytin 已提交
812
                if (attributes.triggerPagingOnInit) {
S
Initial  
superRaytin 已提交
813 814 815 816 817 818 819
                    container.trigger(eventPrefix + 'go', Math.min(attributes.pageNumber, self.model.totalPage));
                }
            }
        };


        // If initial
S
superRaytin 已提交
820
        if (container.data('pagination') && container.data('pagination').initialized === true) {
S
Initial  
superRaytin 已提交
821 822

            // Handling events
S
superRaytin 已提交
823
            if ($.isNumeric(options)) {
S
Initial  
superRaytin 已提交
824 825 826 827
                // container.pagination(5)
                container.trigger.call(this, eventPrefix + 'go', options, arguments[1]);
                return this;
            }
S
superRaytin 已提交
828
            else if (typeof options === 'string') {
S
Initial  
superRaytin 已提交
829 830 831 832

                var args = Array.prototype.slice.apply(arguments);
                args[0] = eventPrefix + args[0];

S
superRaytin 已提交
833
                switch(options) {
S
Initial  
superRaytin 已提交
834 835 836
                    case 'previous':
                    case 'next':
                    case 'go':
S
superRaytin 已提交
837 838
                    case 'disable':
                    case 'enable':
S
superRaytin 已提交
839
                    case 'refresh':
S
superRaytin 已提交
840 841
                    case 'show':
                    case 'hide':
S
Initial  
superRaytin 已提交
842 843 844 845 846 847
                    case 'destroy':
                        container.trigger.apply(this, args);
                        break;

                    // Get selected page number
                    case 'getSelectedPageNum':
S
superRaytin 已提交
848
                        if (container.data('pagination').model) {
S
Initial  
superRaytin 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862
                            return container.data('pagination').model.pageNumber;
                        }
                        else{
                            return container.data('pagination').attributes.pageNumber;
                        }

                    // Get total page
                    case 'getTotalPage':
                        return container.data('pagination').model.totalPage;

                    // Get selected page data
                    case 'getSelectedPageData':
                        return container.data('pagination').currentPageData;

S
superRaytin 已提交
863 864 865
                    // Whether pagination was be disabled
                    case 'isDisabled':
                        return container.data('pagination').model.disabled === true;
S
Initial  
superRaytin 已提交
866 867 868 869 870 871

                    default:
                        throwError('Pagination do not provide action: ' + options);
                }

                return this;
872 873 874
            } else {
                // Uninstall the old instance before initialize a new one
                uninstallPlugin(container);
S
Initial  
superRaytin 已提交
875 876 877
            }
        }
        else{
S
superRaytin 已提交
878
            if (!Helpers.isObject(options)) {
L
leon.shi 已提交
879
                throwError('Illegal options');
S
Initial  
superRaytin 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
            }
        }


        // Attributes
        var attributes = $.extend({}, arguments.callee.defaults, options);

        // Check parameters
        parameterChecker(attributes);

        pagination.initialize();

        return this;
    };

    // Instance defaults
    $.fn[pluginName].defaults = {

        // Data source
        // Array | String | Function | Object
        //dataSource: '',

        // String | Function
903
        //locator: 'data',
S
Initial  
superRaytin 已提交
904

羽牧 已提交
905
        // Total entries, must be specified when the pagination is asynchronous
S
Initial  
superRaytin 已提交
906 907 908 909 910
        totalNumber: 1,

        // Default page
        pageNumber: 1,

羽牧 已提交
911
        // entries of per page
S
Initial  
superRaytin 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
        pageSize: 10,

        // Page range (pages on both sides of the current page)
        pageRange: 2,

        // Whether to display the 'Previous' button
        showPrevious: true,

        // Whether to display the 'Next' button
        showNext: true,

        // Whether to display the page buttons
        showPageNumbers: true,

        showNavigator: false,

        // Whether to display the 'Go' input
        showGoInput: false,

        // Whether to display the 'Go' button
        showGoButton: false,

        // Page link
        pageLink: '',

        // 'Previous' text
        prevText: '&laquo;',

        // 'Next' text
        nextText: '&raquo;',

        // Ellipsis text
        ellipsisText: '...',

        // 'Go' button text
        goButtonText: 'Go',

        // Additional className for Pagination element
        //className: '',

        classPrefix: 'paginationjs',

        // Default active class
        activeClassName: 'active',

        // Default disable class
        disableClassName: 'disabled',

        //ulClassName: '',

        // Whether to insert inline style
        inlineStyle: true,

        formatNavigator: '<%= currentPage %> / <%= totalPage %>',

        formatGoInput: '<%= input %>',

        formatGoButton: '<%= button %>',

        // Pagination element's position in the container
        position: 'bottom',

S
superRaytin 已提交
974 975 976 977 978 979
        // Auto hide previous button when current page is the first page
        autoHidePrevious: false,

        // Auto hide next button when current page is the last page
        autoHideNext: false,

S
Initial  
superRaytin 已提交
980 981 982 983
        //header: '',

        //footer: '',

羽牧 已提交
984
        // Aliases for custom pagination parameters
S
Initial  
superRaytin 已提交
985 986
        //alias: {},

羽牧 已提交
987
        // Whether to trigger pagination at initialization
S
Initial  
superRaytin 已提交
988 989
        triggerPagingOnInit: true,

990 991 992
        // Whether to hide pagination when less than one page
        hideWhenLessThanOnePage: false,

S
Initial  
superRaytin 已提交
993 994 995 996 997
        showFirstOnEllipsisShow: true,

        showLastOnEllipsisShow: true,

        // Pagging callback
S
superRaytin 已提交
998
        callback: function() {}
S
Initial  
superRaytin 已提交
999 1000 1001
    };

    // Hook register
S
superRaytin 已提交
1002
    $.fn[pluginHookMethod] = function(hook, callback) {
S
Initial  
superRaytin 已提交
1003

S
superRaytin 已提交
1004
        if (arguments.length < 2) {
S
Initial  
superRaytin 已提交
1005 1006 1007
            throwError('Missing argument.');
        }

S
superRaytin 已提交
1008
        if (!$.isFunction(callback)) {
S
Initial  
superRaytin 已提交
1009 1010 1011 1012 1013 1014
            throwError('callback must be a function.');
        }

        var container = $(this);
        var paginationData = container.data('pagination');

S
superRaytin 已提交
1015
        if (!paginationData) {
S
Initial  
superRaytin 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
            container.data('pagination', {});
            paginationData = container.data('pagination');
        }

        !paginationData.hooks && (paginationData.hooks = {});

        //paginationData.hooks[hook] = callback;
        paginationData.hooks[hook] = paginationData.hooks[hook] || [];
        paginationData.hooks[hook].push(callback);

    };

    // Static method
S
superRaytin 已提交
1029
    $[pluginName] = function(selector, options) {
S
Initial  
superRaytin 已提交
1030

S
superRaytin 已提交
1031
        if (arguments.length < 2) {
S
Initial  
superRaytin 已提交
1032 1033 1034 1035 1036 1037
            throwError('Requires two parameters.');
        }

        var container;

        // 'selector' is a jQuery object
S
superRaytin 已提交
1038
        if (typeof selector !== 'string' && selector instanceof jQuery) {
S
Initial  
superRaytin 已提交
1039 1040 1041 1042 1043 1044
            container = selector;
        }
        else{
            container = $(selector);
        }

S
superRaytin 已提交
1045
        if (!container.length) return;
S
Initial  
superRaytin 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

        container.pagination(options);

        return container;

    };

    // ============================================================
    // helpers
    // ============================================================

1057 1058
    var Helpers = {};

S
Initial  
superRaytin 已提交
1059
    // Throw error
S
superRaytin 已提交
1060
    function throwError(content) {
S
Initial  
superRaytin 已提交
1061 1062 1063 1064
        throw new Error('Pagination: '+ content);
    }

    // Check parameters
S
superRaytin 已提交
1065
    function parameterChecker(args) {
S
Initial  
superRaytin 已提交
1066

S
superRaytin 已提交
1067
        if (!args.dataSource) {
S
Initial  
superRaytin 已提交
1068 1069 1070
            throwError('"dataSource" is required.');
        }

S
superRaytin 已提交
1071 1072
        if (typeof args.dataSource === 'string') {
            if (typeof args.totalNumber === 'undefined') {
S
Initial  
superRaytin 已提交
1073 1074
                throwError('"totalNumber" is required.');
            }
S
superRaytin 已提交
1075
            else if (!$.isNumeric(args.totalNumber)) {
S
Initial  
superRaytin 已提交
1076 1077 1078
                throwError('"totalNumber" is incorrect. (Number)');
            }
        }
S
superRaytin 已提交
1079 1080
        else if (Helpers.isObject(args.dataSource)) {
            if (typeof args.locator === 'undefined') {
1081
                throwError('"dataSource" is an Object, please specify "locator".');
S
Initial  
superRaytin 已提交
1082
            }
S
superRaytin 已提交
1083
            else if (typeof args.locator !== 'string' && !$.isFunction(args.locator)) {
S
Initial  
superRaytin 已提交
1084 1085 1086 1087 1088
                throwError(''+ args.locator +' is incorrect. (String | Function)');
            }
        }
    }

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    // uninstall plugin
    function uninstallPlugin(target) {
        var events = ['go', 'previous', 'next', 'disable', 'enable', 'refresh', 'show', 'hide', 'destroy'];

        // off events of old instance
        $.each(events, function(index, value) {
            target.off(eventPrefix + value);
        });

        // reset pagination data
        target.data('pagination', {});

        // remove old
        $('.paginationjs', target).remove();
    }

S
Initial  
superRaytin 已提交
1105
    // Object type detection
1106
    function getObjectType(object, tmp) {
1107 1108
        return ( (tmp = typeof(object)) == "object" ? object == null && "null" || Object.prototype.toString.call(object).slice(8, -1) : tmp ).toLowerCase();
    }
S
superRaytin 已提交
1109 1110
    $.each(['Object', 'Array'], function(index, name) {
        Helpers['is' + name] = function(object) {
1111
            return getObjectType(object) === name.toLowerCase();
S
Initial  
superRaytin 已提交
1112 1113 1114 1115 1116 1117
        };
    });

    /*
     * export via AMD or CommonJS
     * */
S
superRaytin 已提交
1118 1119
    if (typeof define === 'function' && define.amd) {
        define(function() {
S
Initial  
superRaytin 已提交
1120 1121 1122 1123 1124
            return $;
        });
    }

})(this, window.jQuery);