-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitem_60.js
More file actions
84 lines (72 loc) · 2.82 KB
/
item_60.js
File metadata and controls
84 lines (72 loc) · 2.82 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
77
78
79
80
81
82
83
84
// Support Method Chaining
/* Stateless APIs offer flexibility to build compound operations out of
* smaller ones. Example: the 'replace' method of strings
*/
function escapeBasicHTML(str1) {
var str2 = str1.replace(/&/g, "&");
var str3 = str2.replace(/</g, "<");
var str4 = str3.replace(/>/g, ">");
var str5 = str4.replace(/"/g, """);
var str6 = str5.replace(/'/g, "'");
return str6;
}
function escapeBasicHTML(str) {
return str.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
}
/* this style of repeated method calls is known as 'method chaining'
* the second version of 'escapeBasicHTML' is much more concise than saving
* each intermediate result to an intermediate variable
* Eliminating the temporary variables makes it clearer to the readers of the
* code that the intermediate results are only important as a step along the
* way to the final result
*/
// another example
var users = records.map(function(record) {
return record.username;
})
.filter(function(username) {
return !!username;
})
.map(function(username) {
return username.toLowerCase();
});
/* takes an array of user records
* - extracts the username property of each
* record
* - filters out any empty usernames
* - converts the usernames to lower-case strings
*/
/* in a stateful setting, design your methods that update an object to return
* 'this' instead of 'undefined' making it possible to perform multiple updates
* on the same object via a sequence of chanined method calls
*/
element.setBackgroundColor("yellow")
.setColor("red")
.setFontWeight("bold");
/* method chaining for stateful API is sometimes know as the 'fluent style'
*/
/* when combining stateless methods that retrieve objects with update methods,
* method chaining can make for very concise and readable code. jQuery
* popularized this approach with a set of (stateless) methods for "querying"
* a web page for UI elements and a set of (stateful) methods for updating
* those elements
*/
$("#notification") // find notification element
.html("Server not responding") // set notification msg
.removeClass("info") // remove one set of styling
.addClass("error"); // add more styling
/* the following stateful calls
* - html
* - removeClass
* - addClass
* support the fluent style by returning the same object
*/
// for users uncomfortable with stylish code
var element = $("#notification");
element.html("Server not responding");
element.removeClass("info");
element.addClass("error");