我正在阅读书中的第5.5章.我仍然难以看到"我们可以使用章节中的可能性函数来组合各组件中的对象".
对象是由具有"on"和"fire"功能的事件系统组成的吗?
以下部分的代码:
var eventuality = function (that) {
var registry = {};
that.fire = function (event) {
// Fire an event on an object. The event can be either
// a string containing the name of the event or an
// object containing a type property containing the
// name of the event. Handlers registered by the 'on'
// method that match the event name will be invoked.
var array,
func,
handler,
i,
type = typeof event === 'string' ?
event : event.type;
// If an array of handlers exist for this event, then
// loop through it and execute the handlers in order.
if (registry.hasOwnProperty(type)) {
array = registry[type];
for (i = 0; i < array.length; i += 1) {
handler = array[i];
// A handler record contains a method and an optional
// array of parameters. If the method is a name, look
// up the function.
func = handler.method;
if (typeof func === 'string') {
func = this[func];
}
// Invoke a handler. If the record contained
// parameters, then pass them. Otherwise, pass the
// event object.
func.apply(this,
handler.parameters || [event]);
}
}
return this;
};
that.on = function (type, method, parameters) {
// Register an event. Make a handler record. Put it
// in a handler array, making one if it doesn't yet
// exist for this type.
var handler = {
method: method,
parameters: parameters
};
if (registry.hasOwnProperty(type)) {
registry[type].push(handler);
} else {
registry[type] = [handler];
}
return this;
};
return that;
}
Run Code Online (Sandbox Code Playgroud)
克罗克福德什么意思先生在这里是可以实现特定功能,如on
并fire
通过调用创建它们(函数对象事件处理添加到任何物体的功能eventuality
与对象作为参数,在这种情况下).
这里的"部分"是体现在eventuality
功能对象中的"事件处理部分" .您可以想象添加其他功能的不同部分.这里的想法是您可以使用此系统将此功能添加到您需要的单个对象.这个概念称为Mixin(1).
另请阅读第5章的最后一段:
通过这种方式,构造函数可以从一组零件组装对象.JavaScript的松散输入在这里是一个很大的好处,因为我们不会担心关注类的谱系的类型系统.
(1)谢谢Zecc.
归档时间: |
|
查看次数: |
1496 次 |
最近记录: |