Scott Scott - 1 year ago 92
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:

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

I have a bunch of widgets/components that currently only consist of HTML which are dynamically loaded. Right now,
basically just said "If = 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
message comes in with an ID that matches the widget.

How can I do this?

See this question on for more info.

Answer Source

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) {

In each component, you would register:

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

And on message:

  channel: chnl,
  message: function(m){
    var msg = $.parseJSON(m);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download