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?

4

1 回答 1

0

解决方案不是创建视图模型,而是创建视图模型的功能,所以......

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

return control;

然后,只需在定义参数中调用传递的引用,就可以根据需要多次重用视图模型。他们也都独立工作。

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

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

return vm;
于 2016-08-01T15:11:10.763 回答