Underscore.js once practice
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<p>_.once Practice</p>
<div id="wrapper">
<a href="#" class="trigger">trigger</a>
<a href="#" class="trigger2">trigger2 will only fire once</a>
</div>
CSS
p, div {
margin: 20px 20px 0px;
clear:both;
}
div.trigger2{
color:red;
}
JavaScript
var num = 0;
$(function () {
function appendit (cl) {
num++;
var div = document.createElement("div");
var txt = document.createTextNode("append-"+num);
div.appendChild(txt);
div.setAttribute("class", cl);
var wrapper = document.getElementById("wrapper");
wrapper.appendChild(div);
}
var appendit_once = _.once(appendit);
$(".trigger").click(function(){
var cl = $(this).attr("class");
appendit(cl);
});
$(".trigger2").click(function(){
var cl = $(this).attr("class");
appendit_once(cl);
});
});