2015-09-24 32 views
0

我正在創建一個Knockout js組件用於我的通知系統。當我添加一個組件到頁面時,我得到一個參數是未定義的消息,它看起來像我的params對象不發送給viewmodel的構造函數。knockoutjs組件params undefined

起初我還以爲我的組件裝載機是問題,所以我手動註冊的組件,像這樣:

ko.components.register('notification-info', { 
    viewModel: { require: "/notifications/info" }, 
    template: { require: "text!/notifications/info.tmpl.html"} 
}); 

該組件包括一個js文件名爲info.js

define(['knockout'], function (ko) { 

function InfoNotificationViewModel(params) { 
    this.type = params.type; 
    this.subject = params.subject; 
    this.title = params.title; 
    this.content = params.content; 
} 

return InfoNotificationViewModel(); 
}); 

和一個名爲info.tmpl.html的html模板

<div class="notification-container" data-bind="css: type"> 
<div class="notification-icon"><span class="glyphicon"></span></div> 
<div class="notification-content"> 
    <div class="notification-subject" data-bind="text: subject"> 
    </div> 
    <div class="notification-message"> 
     <p data-bind="text: title"></p> 
     <p data-bind="text: content"></p> 
    </div> 
</div> 

我的組件添加到我的網頁使用組件綁定:

<div data-bind="component: {name: 'notification-info', params: {type: 'info', subject: '',title: '', content: ''} }"></div> 

後來與數據傳送過來的WebSockets所以PARAMS將成爲觀察到的,這將填補。

有人可以告訴我我在做什麼錯在這裏,我認爲這與我註冊組件的方式有關。

+1

據我所知,你應該返回的構造函數視圖模型,所以而不是'返回InfoNotificationViewModel();'使用'返回InfoNotificationViewModel;'(沒有括號) – Domysee

+0

是的,謝謝@Dominik它沒有工作()。浪費了2個小時。 –

+0

我將它添加爲答案,以便問題可以正確關閉 – Domysee

回答

1

你應該返回的構造函數視圖模型,所以不是

return InfoNotificationViewModel();

使用

return InfoNotificationViewModel;(不含括號)