https://blog.csdn.net/z564359805/article/details/118442507

后来发现之前这一篇好像不能实现不同tabbar之间的通信,所以写的这一篇,此例页面订阅方要想接收数据必须打开过,也就是加载订阅的方法,从来没有加载过是不可以的【先订阅,后发布】:

参考:https://github.com/mroderick/PubSubJS

在utils文件夹中新建pubsub-js.js:

module.exports = (function() {var __MODS__ = {};var __DEFINE__ = function(modId, func, req) { var m = { exports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = { exports: {} }; __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); if(typeof m.exports === "object") { __MODS__[modId].m.exports.__proto__ = m.exports.__proto__; Object.keys(m.exports).forEach(function(k) { __MODS__[modId].m.exports[k] = m.exports[k]; var desp = Object.getOwnPropertyDescriptor(m.exports, k); if(desp && desp.configurable) Object.defineProperty(m.exports, k, { set: function(val) { __MODS__[modId].m.exports[k] = val; }, get: function() { return __MODS__[modId].m.exports[k]; } }); }); if(m.exports.__esModule) Object.defineProperty(__MODS__[modId].m.exports, "__esModule", { value: true }); } else { __MODS__[modId].m.exports = m.exports; } } return __MODS__[modId].m.exports; };var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };__DEFINE__(1602927017928, function(require, module, exports) {/*** Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk* License: MIT - http://mrgnrdrck.mit-license.org** https://github.com/mroderick/PubSubJS*/(function (root, factory){var PubSub = {};root.PubSub = PubSub;var define = root.define;factory(PubSub);// AMD supportif (typeof define === 'function' && define.amd){define(function() { return PubSub; });// CommonJS and Node.js module support} else if (typeof exports === 'object'){if (module !== undefined && module.exports) {exports = module.exports = PubSub; // Node.js specific `module.exports`}exports.PubSub = PubSub; // CommonJS module 1.1.1 specmodule.exports = exports = PubSub; // CommonJS}}(( typeof window === 'object' && window ) || this, function (PubSub){var messages = {},lastUid = -1,ALL_SUBSCRIBING_MSG = '*';function hasKeys(obj){var key;for (key in obj){if ( obj.hasOwnProperty(key) ){return true;}}return false;}/*** Returns a function that throws the passed exception, for use as argument for setTimeout* @alias throwException* @function* @param { Object } ex An Error object*/function throwException( ex ){return function reThrowException(){throw ex;};}function callSubscriberWithDelayedExceptions( subscriber, message, data ){try {subscriber( message, data );} catch( ex ){setTimeout( throwException( ex ), 0);}}function callSubscriberWithImmediateExceptions( subscriber, message, data ){subscriber( message, data );}function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){var subscribers = messages[matchedMessage],callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,s;if ( !messages.hasOwnProperty( matchedMessage ) ) {return;}for (s in subscribers){if ( subscribers.hasOwnProperty(s)){callSubscriber( subscribers[s], originalMessage, data );}}}function createDeliveryFunction( message, data, immediateExceptions ){return function deliverNamespaced(){var topic = String( message ),position = topic.lastIndexOf( '.' );// deliver the message as it is nowdeliverMessage(message, message, data, immediateExceptions);// trim the hierarchy and deliver message to each levelwhile( position !== -1 ){topic = topic.substr( 0, position );position = topic.lastIndexOf('.');deliverMessage( message, topic, data, immediateExceptions );}deliverMessage(message, ALL_SUBSCRIBING_MSG, data, immediateExceptions);};}function hasDirectSubscribersFor( message ) {var topic = String( message ),found = Boolean(messages.hasOwnProperty( topic ) && hasKeys(messages[topic]));return found;}function messageHasSubscribers( message ){var topic = String( message ),found = hasDirectSubscribersFor(topic) || hasDirectSubscribersFor(ALL_SUBSCRIBING_MSG),position = topic.lastIndexOf( '.' );while ( !found && position !== -1 ){topic = topic.substr( 0, position );position = topic.lastIndexOf( '.' );found = hasDirectSubscribersFor(topic);}return found;}function publish( message, data, sync, immediateExceptions ){message = (typeof message === 'symbol') ? message.toString() : message;var deliver = createDeliveryFunction( message, data, immediateExceptions ),hasSubscribers = messageHasSubscribers( message );if ( !hasSubscribers ){return false;}if ( sync === true ){deliver();} else {setTimeout( deliver, 0 );}return true;}/*** Publishes the message, passing the data to it's subscribers* @function* @alias publish* @param { String } message The message to publish* @param {} data The data to pass to subscribers* @return { Boolean }*/PubSub.publish = function( message, data ){return publish( message, data, false, PubSub.immediateExceptions );};/*** Publishes the message synchronously, passing the data to it's subscribers* @function* @alias publishSync* @param { String } message The message to publish* @param {} data The data to pass to subscribers* @return { Boolean }*/PubSub.publishSync = function( message, data ){return publish( message, data, true, PubSub.immediateExceptions );};/*** Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe* @function* @alias subscribe* @param { String } message The message to subscribe to* @param { Function } func The function to call when a new message is published* @return { String }*/PubSub.subscribe = function( message, func ){if ( typeof func !== 'function'){return false;}message = (typeof message === 'symbol') ? message.toString() : message;// message is not registered yetif ( !messages.hasOwnProperty( message ) ){messages[message] = {};}// forcing token as String, to allow for future expansions without breaking usage// and allow for easy use as key names for the 'messages' objectvar token = 'uid_' + String(++lastUid);messages[message][token] = func;// return token for unsubscribingreturn token;};PubSub.subscribeAll = function( func ){return PubSub.subscribe(ALL_SUBSCRIBING_MSG, func);};/*** Subscribes the passed function to the passed message once* @function* @alias subscribeOnce* @param { String } message The message to subscribe to* @param { Function } func The function to call when a new message is published* @return { PubSub }*/PubSub.subscribeOnce = function( message, func ){var token = PubSub.subscribe( message, function(){// before func apply, unsubscribe messagePubSub.unsubscribe( token );func.apply( this, arguments );});return PubSub;};/*** Clears all subscriptions* @function* @public* @alias clearAllSubscriptions*/PubSub.clearAllSubscriptions = function clearAllSubscriptions(){messages = {};};/*** Clear subscriptions by the topic* @function* @public* @alias clearAllSubscriptions* @return { int }*/PubSub.clearSubscriptions = function clearSubscriptions(topic){var m;for (m in messages){if (messages.hasOwnProperty(m) && m.indexOf(topic) === 0){delete messages[m];}}};/** Count subscriptions by the topic* @function* @public* @alias countSubscriptions* @return { Array }*/PubSub.countSubscriptions = function countSubscriptions(topic){var m;var count = 0;for (m in messages){if (messages.hasOwnProperty(m) && m.indexOf(topic) === 0){count++;}}return count;};/** Gets subscriptions by the topic* @function* @public* @alias getSubscriptions*/PubSub.getSubscriptions = function getSubscriptions(topic){var m;var list = [];for (m in messages){if (messages.hasOwnProperty(m) && m.indexOf(topic) === 0){list.push(m);}}return list;};/*** Removes subscriptions** - When passed a token, removes a specific subscription.** - When passed a function, removes all subscriptions for that function** - When passed a topic, removes all subscriptions for that topic (hierarchy)* @function* @public* @alias subscribeOnce* @param { String | Function } value A token, function or topic to unsubscribe from* @example // Unsubscribing with a token* var token = PubSub.subscribe('mytopic', myFunc);* PubSub.unsubscribe(token);* @example // Unsubscribing with a function* PubSub.unsubscribe(myFunc);* @example // Unsubscribing from a topic* PubSub.unsubscribe('mytopic');*/PubSub.unsubscribe = function(value){var descendantTopicExists = function(topic) {var m;for ( m in messages ){if ( messages.hasOwnProperty(m) && m.indexOf(topic) === 0 ){// a descendant of the topic exists:return true;}}return false;},isTopic    = typeof value === 'string' && ( messages.hasOwnProperty(value) || descendantTopicExists(value) ),isToken    = !isTopic && typeof value === 'string',isFunction = typeof value === 'function',result = false,m, message, t;if (isTopic){PubSub.clearSubscriptions(value);return;}for ( m in messages ){if ( messages.hasOwnProperty( m ) ){message = messages[m];if ( isToken && message[value] ){delete message[value];result = value;// tokens are unique, so we can just stop herebreak;}if (isFunction) {for ( t in message ){if (message.hasOwnProperty(t) && message[t] === value){delete message[t];result = true;}}}}}return result;};}));}, function(modId) {var map = {}; return __REQUIRE__(map[modId], modId); })return __REQUIRE__(1602927017928);})()//# sourceMappingURL=index.js.map

通信的页面,订阅方也就是接收数据的页面palylist.js:

import PubSub from '../../utils/pubsub-js'
....
onLoad: function (options) {// 页面通信,订阅动态获取歌曲详情页的歌曲名字和idPubSub.subscribe('switchType', (msg, type) => {console.log("type", type) // type:{playId: 280896, playName: "相见恨晚"}})
}onUnload: function () {// 取消订阅PubSub.unsubscribe('switchType');
},

发布方,发送数据页面songdetail.js:

import PubSub from '../../utils/pubsub-js'
....
onLoad: function (options) {let playId = 280896;let playName= "相见恨晚";// 发布消息数据给palylist页面PubSub.publish('switchType', {playId,playName})},

微信小程序页面间通信实现pub-sub相关推荐

  1. 微信小程序页面间通信的5种方式

    微信小程序页面间通的5种方式 PageModel(页面模型)对小程序而言是很重要的一个概念,从app.json中也可以看到,小程序就是由一个个页面组成的. 如上图,这是一个常见结构的小程序:首页是一个 ...

  2. 【愚公系列】2022年02月 微信小程序-页面间通信

    文章目录 前言 1.页面通信分类 一.GET类通信 二.POST类通信 三.localStorage通信 四.全局参数通信 五.发布订阅中间件 六.oba开源库 七.hack方法 总结 前言 在小程序 ...

  3. 微信小程序-页面间通信

    当前测试的基础库版本为 2.17.0 页面分类 tabBar 页面 - app.json中配置的 tabBar 页面 page 页面 - 其他的 非tabBar 页面,后面称为 page 页面 跳转页 ...

  4. 微信小程序-页面间如何进行传递数据(通信)

    前言 在小程序中组件与组件之间的通信是通过在引用组件处,在自定义组件上添加自定义属性实现的,子组件内部通过properties进行接收 更多关于组件与组件之间的通信可参考小程序-实现自定义组件以及自定 ...

  5. 微信小程序组件间通信(二)

    2019独角兽企业重金招聘Python工程师标准>>> 一.微信小程序中通过事件,实现子组件向父组件中传递数据或操作 注:子组件向父组件中传递通过事件传递操作 通过事件参数对象det ...

  6. 详解微信小程序页面间传递信息的三种方式

    详解微信小程序页面间传递信息的三种方式 在开发微信小程序的时候,经常会遇到在页面间传递信息的情况,有三种方法可以实现. 1. 使用数据缓存 将要存储的数据使用以下方法放入缓存 wx.setStorag ...

  7. vue 传参 微信_小猿圈web前端之微信小程序页面间跳转传参方式总结

    原标题:小猿圈web前端之微信小程序页面间跳转传参方式总结 最近小程序发展的越来越快,很多大公司也在打造自己的小程序平台以及购物小程序等等,今天小猿圈web前端讲师就总结了关于微信小程序的知识点,首先 ...

  8. 微信小程序页面间传递数组对象

    在微信小程序中,有时候使用wx.navigateTo()跳转页面时要传递过长的参数或者传递一个数组对象会发现传递不过去 情景再现: 发送端 接收端 输出值 我们可以使用以下方法解决: 在发送端对数据进 ...

  9. 微信小程序页面间传递文本数据

    写了一个微信小程序可以实现记录日记的功能.当点击编辑时,会再另一个页面中显示这个页面的日记数据,发现通过传递参数的方法很不现实,就在网上搜集了各种方法来实现,其中一个比较可取的方法是利用getCurr ...

最新文章

  1. 规格选项表管理之保存规格选项表数据
  2. 拉勾网《32个Java面试必考点》学习笔记之二------操作系统与网络知识
  3. EGOImageView 解析
  4. ionic常见问题及解决方案
  5. 软件工程 - 团队博客第二阶段成绩
  6. html5嵌套css语言,HTML5和CSS3
  7. php 经典的算法,PHP各种经典算法
  8. 基于JAVA+SpringBoot+Mybatis+MYSQL的酒店管理系统
  9. Ancient Knight(打造Windows Mobile平台最专业的游戏修改器)
  10. NET开发资源站点和部分优秀.NET开源项目
  11. win7查看计算机设置密码,如何查看win7电脑开机密码_win7专业版电脑开机密码怎么查看...
  12. 贫困的苏州(转自新浪)
  13. 淘宝校招鸡蛋篮子算法题标准答案
  14. 浅谈股价预测模型:你是否掉进机器学习的陷阱
  15. 数据库系统是由那些组成的?
  16. 基于JavaScript的餐厅点餐系统微信小程序的设计与实现
  17. Docker 容器镜像无法正常启动,日志抛出Unable to access jarfile问题的解决方法
  18. XML学习笔记——XSL
  19. 计算机课上最难忘的一幕
  20. 新书推荐 |《Linux系统安全:纵深防御、安全扫描与入侵检测》

热门文章

  1. fp16与fp32简介与试验
  2. sql横着连接起来sql_SQL联接
  3. 冀教版五年级计算机教学计划,冀教版信息技术五年级下册教学计划.doc
  4. mysql count 多列_COUNT( )函数对多列数据计数的实例
  5. MyBatisPlus--多数据源
  6. php适应浏览器显示,浏览器变动时进行自适应代码分享
  7. 如何不被程序员(RD)们嫌弃--写给那些血气方刚的产品经理(PM)
  8. utran体系结构包括_接入网体系结构
  9. 实时的YcoCg-DXT压缩
  10. mysql日志备份命令是什么_mysql的常用命令以及备份和恢复