2012-05-02 5 views
3

それは私の質問は、サンプルコードの詳細であるダグラス・クロックフォードの「Javascriptを:良い部品」の章5.5

このquestionにかなり似ています。

コード:コード内

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; 
} 

、私はこの行、func = handler.method;を理解していません。

これはどのように機能しますか?私は、handler.methodは未定義でなければならない、という意味ですか?

array = registry[type]; 
    for (i = 0; i < array.length; i += 1) { 
     handler = array[i]; 

これはthat.on方法で添加した:

おかげ

+1

handlerオブジェクトのmethodプロパティを参照しています、 'method'は' var handler = {method:method、parameters:parameters}; 'の中で' undefined 'ですが、必ずしもそうする必要はありません。どのようにして誰かがハンドラを提供せずに 'something.on( 'event')という呼び出しをすると、それはこの人のせいです。これはこの機能の全目的に反する。 –

答えて

1

handlerregistryに格納されたオブジェクトである

var handler = { 
     method: method, 
     parameters: parameters 
    }; 
    if (registry.hasOwnProperty(type)) { 
     registry[type].push(handler); 
    } else { 
     registry[type] = [handler]; 
    } 

、それは明らかにmethod性質を有しています。

2

handler.methodは(もちろん、それがパラメータとして渡さなければならない)、ここで定義されています

that.on = function (type, method, parameters) { 
    var handler = { 
     method: method, // defines the method property of the handler object 
     parameters: parameters // defines the parameters property of the handler object 
    }; 

Have a read of Working with Objects on the MDNから.methodは、それがあれば可能

関連する問題