Scott Scott - 2 months ago 16
jQuery Question

dynamic javascript load and subscribe to event based on data?

I have a javascript client using for messaging. I'm subscribing to a channel like so:

pubnub.subscribe({
channel : chnl,
message : function(m){
var msg = $.parseJSON(m);
processMessage(msg);
}
);


I have a bunch of widgets/components that currently only consist of HTML which are dynamically loaded. Right now,
processMessage()
basically just said "If msg.id = widget1 then do a bunch of stuff". I would like to modify the component files to include javascript that handles all the widget data, and some how register a hook to detect when a
pubnub
message comes in with an ID that matches the widget.

How can I do this?

See this question on programmers.stackexchange.com for more info.

Answer

You could keep a simple callback map and do a lookup when a message comes in.

Something like:

var callbackMap = {};

function registerCallback(id, callback) {
  callbackMap[id] = callback;
}

function processMessage(msg) {
  callbackMap[msg.id](msg.data);
}

In each component, you would register:

registerCallback('widget1', function(data) {
  //do something for widget1 with data
});

And on message:

pubnub.subscribe({
  channel: chnl,
  message: function(m){
    var msg = $.parseJSON(m);
    processMessage(msg);
  }
);