[转帖]Mootools源码分析-42 -- Group
原帖地址:http://space.flash8.net/space/?uid-18713-action-viewspace-itemid-409097
原作者:我佛山人
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
//监听群组事件的类
var Group = new Class({
//构造函数
initialize: function() {
//使用Array.flatten降维参数
this.instances = Array.flatten(arguments);
//事件集
this.events = {};
//事件检查器
this.checker = {};
},
//为群组添加某类事件
addEvent: function(type, fn) {
//使用||设默认值
this.checker[type] = this.checker[type] || {};
//使用||设默认值
this.events[type] = this.events[type] || [];
//如果已添加事件,返回false
if (this.events[type].contains(fn)) return false;
//否则添加到队列
else this.events[type].push(fn);
//为群组中的每一项添加该类型事件,指向this.check
this.instances.each(function(instance, i) {
//要求群组中的项必须支持addEvent方法
instance.addEvent(type, this.check.bind(this, [type, instance, i]));
}, this);
return this;
},
//约束检查
check: function(type, instance, i) {
//标识,确保群组中的每项都添加了该类事件的监听
this.checker[type][i] = true;
//检查标识一致性
var every = this.instances.every(function(current, j) {
return this.checker[type][j] || false;
}, this);
//如果全部未标识为true,退出
if (!every) return;
//重置
this.checker[type] = {};
//触发本类事件
this.events[type].each(function(event) {
event.call(this, this.instances, instance);
}, this);
}
});
var Group = new Class({
//构造函数
initialize: function() {
//使用Array.flatten降维参数
this.instances = Array.flatten(arguments);
//事件集
this.events = {};
//事件检查器
this.checker = {};
},
//为群组添加某类事件
addEvent: function(type, fn) {
//使用||设默认值
this.checker[type] = this.checker[type] || {};
//使用||设默认值
this.events[type] = this.events[type] || [];
//如果已添加事件,返回false
if (this.events[type].contains(fn)) return false;
//否则添加到队列
else this.events[type].push(fn);
//为群组中的每一项添加该类型事件,指向this.check
this.instances.each(function(instance, i) {
//要求群组中的项必须支持addEvent方法
instance.addEvent(type, this.check.bind(this, [type, instance, i]));
}, this);
return this;
},
//约束检查
check: function(type, instance, i) {
//标识,确保群组中的每项都添加了该类事件的监听
this.checker[type][i] = true;
//检查标识一致性
var every = this.instances.every(function(current, j) {
return this.checker[type][j] || false;
}, this);
//如果全部未标识为true,退出
if (!every) return;
//重置
this.checker[type] = {};
//触发本类事件
this.events[type].each(function(event) {
event.call(this, this.instances, instance);
}, this);
}
});