1
votes

I am building a simple durandal application. I have some viewmodels already that load its data from server and they kind of depend on one another. In order to keep them in sync, I want to reload the viewmodel's data as it is navigated to. What comes to my mind is to try using some sort of navigation events. What is the best way to use it?

Say I have this kind of a viewmodel with its view and stuff. How to make it load its data (that is call loadData function) everytime the user navigates to the page?

define(["knockout", "./repository"], function (ko, repository) {
    // Door viewmodel
    var list = ko.observableArray();

    function loadData() {
        // use repository to load the data
        // map the data to list array
    }

    return {
        list: list, 
        loadData: loadData
    }
});

I am mostly following the example application Durandal provides and my router configuration is based on the one the example uses.

define(["knockout", "plugins/router"], function(ko, router) {

    var childRouter = router.createChildRouter()
        .makeRelative({
            moduleId: "vm/catalog",
            fromParent: true
        }).map([
            { route: ["", "door"], moduleId: "door/index", title: "Drzwi", nav: true },
            { route: "doorType", moduleId: "doorType/index", title: "Typy drzwi", nav: true },
            { route: "accessory", moduleId: "accessory/index", title: "Akcesoria", nav: true }
        ])
        .buildNavigationModel();

    return {
        router: childRouter
    }
});

Is there a way to call the function from within the router when it navigates to the page or somehow pass an object to the module itself to manage the event? In other words, what is the way the navigation router (lifecycle) events are implemented in Durandal?

1

1 Answers

4
votes

You need to read through the docs, all of the answers you are looking for are there.

Composition Lifecycle getView, activate, binding, bindingComplete, attached, compositionComplete, detached

http://durandaljs.com/documentation/Using-Composition

Put your datacalls in your activate method -

define(["knockout", "./repository"], function (ko, repository) {
    // Door viewmodel
    var list = ko.observableArray();

    function loadData() {
        // use repository to load the data
        // map the data to list array
    }

    function activate () {
        loadData();
    }

    return {
        list: list,
        activate: activate, 
        loadData: loadData
    }
});