具有基于视图的数据绑定上下文的模块化 Web 组件
Modular Web Components with View-Based Data-Binding context
我正在尝试使我的代码尽可能模块化并模仿 WPF 和 Caliburn.Micro 的模式。这是我到目前为止使用 Knockout 组件尝试过的内容。
组件视图模型
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"/>
如何在视图本身中定义上下文(使用什么视图模型)?
如果您适当地注册了一个组件,您可以使用任何您想要的视图模型。这种方法可以让你在参数中传递你的组件 viewModel
或者让它使用你的参数创建一个新的视图模型。
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;
}
我正在尝试使我的代码尽可能模块化并模仿 WPF 和 Caliburn.Micro 的模式。这是我到目前为止使用 Knockout 组件尝试过的内容。
组件视图模型
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"/>
如何在视图本身中定义上下文(使用什么视图模型)?
如果您适当地注册了一个组件,您可以使用任何您想要的视图模型。这种方法可以让你在参数中传递你的组件 viewModel
或者让它使用你的参数创建一个新的视图模型。
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;
}