durandaldurandal-2.0durandal-navigation

durandal, pass parameters to widget during navigation


i have several singleton views in my SPA, each of these view contain the same widget.

When the view is activated i take some parameters from the activate callback and pass it to the widget and it works fine.

But if i navigate the second time into the view (with different parameters into the activate callback) the activate method of the widgets is rightly not raised.

How can i pass the fresh data to the widgets ?

I tried to make the parameter observable and subscribe it into the widget (settings.params.subscribe) and it works, but i don't think it's a good solution.


Solution

  • This should be pretty simple assuming you are returning a constructor from your widget -

    View model -

    var thisWidget = new widget(someArbitraryData)
    
    function createWidget() {
        dialog.show(thisWidget);
    }
    
    // later
    function updateWidget() {
        thisWidget.refreshData(newArbitraryData);
    }
    

    Widget module -

    define([], function () {
        var ctor = function () {
            var self = this;
            self.data = ko.observable();
        };
        ctor.prototype.refreshData = function (newData) {
            var self = this;
            self.data(newData);
        };
        ctor.prototype.activate = function (activationData) {
            var self = this;
            self.data(activationData);
        };
    });