我试图使我的代码尽可能模块化,并模仿WPF和Caliburn.Micro的模式。这是我到目前为止使用Knockout组件尝试的内容。
组件ViewModel
function welcomeViewModel() {
this.greeting = 'Hello world!;
}
App ViewModel
function appViewModel() {
this.firstGreetingVM = new welcomeViewModel();
this.secondGreetingVM = new welcomeViewModel();
}
应用视图
<WelcomeWidget data-bind-to="firstGreetingVM"/>
<WelcomeWidget data-bind-to="secondGreetingVM"/>
如何在视图中定义上下文(要使用的视图模型)?
答案 0 :(得分:3)
You can use any view model you want for a component if you register it appropriately. This approach will let you either pass your component a viewModel
in the params or have it create a new view model using your params.
ko.components.register('WelcomeWidget', {
template: ...
viewModel: function (params = {}) {
return params.viewModel || new WelcomeWidgetViewModel(params);
},
});
AppViewModel
function AppViewModel() {
this.firstGreetingVM = new WelcomeWidgetViewModel({greeting: 'first greeting'});
this.secondGreetingVM = new WelcomeWidgetViewModel({greeting: 'second greeting', someOtherProperty: 'howdy'});
}
AppViewModel.html
<WelcomeWidget params="viewModel: firstGreetingVM"></WelcomeWidget>
<WelcomeWidget params="viewModel: secondGreetingVM"></WelcomeWidget>
<WelcomeWidget params="greeting: 'third greeting', someOtherProperty: 'blah'"></WelcomeWidget>
WelcomeWidgetViewModel
function WelcomeWidgetViewModel(options = {}) {
this.greeting = options.greeting;
this.someOtherProperty = options.someOtherProperty;
}