-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjquery.loadMore.js
More file actions
86 lines (63 loc) · 2.12 KB
/
jquery.loadMore.js
File metadata and controls
86 lines (63 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
(function ($) {
function accessToJson (json, accessor) {
var properties = accessor.split(/\./g);
var res = json;
$.each(properties, function (index, property) {
if (!property) {
return;
}
res = res[property];
});
return res;
}
function ItemTemplate (opts) {
this.$base = opts.$base;
this.selectors = opts.selectors || {};
this.copyEvents = (opts.copyEvents === false) ? false : true;
}
ItemTemplate.prototype.renderItem = function (item) {
var selectors = this.selectors;
var $el = this.$base.clone(this.copyEvents);
$.each(selectors, function (selector, value) {
var $field = $el.find(selector);
var methods = (typeof value == 'string') ? {
innerHTML: value
} : value;
$.each(methods, function (attr, accessor) {
var value = (typeof accessor == 'function')
? accessor(item)
: accessToJson(item, accessor);
if (attr == 'innerHTML') {
$field.html(value);
} else {
$field.attr(attr, value);
}
});
});
return $el.get(0);
};
$.fn.loadMore = function (opts) {
// init opts
var path = opts.path;
var jsonAccessor = opts.jsonAccessor || '.';
if (!path) {
throw Error('Path to resource is not found.');
}
// init elements
var $root = $(this.parent().get(0));
var $base = $(this.get(0));
// init template
var itemTemplate = new ItemTemplate({
$base: $base,
selectors: opts.selectors,
copyEvents: opts.copyEvents
});
// request
$.getJSON(opts.path, function (res) {
var items = accessToJson(res, jsonAccessor);
$.each(items, function (index, item) {
$root.append(itemTemplate.renderItem(item));
});
});
};
})(jQuery);