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?
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;