-2

I have this code in my client side SignalR JavaScript file:

ticker.client.observationArrived = function (eventData) {
    console.log("Enter observationArrived with %o", eventData.time);
    var observationId = eventData.observationId;

    // Use cascading jquery "done" functions.
    // First get observation
    ticker.server.getObservation(observationId).done(function (observation) {
            console.log("Cascaded from getObservation with %o and %o", eventData.time, observation.ObservationGroupId);

            var observationGroupId = observation.ObservationGroupId;
        // Next get observation group
        ticker.server.getObservationGroup(observationGroupId).done(function(observationGroup) {
            console.log("Cascaded from getObservationGroup");
            // Add data to HTML table
            var newData = {
                time: eventData.time,
                observationId: eventData.observationId,
                observationGroupName: observationGroup.Name
            }
            $observationTableBody.append(rowTemplate.supplant(newData));
        });
    });
}

Now I want go another step further, take "ProductId" from "observationGroup" and invoke "getProduct" to get the product info to add some of that to my HTML table. But each level of access nests deeper and deeper, and without function nesting I can see no way to pass, eg, eventData.observationId to the functions invoked via done. It doesn't give one warm fuzzies.

Is there some other way to handle this, to, say, use some sort of global (but local to this transaction) data that would allow me to break things up more cleanly, and without the threat of infinitely deeper nesting? (I'm aware that I can declare the methods out of line, but they still must be statically nested, from what I can see.)

Or is there a way to pass more than one parameter on a done? I've seen a couple of examples of doing something like (entityA, entityB).done(function theFunction(a,b) {..., but I could not get something like that to work, and can find no documentation about the form.

Or is there some other way to handle this general "cascade" situation, perhaps by using events?

(Realizing this makes this an "opinion" question) What would you consider "best practice" here?

Hot Licks
  • 47,103
  • 17
  • 93
  • 151

1 Answers1

0

IMHO, events would be the way to go here.
If you have multiple nested events - and they are only going to get deeper and more nested, then possibly try Reactive Extensions.

...is a set of libraries to compose asynchronous and event-based programs using observable collections and Array#extras style composition in JavaScript.

There is a JavaScript library version on github https://github.com/Reactive-Extensions/RxJS

blorkfish
  • 21,800
  • 4
  • 33
  • 24
  • I'm trying to keep from pulling in a lot of other extensions just now, but I'll look at using raw events. Do you know of a good online reference? – Hot Licks Apr 15 '14 at 16:01