-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJqueryClone.js
112 lines (99 loc) · 2.35 KB
/
JqueryClone.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
class ElementCollection extends Array {
ready(callback) {
const isReady = this.some(e => {
return e.readyState != null && e.readyState != "loading"
})
if (isReady) {
callback()
} else {
this.on("DOMContentLoaded", callback)
}
return this
}
on(event, callbackOrSelector, callback) {
if (typeof callbackOrSelector === "function") {
this.forEach(e => e.addEventListener(event, callbackOrSelector))
} else {
this.forEach(elem => {
elem.addEventListener(event, e => {
if (e.target.matches(callbackOrSelector)) callback(e)
})
})
}
return this
}
next() {
return this.map(e => e.nextElementSibling).filter(e => e != null)
}
prev() {
return this.map(e => e.previousElementSibling).filter(e => e != null)
}
removeClass(className) {
this.forEach(e => e.classList.remove(className))
return this
}
addClass(className) {
this.forEach(e => e.classList.add(className))
return this
}
css(property, value) {
const camelProp = property.replace(/(-[a-z])/, g => {
return g.replace("-", "").toUpperCase()
})
this.forEach(e => (e.style[camelProp] = value))
return this
}
}
class AjaxPromise {
constructor(promise) {
this.promise = promise
}
done(callback) {
this.promise = this.promise.then(data => {
callback(data)
return data
})
return this
}
fail(callback) {
this.promise = this.promise.catch(callback)
return this
}
always(callback) {
this.promise = this.promise.finally(callback)
return this
}
}
function $(param) {
if (typeof param === "string" || param instanceof String) {
return new ElementCollection(...document.querySelectorAll(param))
} else {
return new ElementCollection(param)
}
}
$.get = function ({ url, data = {}, success = () => {}, dataType }) {
const queryString = Object.entries(data)
.map(([key, value]) => {
return `${key}=${value}`
})
.join("&")
return new AjaxPromise(
fetch(`${url}?${queryString}`, {
method: "GET",
headers: {
"Content-Type": dataType,
},
})
.then(res => {
if (res.ok) {
return res.json()
} else {
throw new Error(res.status)
}
})
.then(data => {
success(data)
return data
})
)
}