简书链接:每日分享分享一个本人以前纯手写的小程序json本地工具类实现收藏、观看历史功能
文章字数:967,阅读全文大约需要3分钟

功能

可实现自动更新最新的在最上面
支持增加,查询。
支持多表构建,比如同时需要收藏,和观看历史
复制到你的工程里面去。比如改名为maputil.js

用法

1
2
3
4
5
6
7
8
9
10
11
12
const mMaputil = require("../../utils/maputil.js");
mEngine = mMaputil.HistoryEngine();//每次创建/ 在城阳
mEngine.edit(function () {


}, function () {
//应该是没有进行初始化
console.debug("edit模式进入失败");
}, function () {
util.hideLoading();
});
var currentItems = mEngine.query();

更多用法我最下面有一个历史记录的js源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/**
* /持久化工具类 排序 永久 保存 取出
/**
* 返回array 查询失败返回[]
*/


/**
判断是否定义 是否有传递参数
@data 需要进行判断的变量 或者方法
**/
function isUndefined(data) {
return data == false || (typeof data) == "undefined";
}
/**
* @param jsonKey 唯一key
*/
function MapUtil(pKey, jsonKey, pTag) {
var jsonKey=jsonKey;
var tag = "[default_Map]";

var map = {};//如果初始化是数组第一次读取是失败的的,那么第一次存入map[xx]显然会出问题,估计之后的不能存放 数字类型自动变成数组然后 如i数字为为 10 1 -9如果没有数据自动填充为null估计都是因为这个初始值导致的的。
var error = "请先对数据进行初始化操作,如先查询(架构设计问题,当时为了快速添加多个模型而做了缓存处理,所以需要调用edit()进行初始化)";
var init = false;

function edit(succ, fail, complete) {

return queryFromStorage(succ, fail, complete);
}

//此操作成功后回个map对象赋值
// queryFromStorage(succ, fail, complete);//初始化查询

if ((typeof jsonKey) == "undefined") {
console.warn(tag + "key没有传递");
jsonKey = "video";//or id
}
function toString() {
// var array = queryData();
// console.debug("history", array);
}


/**
* 不对外暴露 同步请求2017年9月22日 10:11:53 改良
*/
function queryFromStorage(succ, fail, complete) {
try {
map= wx.getStorageSync(pKey);
console.debug(tag + "数据存储查询成功", map, "查询的键" + pKey);
if (isUndefined(map)) {
map = {};
}
if (!isUndefined(succ)) {
console.debug(tag + "数据存储查询成功,进行回调通知", map);
succ(map);
}
}catch(e){
console.warn(e, tag + "无法读取Key:" + pKey+",",e);
if (!isUndefined(fail)) {
fail(e);
}
}
init = true;
if (!isUndefined(complete)) {
complete();
}
return map;
}
/**
* 不对外暴露 同步存储
*/
function saveDataToStorage(map, succ, fail, complete) {
if (!init) {
console.warn(tag+" 没有使用edit()方法进行初始化,saveDataToStorage fail");
if (!isUndefined(fail)) {
var res = { errMsg: "请先调用本对象的edit(succCall,failCall,completeCall);" };
fail(res);
}
if (!isUndefined(complete)) {
complete();
}

return;
}
try{

wx.setStorageSync(pKey,map);
console.debug(tag + "存储数据到持久化成功", "table", pKey, map);
if (!isUndefined(succ)) {
succ();
}
}catch(e){


console.warn(tag + "无法存储数据", e, "需要存储的数据为为:", map);
if (!isUndefined(fail)) {
fail(e);
}

}
if(!isUndefined(complete)){
complete();
}
return map;
}


function putData(model) {
var id = model[jsonKey];

if (isUndefined(id)) {
console.debug(tag, model, "传递的json对象没有包含键名: " + jsonKey);
} else {
var data = map[id];
if (isUndefined(data)) {
console.debug(tag + "new insert Data : model[", model, "]id is ", id);
} else {
console.debug(tag + "replace Data : model[", data, "]->To->", map[id], "id is" + id);
}

}
map[id] = model;
return true;
}
function dataExist(model) {
var id = model[jsonKey];

var result = !isUndefined(map[id]);
console.debug(tag + "model." + jsonKey + "=", id, "dataExist:" + result + "," + map[id]);
return result;
}
/**
* 成功返回模型 失败返回null
*/
function queryByKey(key) {
if (isUndefined(key)) {
console.error(tag + "queryByKey(key) key is undefined");
return;
}
// var id = model[jsonKey];//也可以理解为为 址model.jsonkey 这里唯一字段为视频id 然后再从从 map缓存中取
var temp = map[key];
console.debug(tag + "queryByKey->查询key==Undefined->" + isUndefined(key) + ",key=" + isUndefined(key) == false ? key : " error", "查询结果:", temp);
return temp;
}
/**
* @fail 失败的回调 不会保存
*/
function deleteData(model, fail) {
//检查当前模型是否有此key, 需要这个key来获取
var id = model[jsonKey];//从模型中取出键名ID
if (isUndefined(id)) {
if (!isUndefined(fail)) {
var err = { errMsg: "deleteData fail: not container key " + jsonKey + "" };
fail(err);
}
console.error(tag + "deleteData fail: not container key " + jsonKey + "", model[jsonKey], id);

return false;
}
//通过模型的id值 检查整个map中是否有此模型
if (isUndefined(map[id])) {
if (!isUndefined(fail)) {
var err = { errMsg: "deleteData fail: not exist:[" + jsonKey + "]", };
fail(err);
}
console.warn(tag + "deleteData fail: not exist:[" + jsonKey + "]");
return false;
}
// map[id] = null;
var result = delete map[id];
console.debug(tag + "删除结果" + result);
return result;


}
/**
* 不对外暴露
*/
function queryToArray() {
var map = queryFromStorage();
console.debug("queryToArray",map);
var array = [];
for (var key in map) {
array.push(map[key]);
console.debug(tag + "mapToArray: ", map[key]);

}
return array;
}
/**
* 返回出 时间排序的json对象 在执行完毕后才能进行操作 非耗时操作,但是本功能必须在在 初始化对象完成后调用
*/
function queryData() {
return queryToArray();
}
function submit(succ, fail, complete) {
saveDataToStorage(map, succ, fail, complete);
}

function isInit() {
return init;
}
function setTag(pTag) {
tag = "[" + pTag + "]";
}
function getTag() {
return tag;
}

// this.saveDataToStorage = saveDataToStorage;
this.submit = submit; //添加修改后都需要保存才行
this.putData = putData;
this.deleteData = deleteData;
this.dataExist = dataExist;
this.queryData = queryData;
this.edit = edit;
this.isInit = isInit;
this.queryByKey = queryByKey;
this.setTag = setTag;
this.getTag = getTag;
if (!isUndefined(pTag)) {
setTag(pTag);
}
console.debug(getTag() + "创建了一个map对象", this);
return this;

}
/**
* 虽然比较奇葩的写法,但是没有办法 比较这耗时操作啊啊,查询会导致按钮。
*/
function LikeEngine() {
console.debug("创建了一个LikeEngine对象");
var maputil = new MapUtil("collect_table", field, "喜欢表");

function removeMulti(array, succ, fail, complete) {
removeMultiData(maputil, array, succ, fail, complete);
}
function add(model, succ, fail, complete) {
addData(maputil, model, succ, fail, complete);
}

function remove(model, succ, fail, complete) {
removeData(maputil, model, succ, fail, complete);
}
function update(model, succ, fail, complete) {
updateData(maputil, model, succ, fail, complete);

}
function query(succ, fail, complete) {
return maputil.queryData(succ, fail, complete);
}
function queryByKey(keyValue) {
return maputil.queryByKey(keyValue);
}

//enter edit mode
function edit(succ, fail, complete) {
return maputil.edit(succ, fail, complete);
}

function isLike(model) {

return maputil.dataExist(model);
}
function isInit() {
return maputil.isInit();
}

this.edit = edit;
this.isLike = isLike;
this.query = query;
this.add = add;
this.remove = remove;
this.removeMulti = removeMulti;
this.isInit = isInit;
this.queryByKey = queryByKey;
return this;
}
function HistoryEngine(uniqueKey) {
var field = isUndefined(uniqueKey)? "id":uniqueKey;
console.debug("创建了一个HistoryEngine对象");

var maputil = new MapUtil("brower_history_table", field, "历史记录表");
function isInit() {
return maputil.isInit();
}
function removeMulti(array, succ, fail, complete) {
removeMultiData(maputil, array, succ, fail, complete);
}
function add(model, succ, fail, complete) {
addData(maputil, model, succ, fail, complete);
}

function remove(model, succ, fail, complete) {
removeData(maputil, model, succ, fail, complete);
}
function update(model, succ, fail, complete) {
updateData(maputil, model, succ, fail, complete);

}
function query(succ, fail, complete) {
return maputil.queryData(succ, fail, complete);
}

//enter edit mode
function edit(succ, fail, complete) {
return maputil.edit(succ, fail, complete);
}
/**
* 视频地址 当前封装的是视频地址的值
*/
function queryByKey(keyValue) {
return maputil.queryByKey(keyValue);
}


function isInit() {
return maputil.isInit();
}
this.isInit = isInit;
this.edit = edit;
this.query = query;
this.add = add;
this.remove = remove;
this.update = update;
this.removeMulti = removeMulti;
this.queryByKey = queryByKey;
return this;

}
/**
* 下面方法 做了complete操作 马上生效
*/
function removeMultiData(engine, array, succ, fail, complete) {

// var failCount = 0;失败就是不!
for (var index = 0; index < array.length; index++) {
var model = array[index];
var result = engine.deleteData(model);//失败了会回调
}
engine.submit(function () {
if (!isUndefined(succ)) {
succ();
}
}, fail, complete);

}

