具有基于视图的数据绑定上下文的模块化Web组件

时间:2015-06-15 13:56:30

标签: javascript html knockout.js data-binding

我试图使我的代码尽可能模块化,并模仿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"/>

如何在视图中定义上下文(要使用的视图模型)

1 个答案:

答案 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;
}