OOP Patterns: Functional Object
This uses a functional pattern that capitalizes on Javascript's prototypal inheritance, everything's an object, non-classical programming features.
HTML
<ul id="unordered-list">
<li id="one">I'm number … </li>
<li id="two">I'm number … </li>
<li id="three">Who's my mommy?</li>
<li id="four">I do nothing :(</li>
</ul>
CSS
p {
text-align: center;
margin: 20px 0 0;
}
ul {
margin: 25px 0;
}
li {
text-align: center;
margin: 10px auto;
padding: 5px;
width: 200px;
background: #ddd;
outline: 1px solid #999;
border: 1px solid #eee;
border-right-color: #bbb;
border-bottom-color: #bbb;
}
li:hover {
border-left-color: #bbb;
border-top-color: #bbb;
cursor: pointer;
}
JavaScript
// Create an "array" so that we can cherry pick out elements
var listArray = document.getElementsByTagName('li');
/*************************************\
**** Functional Object Pattern ****
\*************************************/
var listId = function (item) {
item = item || {};
var that = {};
that.element = item;
that.elementId = item.getAttribute('id');
that.getId = function () {
$(that.element).click(function () {
alert(that.elementId);
});
};
that.getId2 = function () {
$(that.element).release(function () {
alert(hi);
});
};
return that;
}; // End of Functional Object Pattern
// Create a child object that inherits
// from the parent.
// The *new* method is not needed
var retreiveOne = listId(listArray[0]),
retreiveTwo = listId(listArray[1]);
retreiveOne.getId(); // logs "one"
retreiveTwo.getId(); // logs "two"
retreiveTwo.getId2(); // logs "two"
// "Extend" the original object
var whatId = function (item) {
var that = listId(item);
that.elementId = item.parentNode.getAttribute('id');
return that;
};
// Create a grandchild object that inherits
// from the parent and the grandparent.
// Again, the *new* method is not needed
var retreiveThree = whatId(listArray[2]);
retreiveThree.getId2(); // logs "unordered-list" upon click
alert(retreiveThree.elementId);