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.
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.
global AMD that returns a singleton and is shared between
shell and purchase. See @Joseph Gabriel Pass data in DurandalJS to other view for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With