[jQuery] 閉包的運用 -以cookie存取為例

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>


<script type="text/javascript">
//2015/08/05 jwu註釋及視例

//This is not production quality, its just demo code.
var cookieList = function(cookieName) {
//When the cookie is saved the items will be a comma seperated string
//So we will split the cookie by comma to get the original array
var cookie = $.cookie(cookieName);
//Load the items or a new array if null.
var items = cookie ? cookie.split(/,/) : new Array();
//Return a object that we can use to access the array.
//while hiding direct access to the declared items array
return {
"add": function(val) {
//Add to the items.
items.push(val);
//Save the items to a cookie.
//EDIT: Modified from linked answer by Nick
$.cookie(cookieName, items.join(','));
},
"remove": function (val) {
//EDIT: Thx to Assef and luke for remove.
indx = items.indexOf(val);
if(indx!=-1) items.splice(indx, 1);
$.cookie(cookieName, items.join(','));},
"clear": function() {
items = null;
//clear the cookie.
$.cookie(cookieName, null);
},
"items": function() {
//Get all the items.
return items;
}
}
}

var list = new cookieList("MyItems"); // all items in the array.

list.add("foo");//增加一字串
alert(list.items());//顯示一次看有甚麼

list.add("foo2");//增加一字串
list.add("foo3");//增加一字串
list.remove("foo3");//移除一字串
alert(list.items());//顯示一次看有甚麼

list.clear();//清空
alert(list.items());//顯示一次看有甚麼


</script>


 

 

DEMO

 

 

arrow
arrow
    全站熱搜

    kinomelma 發表在 痞客邦 留言(0) 人氣()