Skip to content

Instantly share code, notes, and snippets.

@Skyentific
Created February 5, 2018 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Skyentific/f1ac8583891ef99fd194b9b0b7aed260 to your computer and use it in GitHub Desktop.
Save Skyentific/f1ac8583891ef99fd194b9b0b7aed260 to your computer and use it in GitHub Desktop.
Javascript method chain example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="members-wrapper"></div>
<script>
// Javascript chain example from
// http://javascriptissexy.com/beautiful-javascript-easily-create-chainable-cascading-methods-for-expressiveness/
// The data
var usersData =[
{firstName: "tommy", lastName: "MalCom", email: "test@test.com", id:102},
{firstName: "Peter", lastName: "breCht", email: "test2@test2.com", id: 103},
{firstName: "RoHan", lastName: "sahu", email: "test3@test3.com", id: 104}
];
// A quick utility function that does what it says:
function titleCaseName(str)
{
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
// Our object with the chainable methods
var userController = {
currentUser: "",
findUser: function (userEmail) {
var arrayLength = usersData.length, i;
for (i = arrayLength - 1; i >= 0; i--) {
if (usersData[i].email === userEmail) {
this.currentUser = usersData[i];
break;
}
}
return this;
},
formatName: function () {
if (this.currentUser) {
console.log(this.currentUser);
this.currentUser.fullName =
titleCaseName(this.currentUser.firstName + " " +
titleCaseName(this.currentUser.lastName));
}
return this;
},
createLayout: function () {
if (this.currentUser) {
console.log(this.currentUser.fullName);
this.currentUser.viewData =
"<h2>Member: " + this.currentUser.fullName + "</h2>"
+ "<p>ID: " + this.currentUser.id + "</p>"
+ "<p>Email: " + this.currentUser.email + "</p>";
}
return this;
},
displayUser: function() {
if (!this.currentUser) return;
$(".members-wrapper").append(this.currentUser.viewData);
}
};
userController.findUser("test2@test2.com").formatName().createLayout().displayUser();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment