this.PubSubCache.$uid++;
cache[handler.$uid] = handler;
}
emit(type, ...param) {
let cache = this.PubSubCache[type],
key,
tmp;
if(!cache) return;
for(key in cache) {
tmp = cache[key];
cache[key].call(this, ...param);
}
}
off(type, handler) {
let counter = 0,
$type,
cache = this.PubSubCache[type];
if(handler == null) {
if(!cache) return true;
return !!this.PubSubCache[type] && (delete this.PubSubCache[type]);
} else {
!!this.PubSubCache[type] && (delete this.PubSubCache[type][handler.$uid]);
}
for($type in cache) {
counter++;
}
return !counter && (delete this.PubSubCache[type]);
}
}
//pageA
let app = getApp();
Page({
data: {
helloMsg: 'hello from PageA'
},
onLoad() {
app.pubSub.on('hello', (number) => {
this.setData({
helloMsg: 'hello times:' + number
});
});
},
goC() {
wx.navigateTo({
url: '/pages/c/c'
});
}
});//pageC
let app = getApp();
let counter = 0;
Page({
doSomething() {
app.pubSub.emit('hello', ++counter);
},
off() {
app.pubSub.off('hello');
}
});缺点:要非常注意重复绑定的问题
方式四:gloabelData watcher方式
前面提到方式中,我们有利用globalData完成通信。现在数据绑定流行,结合redux单一store的思想,如果我们直接watch一个globalData,那么要通信,只需修改这个data值,通过water去激活调用。同时修改的data值,本身就可以做为参数数据。
为了方便演示,这里使用oba这个开源库做为对象监控库,有兴趣的话,可以自己实现一个。
//pageA
import oba from '../../plugin/oba';
let app = getApp();
Page({
data: {
helloMsg: 'hello from PageA'
},
onLoad() {
oba(app.$$data, (prop, newvalue, oldValue) => {
this.setData({
helloMsg: 'hello times: ' + [prop, newvalue, oldValue].join('#')
});
});
},
goC() {
wx.navigateTo({
url: '/pages/c/c'
});
}
});//pageC
let app = getApp();
let counter = 0;
Page({
doSomething() {
app.$$data.helloTimes = ++counter;
}
});优点:数据驱动,单一数据源,便于调试
缺点:重复watch的问题还是存在,要想办法避免
方式五:通过hack方法直接调用通信页面的方法
直接缓存页面PageModel, 通信时,直接找到要通信页面的PageModel,进而可以访问通信页面PageModel所有的属性,方法。简直不能太cool,感谢小组内小伙伴发现这么amazing的方式。有人肯定会问了,怎么拿到这个所有的PageModel呢。其它很简单,每个页面有onLoad方法,我们在这个事件中,把this(即些页面PageModel)缓存即可,缓存时用页面路径作key,方便查找。那么页面路径怎么获取呢,答案就是page__route__这个属性
// plugin/pages.js
// 缓存pageModel,一个简要实现
export default class PM {
constructor() {
this.$$cache = {};
}
add(pageModel) {
let pagePath = this._getPageModelPath(pageModel);
this.$$cache[pagePath] = pageModel;
}
get(pagePath) {
return this.$$cache[pagePath];
}
delete(pageModel) {
try {
delete this.$$cache[this._getPageModelPath(pageModel)];
} catch (e) {
}
}
_getPageModelPath(page) {
// 关键点
return page.__route__;
}
}// pageA
let app = getApp();
Page({
data: {
helloMsg: 'hello from PageA'
},
onLoad() {
app.pages.add(this);
},
goC() {
wx.navigateTo({
url: '/pages/c/c'
});
},
sayHello(msg) {
this.setData({
helloMsg: msg
});
}
});//pageC
let app = getApp();
Page({
doSomething() {
// 见证奇迹的时刻
app.pages.get('pages/a/a').sayHello('hello u3xyz.com');
}
});优点:一针见血,功能强大,可以向要通信页面做你想做的任何事。无需要绑定,订阅,所以也就不存在重复的情况
缺点:使用了__route__这个hack属性,可能会有一些风险
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
微信小程序 页面跳转传参的介绍
微信小程序的页面跳转传值的实现
微信小程序 页面跳转和数据传递
以上就是微信小程序中页面间通信的方式的详细内容,更多请关注php中文网其它相关文章!
小程序是一种不需要下载安装即可使用的应用,它实现了应用“触手可及”的梦想,用户扫一扫或者搜一下即可打开应用。
关键词:微信小程序中页面间通信的方式