Last active
September 25, 2015 09:17
-
-
Save rwaldron/898710 to your computer and use it in GitHub Desktop.
Dogfood Pattern
This file contains hidden or 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> | |
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script> | |
<script src="http://code.jquery.com/jquery-latest.js"></script> | |
<script src="dogfood-init.js"></script> | |
</head> | |
<ul id="ui-menu-stuff"> | |
</ul> | |
</html> |
This file contains hidden or 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
(function (global) { | |
var Dogfood = (function () { | |
var cHandlers = {}; | |
return { | |
init: function (selector, handlers) { | |
var actions = _.keys(handlers), | |
domFrags = { | |
li: $("<li>"), | |
a: $("<a>") | |
}, | |
$stack = $(false); | |
_.each(actions, function (action) { | |
// Create new elements from cached frags | |
var $li = domFrags.li.clone(), | |
$a = domFrags.a.clone(); | |
// Set up the anchor | |
$a.attr({ | |
"href": "/" + action | |
}).html(action); | |
// Attach data to the li | |
$li.data("action", action); | |
// Push the new frags into the collection | |
$stack.push($li.append($a)[0]); | |
cHandlers[action] = handlers[action]; | |
}, this); | |
// Bind click handlers | |
$stack.bind("click", | |
this.event.click | |
).appendTo(selector); | |
}, | |
event: { | |
click: function (event, special) { | |
// Whoa. | |
event.preventDefault(); | |
var action = $(this).data("action"); | |
cHandlers[action](action, event.data || special || {}); | |
} | |
} | |
}; | |
})(); | |
global.Dogfood = Dogfood; | |
})(this); | |
$(function () { | |
function dummy(action, data) { | |
console.log(action, data); | |
} | |
Dogfood.init("#ui-menu-stuff", { | |
"add-new": dummy, | |
"reply": dummy, | |
"reply-all": dummy, | |
"forward": dummy, | |
"more-action": dummy | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment