Skip to main content

Registering a listener instance as a subscriber

2 replies [Last post]
xsaissy
Offline
Joined: 2008-01-21
Points: 0

Hello,

I'm trying to define a message listener with jmaki.subscribe, but outside of a widget.
The problem is that in the callback function the "this" keyword uses the Window object instead of my object instance.
Maybe I could register my instance as a widget and retrieve it with its widgetId, but how to pass a class member from the listener scope into the "cb" handling closure ?
(i also tried to define a MessageMonitor.prototype.cb )
My goal is to register several instances of my class so each can listen to a given topic.

Here is the code:

MessageMonitor = function(topic, mmElementId) {

this.mmElement = document.getElementById(mmElementId);

this.cb = function(args) {
jmaki.log(this);
var msgMonitor = this.mmElement;
markup = markup + args.foobar;
msgMonitor.innerHTML = markup;
};

this.sub = jmaki.subscribe(topic, this.cb);
};

Any insight welcome.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
carlavmott
Offline
Joined: 2005-02-10
Points: 0

Hi xsaissy,

Not sure what you are doing so let me give you some info and maybe you can provide more info based on what I say.

If your handler MessageMonitor listens to a topic the widgets publish to already like onSave or onClick then the widget id is published as part of the payload. so you can do the following:

//log all onSave events that occur.
MessageMonitor = function("*/onSave", args) {
var w = document.getElementById(args.widgetId);
jmaki.log(args);
w.innerHTML = args;
}

If you have the widgetid when you publish to the topic then add it to the payload and pick it up in MessageMonitor since that is what you need do what you want. If you don't have the widget id then what info to you have about the widget?

Carla

xsaissy
Offline
Joined: 2008-01-21
Points: 0

You're right, reading the widgetId from the payload is sufficient in most cases as I can get the widget instance and do whatever I need with it.
Dealing with member fields or functions is not compulsory.

The origin of my question was because I tried to adapt a Pagebus example into jMaki. The Pagebus [i]subscribe[/i] function has a [i]scope[/i] parameter that enabled the code above:

[i]"If the value is non-null, the object specified here becomes the context of the callback function. In other words, when the JavaScript this keyword is used in the callback function, it will point to this object.
If the value is null, then the object window is used as the default context of the callback function."[/i]

Thanks Carla for your reply,
Xavier

Message was edited by: xsaissy