前言:
apicloud中最常用的兩種打開新頁面的方式是 openWin 和 openFrame
而apicloud提供的api:
api.addEventListener({
? ? ????name: 'keyback'
????}, function(ret, err){? ??
????????alert('按了返回鍵');
});
必須在 Window 中注冊才有效,F(xiàn)rame 中注冊無效,并且只在當前屏幕上的 window 才能收到回調。
但是 openWin 占用的資源比 openFrame 高太多,稍微打開幾個頁面就會有明顯的卡頓。
因此這里簡單的實現(xiàn)了一個通過攔截 openFrame,在緩存中實現(xiàn)一個簡單的historyList,來實現(xiàn)點擊物理返回實現(xiàn)返回上一頁
準備:
新打開一個頁面:
api.openFrame({
? ? ? ? name: name, // 新打開的Frame的名字,apicloud會根據(jù)名字來判斷到底是哪個frame
? ? ? ? url: path. // 打開頁面的地址
? ? });
設置緩存:
api.setGlobalData({
? ? ? ? ? ? key: 'historyList', // 存放的緩存的 key
? ? ? ? ? ? value: JSON.stringify(historyList), // 官方文檔說介意放json對象,但是數(shù)組放不了,所以轉換成字符串
? ? ? ? });
獲取緩存:
api.getGlobalData({
? ? ? ? key: 'historyList' // 根據(jù)ke來獲取緩存
? ? })
實現(xiàn):
首先新建一個 tools.js 文件,里面放上下邊代碼:
let whiteList = ['login', 'home']? // 按下返回鍵退出程序的頁面,若不在whiteList中則是返回上一頁
// 跳轉? 參數(shù): 新打開frame的名字 | 新打開頁面的路徑 | 需要傳遞的參數(shù)
function goto (name, path, pageParam) {
? ? // 保存歷史記錄
? ? let historyList = api.getGlobalData({
? ? ? ? key: 'historyList'
? ? }) || '[]'; // 歷史記錄 首次進入是沒有值的 所以賦值為字符串 ‘[]’?
? ? historyList = JSON.parse(historyList) // 轉換為數(shù)組
? ? historyList.push(name)? ? ?// 將新頁面放進history
? ? api.setGlobalData({ // 將history 存入緩存
? ? ? ? key: 'historyList',
? ? ? ? value: JSON.stringify(historyList)
? ? });
? ? api.openFrame({ // 打開新頁面
? ? ? ? name: name,
? ? ? ? url: path,
? ? ? ? bounces: false,
? ? ? ? rect: {
? ? ? ? ? ? w: 'auto'
? ? ? ? },
? ? ? ? animation: {
? ? ? ? ? ? type: 'push',
? ? ? ? ? ? subType: 'from_bottom'
? ? ? ? },
? ? ? ? pageParam: pageParam // 需要傳遞的參數(shù)
? ? });
}
// 返回上一頁
function back () {
? ? let historyList = api.getGlobalData({
? ? ? ? key: 'historyList'
? ? }); // 獲取歷史記錄
? ? historyList = JSON.parse(historyList)? // 轉換為數(shù)組
? ? let frame = historyList[historyList.length - 1]? // 獲取到當前頁面的name,即最后打開的這個頁面
? ? if (whiteList.includes(frame)) { // 如果是在 whiteList 中則執(zhí)行 關閉app 的操作
? ? ? ? api.closeWidget({
? ? ? ? ? ? id: appID // 這里替換成你的appid
? ? ? ? });
? ? } else { // 若沒在whiteList中 則執(zhí)行返回上一頁操作
? ? ? ? historyList.pop() // 將本頁從history中移除
? ? ? ? api.setGlobalData({?
? ? ? ? ? ? key: 'historyList',
? ? ? ? ? ? value: JSON.stringify(historyList) // 更新historyList
? ? ? ? });
? ? ? ? api.closeFrame({ // 關閉本頁,apicloud自動打開上一個frame,實現(xiàn)返回上一頁的效果
? ? ? ? ? ? name: frame
? ? ? ? })
? ? }
}
最后,在程序入口頁面 index.html中先引入 tools.js, 然后放入以下代碼:
apiready = function() {
? ? ? ? goto('login', 'html/login.html') // 進入程序跳轉到登錄頁,根據(jù)自己情況調整
? ? ? ? // 攔截返回鍵?
? ? ? ? api.addEventListener({
? ? ? ? ? ? name: 'keyback'
? ? ? ? }, function(ret, err) {
? ? ? ? ? ? back() // 執(zhí)行返回操作
? ? ? ? ? ? return
? ? ? ? });
? ? };
后言:
goto 和 back 方法中可以拓展很多內容,
比如返回是否刷新上一頁,實現(xiàn)自定義router等等
我這個程序比較簡單就深入了。
文中如果有地方講的不對,歡迎指正,歡迎交流。