0

So I've created a scroller control that I want to use in two different places within the same viewmodel for example:-

define(['common/viewmodels/controls/scroller-nav', 'common/viewmodels/controls/scroller-nav'],
     function(mainScrollNav, modalScrollNav))

        vm = {
            activate: activate,
            mainScrollControl: ko.observable(null),
            modalScrollControl : ko.observable(null)
        }

        return vm;

        function activate() {
            vm.mainScrollControl({ model: mainScrollNav, view: 'common/views/controls/mainScroll' });
            vm.modalScrollControl({ model: modalScrollNav, view: 'common/views/controls/modalScroll' });

            // load up the data that is to be used for each (should be independent)
            mainScrollNav.init();   
            modalScrollNav.init();
        }
    }
}

The control loads fine on both instances where mainScrollControl and modalScrollControl is populated however, the data is being shared (modify the scroller position in the modal and its also modified on the main page) even though the controls are defined separately. It seems like mainScrollNav and modalScrollNav link to a single service viewmodel as opposed to being independent viewmodels. Am I going about this right way or should I be using something else?

Scott Alexander
  • 455
  • 2
  • 17
  • 1
    The define function does not instantiate your objects it simply downloads the source files necessary, so repeating the same path again will not have any effect. The answer depends on the code in your scroller-nav and what it returns, but you probably want to invoke that instead of setting it directly as the model. "{ model: mainScrollNav(), ..." – Jason Spake Jul 25 '16 at 16:45
  • Completely forgot to post the solution but yes spot on. – Scott Alexander Aug 01 '16 at 15:04

1 Answers1

0

The solution was not to create a viewmodel, but a function of the view model so...

var control = function(){
     vm = {
         // Vars and functions
     }
     return vm;
}

return control;

Then the viewmodel can be resused as many times as needed just by calling the passed reference in the define paramaters. They both work independently as well.

 define(['common/viewmodels/controls/scroller-nav'],function(scrollNav)){

 vm = {
     mainScroller: new scrollNav(),
     subPageScroller: new scrollNav()
 }

return vm;
Scott Alexander
  • 455
  • 2
  • 17