延续上一篇 cordova的原理解释, 参考这里
3. cordova PubSub模式 (channel)
cordova基于观察者模式的,提供了一个自定义的pub-sub模型,基于该模型提供一些事件,用来控制事件什么时候以什么样的顺序被调用,以及事件的调用。
cordova/channel, 的代码结构也是一个很经典的定义结构(构造函数、实例、修改函数原型共享实例方法),它提供事件通道的订阅(subscribe)、撤消订阅(unsubscribe)、调用(fire)等基本方法。最后发布了9个事件。
请看源码 :
// 定义channel模块
define("cordova/channel", function(require, exports, module) {
var utils = require('cordova/utils'),
nextGuid = 1;
/**
* Channel
* @constructor
* @param type String the channel name
* ①事件通道的构造函数
*/
var Channel = function(type, sticky) {
// 事件通道名称
this.type = type;
// 事件通道上的所有事件处理函数Map(索引为guid)
// Map of guid -> function.
this.handlers = {};
// 事件通道的状态(0:非sticky, 1:sticky但未调用, 2:sticky已调用)
// 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
this.state = sticky ? 1 : 0;
// 传给fire()的参数
// Used in sticky mode to remember args passed to fire().
this.fireArgs = null;
// 当前通道上的事件处理函数的个数
// Used by onHasSubscribersChange to know if there are any listeners.
this.numHandlers = 0;
// 订阅第一个事件或者取消订阅最后一个事件时调用自定义的处理
// Function that is called when the first listener is subscribed, or when
// the last listener is unsubscribed.
this.onHasSubscribersChange = null;
},
// ②事件通道外部接口
channel = {
/**
* Calls the provided function only after all of the channels specified
* have been fired. All channels must be sticky channels.
*/
// 把指定的函数h订阅到c的各个通道上,保证h在每个通道的最后被执行
join: function(h, c) {
var len = c.length,
i = len,
f = function() {
if (!(--i)) h();
};
// 把事件处理函数h订阅到c的各个事件通道上
for (var j=0; j<len; j++) {
// 必须是sticky事件通道
if (c[j].state === 0) {
throw Error('Can only use join with sticky channels.');
}
c[j].subscribe(f);
}
// 执行h
if (!len) h();
},
// 创建事件通道
create: function(type) {
return channel[type] = new Channel(type, false);
},
// 创建sticky事件通道
createSticky: function(type) {
return channel[type] = new Channel(type, true);
},
/**
* cordova Channels that must fire before "deviceready" is fired.
*/
// 调用deviceready事件之前要调用的事件,
deviceReadyChannelsArray: [],
deviceReadyChannelsMap: {},
/**
* Indicate that a feature needs to be initialized before it is ready to be used.
* This holds up Cordova's "deviceready" event until the feature has been initialized
* and Cordova.initComplete(feature) is called.
*
* @param feature {String} The unique feature name
*/
// 设置deviceready事件之前必须要完成的事件
waitForInitialization: function(feature) {
if (feature) {
var c = channel[feature] || this.createSticky(feature);
this.deviceReadyChannelsMap[feature] = c;
this.deviceReadyChannelsArray.push(c);
}
},
/**
* Indicate that initialization code has completed and the feature is ready to be used.
* 表明代码已经初始化,并准备好被使用
* @param feature {String} The unique feature name
*/
initializationComplete: function(feature) {
var c = this.deviceReadyChannelsMap[feature];
if (c) {
c.fire();
}
}
};
// 判断是否函数类型, Js中类型的判断可参考这里
function forceFunction(f) {
if (typeof f != 'function') throw "Function required as first argument!";
}
/**
* Subscribes the given function to the channel. Any time that
* Channel.fire is called so too will the function.
* Optionally specify an execution context for the function
* and a guid that can be used to stop subscribing to the channel.
* Returns the guid.
*/
// ③修改函数原型共享实例方法
// 向事件通道订阅事件处理函数(subscribe部分)
// f:事件处理函数 c:事件的上下文(可省略)
Channel.prototype.subscribe = function(f, c) {
// 判读是否函数
forceFunction(f);
// 如果是被订阅过的sticky事件,就直接调用。
if (this.state == 2) {
f.apply(c || this, this.fireArgs);
return;
}
var func = f,
guid = f.observer_guid;
// 如果事件有上下文,要先把事件函数包装一下带上上下文
if (typeof c == "object") { func = utils.close(c, f); }
// 自增长的ID
if (!guid) {
// first time any channel has seen this subscriber
guid = '' + nextGuid++;
}
// 把自增长的ID反向设置给函数,以后撤消订阅或内部查找用
func.observer_guid = guid;
f.observer_guid = guid;
// 判断该guid索引的事件处理函数是否存在(保证订阅一次)
// Don't add the same handler more than once.
if (!this.handlers[guid]) {
// 订阅到该通道上(索引为guid)
this.handlers[guid] = func;
// 通道上的事件处理函数的个数增加1
this.numHandlers++;
// 如果时间
if (this.numHandlers == 1) {
// 订阅第一个事件时调用自定义的处理(比如:第一次按下返回按钮提示“再按一次...”)
this.onHasSubscribersChange && this.onHasSubscribersChange();
}
}
};
/**
* Unsubscribes the function with the given guid from the channel.
*/
// 撤消订阅通道上的某个函数(guid)
Channel.prototype.unsubscribe = function(f) {
// need a function to unsubscribe
// 事件处理函数校验
forceFunction(f);
// 事件处理函数的guid索引
var guid = f.observer_guid,
// 事件处理函数
handler = this.handlers[guid];
if (handler) {
// 从该通道上撤消订阅(索引为guid)
delete this.handlers[guid];
// 通道上的事件处理函数的个数减1
this.numHandlers--;
if (this.numHandlers === 0) {
// 撤消订阅最后一个事件时调用自定义的处理
this.onHasSubscribersChange && this.onHasSubscribersChange();
}
}
};
/**
* Calls all functions subscribed to this channel.
*/
// 调用所有被发布到该通道上的函数
Channel.prototype.fire = function(e) {
var fail = false,
fireArgs = Array.prototype.slice.call(arguments);
// Apply stickiness.
// sticky事件被调用时,标示为已经调用过。
if (this.state == 1) {
this.state = 2;
this.fireArgs = fireArgs;
}
if (this.numHandlers) {
// 把该通道上的所有事件处理函数拿出来放到一个数组中。
var toCall = [];
for (var item in this.handlers) {
toCall.push(this.handlers[item]);
}
// 依次调用通道上的所有事件处理函数
for (var i = 0; i < toCall.length; ++i) {
toCall[i].apply(this, fireArgs);
}
// sticky事件是一次性全部被调用的,调用完成后就清空。
if (this.state == 2 && this.numHandlers) {
this.numHandlers = 0;
this.handlers = {};
this.onHasSubscribersChange && this.onHasSubscribersChange();
}
}
};
// ④创建事件通道(publish部分)-----------------------
// (内部事件通道)页面加载后DOM解析完成
channel.createSticky('onDOMContentLoaded');
// (内部事件通道)Cordova的native准备完成
channel.createSticky('onNativeReady');
// (内部事件通道)所有Cordova的JavaScript对象被创建完成可以开始加载插件
channel.createSticky('onCordovaReady');
// (内部事件通道)所有自动load的插件js已经被加载完成
channel.createSticky('onPluginsReady');
// Cordova全部准备完成
channel.createSticky('onDeviceReady');
// 应用重新返回前台
channel.create('onResume');
// 应用暂停退到后台
channel.create('onPause');
// (内部事件通道)应用被关闭(window.onunload)
channel.createSticky('onDestroy');
// ⑤设置deviceready事件之前必须要完成的事件
// ***onNativeReady和onPluginsReady是平台初期化之前要完成的。
channel.waitForInitialization('onCordovaReady');
channel.waitForInitialization('onDOMContentLoaded');
module.exports = channel;
});
以上是源码,下面说说理解
---1####
,首先定义几个变量,utils, nextGuid, Channel, channel , utils就是前面两篇文章分析的工具模块;nextGuid 就是一个Guid; Channel是一个普通的构造器方法;channel则是最终返回的结果。
注意到下面这一段代码(将所有具体逻辑省略) , 将Channel的定义及其原型的修改放在一起,我们可以看到一个典型的创建对象的方法:通过构造器初始化内部变量,从而让各个实例互相独立,通过修改函数原型共享实例方法。
var Channel = function(type, sticky) {
// 通过构造器初始化内部变量
},
channel = {
// 创建对象函数
Channel.prototype.subscribe = function(f, c) {
// subscribe(向事件通道注入事件处理函数)
};
Channel.prototype.unsubscribe = function(f) {
// 解除事件处理函数,反注入
};
Channel.prototype.fire = function(e) {
// fire(触发所有注入的函数)
};
---2####
subscribe是向通道注入事件处理函数的函数,这个函数,是负责将函数注入事件通道的、通过一个自增长GUID为注入函数的索引。
unsubscribe 是反注入,就是将通过subscribe注入到通道的函数删除,通过guid,找到this. handler中保存的响应函数,并且删除。
fire 调用、触发注入函数, 主要是修改 sticky事件状态,构造调用函数的数组, 并且一次调用所有事件处理函数(利用了apply()函数实例方法调用 )
4. cordova 工具类 (utils)
// file: src/common/utils.js
define("cordova/utils", function(require, exports, module) {
//exports是一个{ }空对象, 赋值给utils
var utils = exports;
/**
* Defines a property getter / setter for obj[key].
*/
utils.defineGetterSetter = function(obj, key, getFunc, opt_setFunc) {
if (Object.defineProperty) {
var desc = {
get: getFunc,
configurable: true
};
if (opt_setFunc) {
desc.set = opt_setFunc;
}
Object.defineProperty(obj, key, desc);
} else {
obj.__defineGetter__(key, getFunc);
if (opt_setFunc) {
obj.__defineSetter__(key, opt_setFunc);
}
}
};
/**
* 通过 obj[key]. 定义一个Getter方法(内部调用utils.defineGetterSetter)
*/
utils.defineGetter = utils.defineGetterSetter;
utils.arrayIndexOf = function(a, item) {
if (a.indexOf) {
return a.indexOf(item);
}
var len = a.length;
for (var i = 0; i < len; ++i) {
if (a[i] == item) {
return i;
}
}
return -1;
};
/**
* 返回该项目是否在数组中。
*/
utils.arrayRemove = function(a, item) {
var index = utils.arrayIndexOf(a, item);
if (index != -1) {
a.splice(index, 1);
}
return index != -1;
};
utils.typeName = function(val) {
return Object.prototype.toString.call(val).slice(8, -1);
};
/**
* 判断一个对象是否为Array类型
*/
utils.isArray = Array.isArray ||
function(a) {return utils.typeName(a) == 'Array';};
/**
* 判断一个对象是否为Date类型
*/
utils.isDate = function(d) {
return (d instanceof Date);
};
/**
* 深度copy一个对象,包括这个对象的事件等
*/
utils.clone = function(obj) {
if(!obj || typeof obj == 'function' || utils.isDate(obj) || typeof obj != 'object') {
return obj;
}
var retVal, i;
if(utils.isArray(obj)){
retVal = [];
for(i = 0; i < obj.length; ++i){
retVal.push(utils.clone(obj[i]));
}
return retVal;
}
retVal = {};
for(i in obj){
if(!(i in retVal) || retVal[i] != obj[i]) {
retVal[i] = utils.clone(obj[i]);
}
}
return retVal;
};
/**
* 对一个函数的包装调用
*/
utils.close = function(context, func, params) {
return function() {
var args = params || arguments;
return func.apply(context, args);
};
};
//------------------------------------------------------------------------------
// 内部私有函数 , UUIDcreatePart函数用来随机产生一个16进制的号码,接受一个表示号码长度的参数(实际上是最终号码长度的一半),一般用途是做为元素的唯一ID;
function UUIDcreatePart(length) {
var uuidpart = "";
for (var i=0; i<length; i++) {
var uuidchar = parseInt((Math.random() * 256), 10).toString(16);
if (uuidchar.length == 1) {
uuidchar = "0" + uuidchar;
}
uuidpart += uuidchar;
}
return uuidpart;
}
/**
* 产生随机字符串 (UUID)
*/
utils.createUUID = function() {
return UUIDcreatePart(4) + '-' +
UUIDcreatePart(2) + '-' +
UUIDcreatePart(2) + '-' +
UUIDcreatePart(2) + '-' +
UUIDcreatePart(6);
};
/**
* 继承子对象
*/
utils.extend = (function() {
// proxy used to establish prototype chain
var F = function() {};
// extend Child from Parent
return function(Child, Parent) {
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.__super__ = Parent.prototype;
Child.prototype.constructor = Child;
};
}());
/**
* 弹出消息,不支持弹出消息时,写日志到控制台
*/
utils.alert = function(msg) {
if (window.alert) {
window.alert(msg);
} else if (console && console.log) {
console.log(msg);
}
};
});
附上JS一些函数的解析
(1)push():接受任意数量的参数,逐个添加到数组末尾,并返回修改后数组长度
(2)pop():移除最后一项,修改数组长度,返回被移除的项
(3)shift():移除数组第一项,修改数组长度,返回被移除的项
(4)unshift():在数组前端添加任意个项,并返回数组长度
(5)slice():基于当前数组的一个或多个项创建一个新数组,可以接受1或2个参数,即要返回项的起始和结束位置,只有一个参数时,返回从该参数指定位置开始到末尾,有两个参数,返回这两个参数之间项(前闭后开区间),slice不会影响原数组。若参数为负数,则用数组长度加上参数直至为正数,若结束位置小于起始位置,返回空数组。
(6)splice():返回从原数组中删除的项构成的数组,若没有删除,返回空数组
删除:可以删除任意数量的项,只需指定2个参数,要删除的第一项的位置和要删除的项数,如splice(0,2)会删除前面两项
插入:可以向指定位置插入任意数量的项,只需提供3个参数,起始位置,0(要删除的数),要插入的项,如果要插入多个项,可以传入第四、第五以至任意多个项
替换:可以向指定位置插入任意数量的项,且同时删除任意数量的项
网友评论