2

I have ViewModels that are implemented using the Revealing Module Pattern. I am using global knockout subscribable to achieve decoupled passing of data between these. What i am doing now is, creating an instance of a ViewModel in a master-ViewModel:

NameSpace.MasterViewModel = function(){
    var viewModel = new viewModel(),
        initSubscription = function(){
            viewModel.initSubscription();
        };

    return {
        initSubscription: initSubscription
    }
}

And initializes a subscription in ViewModel like this:

NameSpace.ViewModel = function(){
    var data,
        initSubscription = function(){
            ko.postbox.subscribe( "New Data"function(newData){
                this.data = newData;
            }, this);
        };

    return {
        data: data,
        initSubscription: initSubscription
    }
}

This works, but I want to know if there is a way to initialize the subscription at creation of ViewModel? So that I can avoid a public initialization function.

robbannn
  • 5,001
  • 1
  • 32
  • 47
  • Can't you just execute `initSubscription` when the `ViewModel` constructor function is executed? – Jeroen Mar 20 '16 at 09:20

1 Answers1

0

is there a way to initialize the subscription at creation of ViewModel?

Why sure. Just subscribe between declaration of your revealed module and returning it:

NameSpace.ViewModel = function(){
    var data;
    var self = this;
    var initSubscription = function(){
            NameSpace.Postbox.subscribe(function(newData){
                self.data = newData;
            }, this, "New Data");
        };

    initSubscription(); // <-- does exactly what you ask

    return {
        data: data,
        initSubscription: initSubscription  // <-- might be superfluous now
    }
}
Jeroen
  • 60,696
  • 40
  • 206
  • 339
  • I tried it, but it didn't work. Because `this`, when calling the subscribe function, doesn't refer to the ViewModel. By the way, I'm using the postbox extension now, same result though. I will edit my post. – robbannn Mar 22 '16 at 12:47
  • I've adjusted my answer for the `this` problem using the `var self = this;` idiom. – Jeroen Mar 22 '16 at 12:55