Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Durandal: I have data in the shell - how do I push it to a viewmodel?

In my shell.js, there's an action that can be called to collect some data from an API endpoint (a list of tickets). Once I have this data, I router.navigateTo("purchase"), which is a valid route.

I need to pass this data into the viewModel now. Is there any standard approach to doing this with DurandalJS, or do I have to look into some kind of pub/sub mechanism?

One solution (that I've implemented for now) is to just use window - in shell.js, once the data service call is complete, I say window.tickets = dataFromService. Then within the "purchase" vm, I work off of window.tickets. This feels dirty and I'm interested in what a proper solution would look like with durandal.

like image 965
SB2055 Avatar asked Dec 12 '25 08:12

SB2055


1 Answers

In Durandal's philosophy not the shell should retrieve the data. Instead the purchase vm should do it in its activate callback (http://durandaljs.com/documentation/Creating-A-Module/). Just make sure to return a promise from activate if ticket collection is an async operation.

Here's an example of that pattern, where getListCollection can either returns a cached result (sync) or an async result and is therefore wrapped in a $.when(), which always returns a promose.

http://www.spirit.de/demos/metro/durandalsp3/index.html#/lists

var activate = function () {
    var self = this;
    var webUrl = L_Menu_BaseUrl;

    self.webUrl(webUrl);

    logger.log('Activatíng List View', null, 'list', true);

    return $.when(spdata.getListCollection({ webUrl: webUrl })).then(function (result) {

        // Access to detail list information through listInfo[listName]
        self.listInfo = result;
        self.lists(createListVMs(result));

        return true;
    });
};

Updated based on comment: If you have to retrieve data in shell to make decisions there are a couple of options.

  • You might consider converting the purchase vm into a widget as in Durandal 1.2 only widgets can have additional data passed in.
  • As an alternative create a global AMD that returns a singleton and is shared between shell and purchase.
  • Third option would be to declare purchase as dependency in shell and modify purchase directly.

See @Joseph Gabriel Pass data in DurandalJS to other view for details.

like image 197
RainerAtSpirit Avatar answered Dec 14 '25 20:12

RainerAtSpirit