0

このパターンがどのように機能するかを完全に理解できるように、JavaScript で単純な pub/sub を実装しています。

//obj to hold references to all subscribers
pubSubCache = {};

//subscribe function - push the topic and function in to pubSubCache
subscribe = function (topic, fn) {
    pubSubCache[topic] = fn;
};

//publish function
publish = function (topic, obj) {
    var func;
    console.log(obj);
    console.log(pubSubCache);
    // If topic is found in the cache
    if (pubSubCache.hasOwnProperty(topic)) {
        //Loop over the properties of the pubsub obj - the properties are functions
        //for each of the funcitons subscribed to the topic - call that function and feed it the obj           
        for (func in pubSubCache[topic]) {
            //this console.log returns a long list of functions - overloadsetter,overloadgetter,extend etc
            //I expected to see the 'therapist' function here...
            console.log(func);
            //error occurs here - it should be calling the therapist function
            pubSubCache[topic][func](obj);
        }
    }
}; 


function therapist (data) {
    alert(data.response);
}

subscribe('patient/unhappy', therapist);
publish('patient/unhappy',{response:'Let me prescribe you some pills'})

</p>

私はほとんどそこにいますが、コードに奇妙な問題があるようです。パブリッシャー関数は、サブスクライバーへのすべての参照を保持するオブジェクトを検索し、一致するものを見つけます。次に、サブスクライブされている関数への参照を取得するために for in ループを実行しようとすると、必要な関数ではなく、この関数の長いリストが返されます。

overloadSetter overloadGetter 拡張 実装 非表示 保護 $family $constructor

私は当初、これらの関数は関数のプロトタイプからのものだと思っていましたが、そうではありません。

何か案は?これが理にかなっていることを願っています。

4

2 に答える 2

1

サブスクライブでは、トピックへの複数のサブスクリプションを許可する必要があります。したがって、各トピックのキャッシュエントリには配列が必要です。

 //subscribe function - push the topic and function in to pubSubCache
subscribe = function (topic, fn) { // if new topic init to empty array
    if (!pubSubCache.hasOwnProperty (topic)) 
      pubSubCache[topic] = [];   
    pubSubCache[topic].push (fn);
};

公開では、トピックキャッシュ内の各関数を呼び出す必要があります。

//publish function
publish = function (topic, obj) {
  if (pubSubCache.hasOwnProperty (topic)) {
    for (var f = pubSubCache[topic].length; f--;) {
      pubSubCache[topic][f](obj);
    }
  }
}; 

フィドルを参照してください:http://jsfiddle.net/cRTRL/1/

于 2012-12-05T14:20:50.393 に答える
0

ああ、これはニシンだったようです。返された関数は、mootools を選択して jsfiddle を使用してテストした結果のものでした。私が見ていた機能はそこからのものでした。

残念ながら、私のコードは修正されていません... for inループにはまったく入っていません。

于 2012-12-05T12:59:04.593 に答える