优化bmob小程序SDK

//代码重构
const default_info=require(‘als_config.js’);
const pageConfig =default_info.config;
const token_key = default_info.token_key;
const TextStyle =’#ffffff’;//导航字体颜色
Bmob.initialize(default_info.bmob_key, default_info.bmob_secret);
var start_arr = default_info.start_arr, is_debug = default_info.is_debug;
const route_num = 1, limit_add= 20, load_time = 900, order_desc = “updatedAt”, is_index = ‘index’;

const _URL = {
version:’1.0.6′,
limit_num:10,
_bmobFunc: function (tablename,method = ”, param = ”, attr = ”, include=”){
var _self=this;
const query = Bmob.Query(tablename);
if (_self._notEmpty(attr)==false){
attr=tablename;
}
if (_self._notEmpty(include)) {
query.include(include);
}

query.order(order_desc);
query.limit(_self.limit_num);
// query.skip(10);
if (is_debug) {
console.log(query)
}
var pro_fn= new Promise(function (resolve, reject) {
switch (method){
case ‘all’:
if (param.constructor === Object) {
for (let key in param) {
query.equalTo(key, ‘==’, param[key])
}
}
query.find().then(res => {
if (param != ‘no’) {
_self._change_data(attr,res)
}
if (is_debug) {
console.log(“我是全部”)
console.log(res)
}
resolve(res);
});
break;
case ‘update’:
if (param.constructor === Object) {
for (let key in param) {
// query.set(‘id’, ‘objectId’) 需要修改的objectId
query.set(key,param[key])
}
}
query.save().then(res => {
console.log(res)
resolve(res);
}).catch(err => {
console.log(err)
});
break;
case ‘get_one’:
query.get(attr).then(res => {//查改
console.log(res)
if (param.constructor === Object) {
for (let key in param) {
res.set(key,param[key])
}
res.save();
}
resolve(res);
}).catch(err => {
console.log(err)
})
break;
case ‘add’:
if (param.constructor === Object) {//添加
for (let key in param) {
query.set(key, param[key])
}
query.save().then(res => {
resolve(res);
}).catch(err => {
console.log(param)

console.log(err)
})
}
break;
case ‘del_one’:
query.destroy(attr).then(res => {
console.log(res)
resolve(res);
}).catch(err => {
console.log(err)
})
break;
default:
if (param.constructor === Object) {
for (let key in param) {
query.equalTo(key, “==”, param[key]);
}
}
query.find().then(res => {
if(_self._notEmpty(res)){
if (method!=’no’){
_self._change_data(attr, res[0])
}
if(is_debug){
console.log(res)
}
resolve(res[0]);
}

});
}

})
return pro_fn;

},
_bind_event(e){
var _self=this//指向页面
var app=getApp()
if (!app._on_event || typeof (app._on_event)!=”function”){
app._on_event=function(e){
console.log(“%c app未定义监听_on_event函数”, ‘color:red’);
return true;
}
}
if (!app.call_back || typeof(app.call_back)!=”function”){
app.call_back=function(e){
if(is_debug){
console.log(e)
}
console.log(“%c app未定义回调call_back函数”, ‘color:red’);
}
}
var is_hook = app._on_event.call(this,e);
var sdk = app.get_sdk;
if (is_debug) {
console.log(e)
console.log(sdk)
}
if (is_hook){
var e_type=e.type
var info=e.target.dataset
var formId=e.detail.formId

var page = info.page, id = info.id, vclass = info.vclass,toggle=info.toggle,local=info.local
var openid = wx.getStorageSync(‘openid’)
if (vclass) {
var v_obj = sdk._param_str(vclass,true)
for (let key in v_obj) {
sdk._change_data(key, v_obj[key])
if(local){
wx.setStorageSync(key, v_obj[key])
}
}
}
if(toggle){
console.log(toggle)
var toggle_arr = _self.data[toggle]?false:true;
sdk._change_data(toggle,toggle_arr);
}
if(openid &&formId){

}
if(info.param){
var param=sdk._param_str(info.param);
sdk._bmobFunc(info.table, info.method, param).then((res)=>{
app.call_back.call(this,res,info);
})
}
if(page){
_self.topage(page);
}
}
},

_time_str: function (o, t) {
var i = [“Y”, “M”, “D”, “h”, “m”, “s”], n = [], a = new Date(1e3 * o);
n.push(a.getFullYear()), n.push(e(a.getMonth() + 1)), n.push(e(a.getDate())), n.push(e(a.getHours())),
n.push(e(a.getMinutes())), n.push(e(a.getSeconds()));
for (var c in n) t = t.replace(i[c], n[c]);
return t;
},
_param_str(param,opt=”){
let obj={};
var params =param.split(‘,’);
var plength = params.length;
if (plength > 0) {
for (var i = 0; i < plength; i++) { if (i % 2 == 0) { if(opt==true){ if (params[i + 1]=='true'){ params[i + 1]=true; } else if (params[i + 1] == 'false' || params[i + 1]==''){ params[i + 1]=false; } obj[params[i]] = params[i + 1]; }else{ obj[params[i]] = params[i + 1]; } } } } return obj; }, _start(info = 'index', count_data= '') { var app = getApp() var _self=this; var pages = getCurrentPages() var currentPage = pages[pages.length - 1] if (currentPage){ var routeArr= currentPage.route.split("/"); var pagedata, eventdata, nav, def_data, bottomdata;//初始化页面配置 var route=routeArr[route_num]||'index'; if (_self._notEmpty(pageConfig[route])) { pagedata = pageConfig[route].onload eventdata = pageConfig[route].onshow var nav = pageConfig[route].nav def_data=pageConfig[route].data bottomdata=pageConfig[route].bottom if(nav){ _self._set_info(nav) } } var openid = wx.getStorageSync('openid') if (app.aldstat) {//阿拉丁统计 } var t = currentPage; t.onLoad && function(){ var n = t.onLoad; _self.limit_num = limit_add; if(_self._notEmpty(pagedata)){ pagedata.forEach(function(val){ var opt = t.options; console.log(opt); if (val.param && _self._notEmpty(opt)) { let opt_param = val.param; let opt_info = opt[opt_param]; val.param = { opt_param, opt_info }; } console.log(val.param) _self._bmobFunc(val.table, val.method, val.param, val.attr, val.include); }) } if(_self._notEmpty(def_data)){ for (let key in def_data) { _self._change_data(key, def_data[key]) } } t.topage = _self._topage;//公共跳转功能 t._bind_event=_self._bind_event; t.toapp=_self._toapp; t.data.app_data = app.globalData; t.onLoad=function(){ n.call(this, arguments); } }(); t.onShow && function(){ var n = t.onShow; t.onShow = function (opt) { var nowpage=this; if (is_debug) { console.log(opt) } if (app.globalData.config.can_show!=true){ console.log("请求开关") _self._change_app(); } wx.showToast({ title: "加载中...", icon: "loading", duration: load_time }); if (_self._notEmpty(eventdata)) { console.log("onshow事件") eventdata.forEach(function (val) { if (val.param && typeof (val.param) == 'string') { val.param = _self._get_storage(val.param); } _self._bmobFunc(val.table, val.method, val.param, val.attr,val.include); }) } n.call(this, arguments); }; }(); t.onShareAppMessage && function(){ var n = t.onShareAppMessage; t.onShareAppMessage=function(){ console.log("执行分享") n.call(this, arguments); } }(); t.onReachBottom && function(){ var n = t.onReachBottom; t.onReachBottom=function(){ if (_self._notEmpty(bottomdata)) { console.log("bottom事件") _self.limit_num += limit_add; console.log(_self.limit_num) if(_self.limit_num<=400){ bottomdata.forEach(function (val) { _self._bmobFunc(val.table, val.method, val.param, val.attr, val.include); }) } } n.call(this,arguments); } }(); if (is_debug) { console.log(t) } } }, _get_storage(str) { var obj = {} if (str) { var str_arr = str.split(','); var slen = str_arr.length console.log("本地数据读取") if (slen > 0) {
for (var i = 0; i < slen; i++) { var attr = str_arr[i] obj[attr] = wx.getStorageSync(attr); } } } return obj; }, _topage(e, id = '') { var page if (is_debug) { console.log(e) } if (e.constructor === Object) { console.log("33") id = e.target.dataset.id page = e.target.dataset.page var appid = e.target.dataset.appid var path = e.target.dataset.path if (!path) { path = "pages/index/index" } if (appid) { this.toapp(appid, path) } else if (page) { wx.navigateTo({ url: page + '?id=' + id, }) } } else { page = e; if(page=="back"){ wx.navigateBack({ delta:1 }) }else{ wx.navigateTo({ url: page + '?id=' + id, }) } } }, _toapp(appid,path=''){ wx.navigateToMiniProgram({ appId: appid, path:path, extraData: { foo: 'bar', als_skd:'1.06' }, envVersion: 'release', success(res) { // 打开成功 console.log("跳转成功") if(is_debug){ console.log(res) } } }) }, _change_data(attr='',data=''){ var _self = this; var pages = getCurrentPages() var currentPage = pages[pages.length - 1] currentPage.setData({ [attr]: data }) }, _ald_count(event_name,count_data){ if (is_debug) { console.log(event_name) } app.aldstat.sendEvent(event_name, count_data); }, _set_info(nav){ var title=nav.title var bgcolor=nav.bgcolor if(title){ wx.setNavigationBarTitle({ title: title }) } if(bgcolor){ wx.setNavigationBarColor({ frontColor: TextStyle, backgroundColor:bgcolor, }) } }, _rand_num(num=''){ num=num?num:0.5; var is_true = Math.random()>num?true:false;
return is_true;
},
_notEmpty(obj) {
// 检验 undefined 和 null 参数检测
if(!obj || obj == ” ||obj == undefined) {return false;}
if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) {return false;  }
if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) {    return false;  }   
return true;
},
_sys_info(){
var a = wx.getSystemInfoSync();
a.app=wx.getLaunchOptionsSync();
wx.getNetworkType({
success: function (b) {
wx.setStorageSync(‘network’,b.networkType)
}
})
a.network=wx.getStorageSync(‘network’);
return a;

},

init(code = ”,options=”) {
var _self=this

var app = getApp()
var openid
if (code) {
Bmob.User.requestOpenId(code).then((res)=>{
if(res && res.openid){
openid=res.openid
app.globalData.openid = openid;
wx.setStorageSync(‘openid’, openid)
}
})
}
_self._change_app();
// var a=_self._sys_info();//设备信息
// app.get_sdk=get_sdk();
app.get_sdk =this;

_self._start(is_index,’all’);
if (is_debug) {
console.log(app)
}
},
_change_app(){
var _self=this
let app=getApp()
_self._bmobFunc(start_arr[0], ‘no’).then((res) => {
if (res) {
app.globalData.config = res;
}
})
},
_showTips: function(title, content,callback=””) { //提示
wx.showModal({
title: title,
content: content,
showCancel: false,
success: function(res) {
if(res.confirm){
typeof (callback)==”function”&&callback()
}
}
});
},

};
// _bind_event.prototype.toggle = function () {

// };
// Function.prototype.before = function (fn) {
// var self = this;
// return function () {
// var res = fn.call(this);

// if (res) {
// self.call(this, arguments);
// }
// }
// };

// Function.prototype.after = function (fn) {
// var self = this;

// return function () {
// self.call(this, arguments);
// fn.call(this);
// }
// };
var D=[‘geta’,’getb’]
for (var i=0;i

This entry was posted in 编程 by .

发表评论

电子邮件地址不会被公开。 必填项已用*标注