【问题标题】:knockoutjs components params undefined淘汰赛组件参数未定义
【发布时间】:2015-12-21 21:29:15
【问题描述】:

我正在创建一个 Knockout js 组件以在我的通知系统中使用。当我将组件添加到页面时,我收到 params is undefined 消息,看起来我的 params 对象没有发送到 viewmodel 的构造函数。

一开始我以为我的组件加载器有问题,所以我手动注册了组件,如下所示:

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

该组件由一个名为 info.js 的 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 将成为可观察的。

谁能告诉我我在这里做错了什么,我认为这与我注册组件的方式有关。

【问题讨论】:

  • afaik 你应该返回视图模型的构造函数,所以不要使用return InfoNotificationViewModel(); 使用return InfoNotificationViewModel;(不带括号)
  • 是的,感谢@Dominik,它可以在没有 () 的情况下工作。浪费了 2 个小时。
  • 我将其添加为答案,以便可以正确关闭问题

标签: knockout.js requirejs knockout-components


【解决方案1】:

你应该返回视图模型的构造函数,而不是

return InfoNotificationViewModel();

使用

return InfoNotificationViewModel;(不带括号)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2016-08-13
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多