1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 微信小程序页面间通信实现pub-sub

微信小程序页面间通信实现pub-sub

时间:2021-06-05 19:15:09

相关推荐

微信小程序页面间通信实现pub-sub

/z564359805/article/details/118442507

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

参考:/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) ,,,, Morgan Roderick http://roderick.dk* License: MIT - http://mrgnrdrck.mit-** /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})},

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。