在不使用全局变量的情况下重用knockout.js的viewModel

Reusing a knockout.js viewModel without using global variables

本文关键字:knockout js viewModel 情况下 全局变量      更新时间:2023-09-26

我有一个不同的knockout生成内容的页面。我有一个右菜单的数据,应该加载新的数据在页面的中间,这取决于在右菜单中选择的行。

我可以获取页面中间的内容。它从后端加载并显示当前内容。但是,当我在右侧面板中选择一个项目时……我想为页面的中间重新获取数据并更新页面。然而,对我来说,这是一个停止点。由于内容的获取是在名称空间中完成的,并且不允许使用全局变量,因此我无法重用当前的viewModel(或者,至少我不知道如何重用)。因此,我正在创建一个新的viewModel,我不能对其应用绑定,因为在加载页面时,这些绑定已经应用于相同类型的viewModel。

这是我的JS代码:
Function.registerNamespace('Domain.Discussion');
$(document).ready(function () {
    var repliesViewModel = Domain.Discussion.RepliesView.ReplyPage;
    ko.applyBindings(repliesViewModel, document.getElementById('discussion'));
});
Domain.Discussion.RepliesView = Domain.Discussion.RepliesView || {
    ReplyPage: (function () {
        function Reply(data) {
            var self = this;
            self.ParentItemId = data.ParentItemID;
            self.Body = data.Body;
            self.Created = data.Created;
        }
        var onGetRepliesSuccess = function (replies) {
            var buffer;
            buffer = $.map(replies.RepliesResult, function (item) { return new Reply(item); });
            viewModelReplies.replies(buffer);
        };
        var onGetRepliesError = function (sender, args) {
            alert(args.message);
        };
        var viewModelReplies = {
            replies: ko.observableArray([]),
            loadReplies: function (parentItemId, listId) {
                if (parentItemId !== null && listId !== null) {
                    console.log("ParentItemId: " + parentItemId + " -- ListId: " + listId);
                    alert("Domain.Discussion.RepliesView");
                    $.ajax({
                        url: absolutePath + "api/Replies/" + listId + "/" + parentItemId,
                        headers: { "Accept": "application/json; odata=verbose" },
                        success: onGetRepliesSuccess,
                        error: onGetRepliesError
                    })
                }
            },
        };
        viewModelReplies.loadReplies(1, '6a5ed4ad-5a7c-428f-947e-b8aa2de54489');
        return viewModelReplies;
    }())
};
// The method loaded by the row-click in the right panel.
Domain.Discussion.LoadDiscussionReplies2 = function (discussionListId, currentItem) {
    try {
        if (currentItem.ListId !== "" && currentItem.Id !== "") {
            // Call the current viewModel and tell it to loadReplies
            // This doesn't work since global variables are, of course, not allowed
            repliesViewModel.loadReplies(currentItem.Id, currentItem.ListId);
        }
    }
    catch (e) {
        alert(e);
    }
}
这是我的HTML代码:
<!-- page discussion -->
<div data-role="page" id="discussion">
    <!-- Content -->
    <div data-role="content">
        <!-- ladda replies -->
        <div id="replies">
            <!-- ko foreach: replies -->
            <div class="message message-first">
                <div class="message-header">
                    <div class="message-header-user">
                        <h1>Persons Name</h1>
                        <h2>Subtitle</h2>
                    </div>
                    <div class="message-header-date" data-bind="text: Created"></div>
                </div>
                <div class="message-content">
                    <span data-bind="text: Body"></span>
                    <hr />
                </div>
            </div>
            <!-- /ko -->
        </div>
    </div>
    <!-- panel -->
    <!-- Grupper -->
    <div id="nav-panel-discussion-groups" data-role="panel" data-theme="a" data-position="right" data-display="overlay">
                <!-- ko foreach: discussions -->
                <ul class="nav-search" data-role="listview" data-theme="a" data-iconpos="left" data-inset="true">
                    <li data-role="list-divider" data-swatch="a" data-theme="a" data-form="ui-bar-a">
                        <div data-type='horizontal'>
                            <label data-bind="text: Title"></label>
                            <a data-bind="attr: { eventId: Id }"  eventId="" name='newThread' data-role="button" data-icon='plus' data-inline="true" data-mini="true" data-theme="a" data-iconpos='notext' id="A4">New</a>
                        </div>
                    </li> 
                    <!-- ko foreach: Threads -->
                    <li data-mini="true" data-icon="false" data-bind="">
                        <a href="#discussion" data-bind="text: Title, click: Domain.Discussion.LoadDiscussionReplies2.bind($root.Id, Id)" data-transition="slide"></a>
                    </li>
                    <!--  /ko -->
                </ul>
                <!-- /ko -->
    </div>
    <!-- /panel -->
</div>

我的问题是:我如何重新获取数据和重用viewModel一旦启动页面加载。我现在完全卡住了

在我当前的项目中有类似的需求。我们在同一个页面上有几个视图模型,一个视图模型中的操作可能会影响另一个(或多个)视图模型中的状态。我们通过使用所有视图模型共享的EventEmitter总线解决了这个问题。当其中一个视图模型获得一些新数据时,它会把它作为事件发送给侦听这个事件的其他视图模型。像这样:

// Data fetched
eventBus.emit('mynamespace:data', [data]);

在另一个视图模型中:

// Respond to data
eventBus.on('mynamespace:data', function(data) {
    // Process data and update viewmodel state
}

所以唯一的共同点是事件总线。他们对彼此一无所知。