function removeData(engine, model, succ, fail, complete) {
var result = engine.deleteData(model, fail);
if (result) {
engine.submit(succ, fail, complete);
} else {
if (!isUndefined(complete)) {
complete();
}
}

}

function addData(engine, model, succ, fail, complete) {
var result = engine.putData(model);
if (result) {
engine.submit(succ, fail, complete);
} else {
if (!isUndefined(fail)) {
var res = {};
res.errMsg = "找不到model对应的唯一key,";
res.model = model;
fail(res);
}
if (!isUndefined(complete)) {
complete();
}

}

}
/**
* updatetime进行排序
*/
function updateData(engine, model, succ, fail, complete) {
var result = false;
if (engine.dataExist(model)) {
console.warn(engine.getTag() + "updateData check msg:update exist :", model);
}
model.updatetime = new Date().getTime();

result = engine.putData(model);
if (result) {//基本上不可能失败 key
engine.submit(succ, fail, complete);
} else {
console.error(engine.getTag() + " 提交更新失败");
}
return result;
}
module.exports.MapUtil = MapUtil;
module.exports.LikeEngine = LikeEngine;
module.exports.HistoryEngine = HistoryEngine;

播放历史的实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
Page({
data: {
edit: false,
items: [],
checkCount: 0
},
onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数
mEngine = mMaputil.HistoryEngine();//每次创建/ 在城阳
this.queryData();

},
queryData: function () {
var that = this;
util.showLoading();
mEngine.edit(function () {


}, function () {
//应该是没有进行初始化
console.debug("edit模式进入失败");
}, function () {
util.hideLoading();
});


var currentItems = mEngine.query();
for(var i=0;i<currentItems.length;i++){
currentItems[i].updatetimeStr = util.getAboutTime(new Date(currentItems[i].updatetime));
}
currentItems.sort(function (model1, model2) {
return model2.updatetime - model1.updatetime
});
console.debug("items:", currentItems);
that.setData({ items: currentItems });


},
onReady: function () {
// 页面渲染完成
},
onShow: function () {
// 页面显示
},
onHide: function () {
// 页面隐藏
},
onUnload: function () {
// 页面关闭
}, onPullDownRefresh: function () {
this.queryData();
}, onCancelClick: function () {
this.check(false);
this.setData({ edit: false });
}, onCheckAllClick: function () {
// this.checkItems=this.items.concat();

this.check(true);

},
check: function (check) {
var items = this.data.items;
if (items == null || typeof (items) == "undefined") {
util.showDialog("没有数据!");
return;
}
for (var i = 0, len = items.length; i < len; i++) {
items[i].checked = check;
}
this.setData({ items: items, checkCount: check == false ? 0 : items.length });
}
, onDelClick: function () {
var that=this;
if (this.data.checkCount == 0) {
util.showToast("别闹!请先选择一个数据");
return;
}
util.showLoading();
var items = this.data.items;
var deleteArr = [];
for (var index = 0; index < items.length; index++) {
var model = items[index];
if (model.checked) {
deleteArr.push(model);//add
} else {
console.debug("没有选中", model);
}
}
console.debug("删除总数:", deleteArr);
mEngine.removeMulti(deleteArr, function (succCount) {
var arr = mEngine.query();
var json = {};
json.items = arr;
json.checkCount=0;
that.setData(json);
util.showDialog("删除成功 ");
}, function (e) {
util.showDialog("删除失败" + e.errMsg);
}, function () {
util.hideLoading();
});


}, onEditClick: function (e) {
this.setData({ edit: true });
console.log(this.data.edit)
console.log(e)
}
// , checkboxChange: function (e) {
// console.debug("check", e);
// //checkCount
// }
, onItemClick: function (e) {
if (this.data.edit) {
return;
}
console.debug("res", e);
var param = '/pages/story/play/play?id=' + e.currentTarget.dataset.id + "&classid=" + e.currentTarget.dataset.classid;
wx.navigateTo({
url: param,
success: function (res) {
// success
},
fail: function (e) {
// fail
console.debug("无法跳转", e);
},
complete: function () {
// complete
}
})
}, checkboxClick: function (e) {

var index = parseInt(e.currentTarget.dataset.index);
var model = this.data.items[index];
model.checked = model.checked == undefined || model.checked == false ? true : false;
var result = {};
result.checkCount = model.checked ? this.data.checkCount + 1 : this.data.checkCount - 1;
result.items = this.data.items;
this.setData(result);
console.debug("e", e);
}


// <text class="edit_cancel" bindtap="onCancelClick">取消</text>
// <text class="edit_check_all" bindtap="onCheckAllClick">全选</text>
// <text class="edit_del" bindtap="onDelClick">删除</text>
// </block>
// <block wx:else>
// <text class="edit_text" bindtap="onEditClick">编辑</text>
})