locallist.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @fileOverview
  3. *
  4. * 提供存储在 LocalStorage 中的列表
  5. *
  6. * @author: techird
  7. * @copyright: Baidu FEX, 2014
  8. */
  9. KityMinder.registerUI('widget/locallist', function() {
  10. function LocalList(name, maxCount) {
  11. var list;
  12. maxCount = maxCount || 10;
  13. function load() {
  14. list = localStorage.getItem(name);
  15. if (list) {
  16. list = JSON.parse(list);
  17. } else {
  18. list = [];
  19. }
  20. this.length = list.length;
  21. }
  22. function save() {
  23. while (list.length > maxCount) list.pop();
  24. localStorage.setItem(name, JSON.stringify(list));
  25. this.length = list.length;
  26. }
  27. function get(index) {
  28. return list[index];
  29. }
  30. function remove(index) {
  31. list.splice(index, 1);
  32. save();
  33. }
  34. function clear() {
  35. list = [];
  36. save();
  37. }
  38. function unshift(item) {
  39. list.unshift(item);
  40. save();
  41. }
  42. function createKeyMatcher(key) {
  43. return function(item, value) {
  44. return item[key] == value;
  45. };
  46. }
  47. function findIndex(matcher, value) {
  48. if (typeof(matcher) == 'string') {
  49. matcher = createKeyMatcher(matcher);
  50. }
  51. for (var i = 0; i < list.length; i++) {
  52. if (matcher(list[i], value)) return i;
  53. }
  54. return -1;
  55. }
  56. function find(matcher, value) {
  57. return get(findIndex(matcher, value));
  58. }
  59. function forEach(callback) {
  60. list.forEach(callback);
  61. save();
  62. }
  63. load.call(this);
  64. this.get = get;
  65. this.remove = remove;
  66. this.findIndex = findIndex;
  67. this.find = find;
  68. this.forEach = forEach;
  69. this.unshift = unshift;
  70. this.clear = clear;
  71. }
  72. return {
  73. use: function(name) {
  74. return new LocalList(name);
  75. }
  76. };
  77. });