Page communication between Baidu applet

Page communication between Baidu applet

author: @TiffanysBear

background

The main problem is for communication between the applet page development, in scenes involving payment, the user pays the entrance to jump from page to make payments after the return to the original page, you need to make the appropriate state to refresh the original page, such as user identity status, payment status, documents or merchandise case.

Problems encountered

When using swan.navigateBack Baidu applet will be back jump page, method parameters in the API does not support the argument carries only support number parameters.

It involves the problem of communication between several separate page. Mainly the following several methods are listed for reference.

swan.navigateBack

parameter name Types of Mandatory Defaults Explanation
delta Number no 1 The number of pages returned if the delta is greater than the existing number of pages, then return to the home page 1.
success function no - Interface call success callback function
fail function no - Interface calls the failure callback function
complete function no - Interface calls the end of the callback function (call succeeds, the failure will be executed)

Solution

There are three main methods to achieve the communication between the page.

One solution: use app.js, set up a public variable

App.js use of common features, variable hung on APP.

// app.js 启动文件
App({
    globalData: {
        isLogin: false,
        userInfo: null,
        networkError: false,
        networkType: 'none'
    }
})

When used on other pages Page, use:

// test.js
const app = getApp();
const commonParams = app.globalData.isLogin;

But the disadvantage is also very obvious, when the data than larger, more complex data relationships, the maintenance would be more complicated, the logic will be very confusing.

Solution two: Using storage

The use of applets global storage, data access, a principle similar to the solution.

// 存储-异步
swan.setStorage({
    key: 'key',
    data: 'value'
});
// 存储-同步
swan.setStorageSync('key', 'value');

// 获取-异步
swan.getStorage({
    key: 'key',
    success: function (res) {
        console.log(res.data);
    },
    fail: function (err) {
        console.log('错误码:' + err.errCode);
        console.log('错误信息:' + err.errMsg);
    }
});

// 获取-同步
const result = swan.getStorageSync('key');

Solution three: Using Event Center

Publish and subscribe use for event center.

// event.js 事件中心

class Event {
    on(event, fn, ctx) {
        if (typeof fn !== 'function') {
            console.error('fn must be a function');
            return;
        }

        this._stores = this._stores || {};
        (this._stores[event] = this._stores[event] || []).push({
            cb: fn,
            ctx: ctx
        });
    }
    emit(event, ...args) {
        this._stores = this._stores || {};
        let store = this._stores[event];
        if (store) {
            store = store.slice(0);
            for (let i = 0, len = store.length; i < len; i++) {
                store[i].cb.apply(store[i].ctx, args);
            }
        }
    }
    off(event, fn) {
        this._stores = this._stores || {};
        // all
        if (!arguments.length) {
            this._stores = {};
            return;
        }
        // specific event
        let store = this._stores[event];
        if (!store) {
            return;
        }
        // remove all handlers
        if (arguments.length === 1) {
            delete this._stores[event];
            return;
        }
        // remove specific handler
        let cb;
        for (let i = 0, len = store.length; i < len; i++) {
            cb = store[i].cb;
            if (cb === fn) {
                store.splice(i, 1);
                break;
            }
        }
        return;
    }
}

module.exports = Event;

Be declared and managed in app.js

// app.js
import Event from './utils/event';

App({
    event: new Event()
})

Subscribe to the page, use the method on subscription

// view.js 阅读页进行订阅

Page({
    // 页面在回退时,会调用onShow方法
    onShow() {
        // 支付成功的回调,调起下载弹层
        app.event.on('afterPaySuccess', this.afterPaySuccess, this);
    },
    afterPaySuccess(e) {
        // ....业务逻辑
    }
})

Page published, publish emit based on business case

// paySuccess.js

const app = getApp();

app.event.emit('afterPaySuccess', {
    docId: this.data.tradeInfo.docId,
    triggerFrom: 'docCashierBack'
});

According to publish and subscribe event center, enables communication between the pages, such as a scene change can be achieved when the page is rolled back after successful payment, the page states, while maintaining beneficial relationships between data pages, published by the when passing parameters, communication between the data.

Welcome to doubt, I hope to help you ~

Guess you like

Origin www.cnblogs.com/tiffanybear/p/11203724.html