Strange behavior with SignalR JavaScript hub proxy subscribe/event handling

211 Views Asked by At

I have a server-side hub called EventHub with pub/sub (groups) and I'm trying to subscribe the JS client to messages emitted from it. The messages and pub/sub work fine. If I do everything manually in the console it all works as expected. But I'm seeing weird behavior that I can't figure out... It seems like a variable reference issue but I've tried dozens of things and nothing has fixed it.

var mystore = {
    EventHub: null,
    Foo: { Bar: { Active: true }, Baz: { Active: true } },

    SetEventHub: function(hub) {
        this.EventHub = hub;
        for (var t in this.Foo) if (this.Foo.hasOwnProperty(t) && this.Foo[t].Active) {
            console.log('t',t);
            var eventName = t.toLowerCase();
            hub.server.subscribe(eventName).done(function(){
                console.log('eventName',eventName);
            });
        }
    }
};

$(document).ready(function () {
    $.connection.hub.start().done(function() {
        mystore.SetEventHub($.connection.eventHub);
    });
});

This will output in the console:

t Bar
t Baz
(2) eventName baz

I would expect it to output:

t Bar
t Baz
eventName bar
eventName baz

Maybe not that order, but separate bar/baz lines not two bar lines. Using $.connection instead of hub doesn't help; various things like var x = t+''; (thinking a weird obj ref issue) don't help. For some reason only the last "eventName" callback seems to be getting registered and is overwriting the previous ones. However if I do multiple callbacks manually, they all register and all fire as expected... It seems like a race condition or scoping issue or something like that. I've spent hours on this and haven't gotten anywhere. :(

Update: Using var f = function(){console.log('eventName',eventName);} doesn't help either.

1

There are 1 best solutions below

0
On

I agree with you this should be a client side scoping issue. Did you try something along these lines (not tested)?

var eventName = t.toLowerCase();
(function(en) {
    hub.server.subscribe(en).done(function(){
        console.log('eventName', en);
    });
})(eventName);

If it works it could then be improved, but it should at least prove what kind of problem you have.