How to carry the data from one viewModel to another ViewModel Knockout JS

前端 未结 2 1604
感动是毒
感动是毒 2020-12-21 21:14

I am using the Knockout js in my single page Application,I need to carry the value of one viewmodel data to another viewModel data,So i can reduce my duplication creating sa

相关标签:
2条回答
  • 2020-12-21 21:59

    You could try to gather ur instanced view models in an object, then run applybindings on this object. You would have to rescope the stuff u already have binded. But with this you should be able to cross reference between the models by accessing for instance vm.EmployeeViewModel.SomeFunction()

    var vm = {};
    vm.EmployeeViewModel = new EmployeeViewModel();
    vm.DepartmentViewModel = new DepartmentViewModel();
    ko.applyBindings(vm);
    
    0 讨论(0)
  • 2020-12-21 22:06

    This is what components are for. Have an Employee component with its own ViewModel, a Department component with its own ViewModel, and an application ViewModel that coordinates them. In general, best practice is to applyBindings once for the entire application, and let Knockout do all control of the DOM.

    The way you're doing things suggests that you start with HTML that has multiple employees and departments in it, which is to say, your data is embedded in your HTML and you're expecting Knockout to extract it from there. That is not good practice. Your ViewModel should have the employee data in it and the View should reflect what is in the ViewModel.

    0 讨论(0)
提交回复
热议问题