Last active
January 3, 2016 20:09
-
-
Save ianscrivener/8513317 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="description" content="js method chaining" /> | |
<script src="http://code.jquery.com/jquery-latest.js"></script> | |
<meta charset=utf-8 /> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div class="members-wrapper"></div> | |
<div class="logger"></div> | |
<script> | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The data store: | |
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} | |
]; | |
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; | |
} | |
} | |
//console.log(this); | |
return this; | |
}, | |
formatName:function () { | |
if (this.currentUser) { | |
this.currentUser.fullName = titleCaseName (this.currentUser.firstName + " " + this.currentUser.lastName); | |
} | |
return this; | |
}, | |
createLayout:function () { | |
if (this.currentUser) { | |
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); | |
} | |
}; | |
// Now, use the chaninable methods with expressiveness: | |
userController.findUser("test3@test3.com").formatName().createLayout().displayUser(); | |
/* | |
same as | |
userController.findUser("test3@test3.com") | |
.formatName() | |
.createLayout() | |
.displayUser() | |
same as | |
userController.findUser("test3@test3.com"); | |
userController.formatName(); | |
userController.createLayout(); | |
userController.displayUser(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment