2015-06-15 53 views
2

我試圖讓我的代碼儘可能模塊化,並模仿WPF和Caliburn.Micro的模式。以下是我迄今爲止使用Knockout組件嘗試過的內容。模塊化Web組件與基於視圖的數據綁定上下文

組件視圖模型

function welcomeViewModel() { 
    this.greeting = 'Hello world!; 
} 

應用視圖模型

function appViewModel() { 
    this.firstGreetingVM = new welcomeViewModel(); 
    this.secondGreetingVM = new welcomeViewModel(); 
} 

應用查看

<WelcomeWidget data-bind-to="firstGreetingVM"/> 
<WelcomeWidget data-bind-to="secondGreetingVM"/> 

如何我可以在視圖本身中定義上下文(使用什麼視圖模型)

+0

http://knockoutjs.com/documentation/component-custom-elements.html –

回答

3

如果您正確註冊組件,則可以使用組件所需的任何視圖模型。這種方法可以讓你通過參數傳遞你的組件viewModel,或者讓它使用你的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; 
} 
+0

謝謝,沒有意識到你可以做到這一點。下一個問題是通知它現在附加到視圖的視圖模型。 :D –

+0

我遵循一個受許多MVVM框架啓發的模式。每個視圖模型_can_實現一個'onPresented'函數,我會在適當時調用它。 *什麼時候在網絡應用程序中顯示某些內容非常依賴於上下文。通常父組件負責在其子組件上調用onPresented。 – CrimsonChris

+0

找到這個片段。 http://jsfiddle.net/gLcfxkv6/1/。第二個問題是在附加視圖時讓Snap進行繪製。所以我想我可以使用這個片段。 –

相關問題