组件无法显示数组的内容

时间:2015-02-06 20:19:59

标签: javascript asp.net-mvc knockout.js

我是knockout.js的新手,正在尝试创建一个简单的通知消息组件。发生的事情是绑定似乎发生了,但UI没有发生更新。下面是代码,如果有任何帮助,我将非常感谢您找到它的位置。

请注意:我正在使用ASP.NET MVC 5,Knockout.js 3.2.0,Require.js 2.1.14与AMD一起访问脚本和视图。

查看 - 中心

<div class="row">
    <notification-hub></notification-hub>
</div>
<button type="button">Push Me!</button>
@section scripts {
    <script src="~/Scripts/Views/Home/index.js" type="text/javascript"></script>
}

中心脚本

require(["ko", "jquery", "ViewModels/notificationMessage", "Components/Notifications/hub", "Plugins/jquery.timeago"], function (ko, jquery, notificationMessage, notificationHub) {

try {
    // Register the component.
    ko.components.register("notification-hub", {
        viewModel: notificationHub,
        template: { require: "text!/Components/Notifications/HubItemView" }
    });

    // Create an instance of the hub and add an inital message.
    var hub = new notificationHub();
    hub.addMessage(new notificationMessage("Test", "This is a test message.", "2015-02-06 11:00 AM"));

    // Bind things up.
    ko.applyBindings(hub, $("notification-hub")[0]);

    // Create a handler for the button click.
    $("button").on("click", function () {
        hub.addMessage(new notificationMessage("New Message", "This is a new message", new Date().toLocaleDateString()));
    });
}
catch (e) {
    $("#displayValues").html("Something went wrong...");
    Debug.writeln("Script error: " + e.message);
}

});

ViewModel - Hub

define(["ko", "jquery"], function (ko, jquery) {

// Create the hub's main ViewModel.
function notificationHub() {
    var self = this;

    // Define the Properties.
    self.messages = ko.observableArray();
    self.count = ko.computed(function () { return self.messages().length; });
}

// Define the addMessage method.
notificationHub.prototype.addMessage = function (msg) {
    var self = this;

    // Pop message to the top of the stack.
    self.messages().push(msg);
    Debug.writeln("Count of message array: " + self.messages().length);
}

return notificationHub;

});

查看 - 消息模型

<p data-bind="if: messages().length == 0">Unfortunately we didn't find any records.</p>
<ul data-bind="foreach: messages">
<li class="notificationMessage">
    <span class="timeAgo" data-bind="text: createdDate"></span>
    <h2 data-bind="text: title"></h2>
    <p data-bind="text: message"></p>
</li>
</ul>
<!-- For debugging purposes -->
<input type="text" data-bind="value: count" />

ViewModel - 消息模型

define(["ko"], function (ko) {

// Define the ViewModel for the messages themselves.
return function notificationMessage(title, message, date) {
    var self = this;

    // Define the Properties.
    self.title = title;
    self.message = message;
    self.createdDate = date;
};

});

0 个答案:

没有答案