3

Here is my markup:

<section id="Application">
    <!-- ko ifnot: initialized -->
    <span>Loading...</span>
    <!-- /ko -->
    <ul data-bind="template:{name: 'clientList', foreach:clients}">
    </ul>

    <ul data-bind="template:{name: 'storyList', foreach:stories}">
    </ul>
</section>

Here is my templates (they are in separate files):

function IncompleteStoriesViewModel() {
//data
var self = this;
self.initialized = ko.observable(false);
self.stories = ko.observableArray();
(function () {
    $.ajax({
        url: lucidServer.getIncompleteStory(1),
        success: function (data) {
            ko.mapping.fromJS(data, {}, self.stories);
            self.initialized(true);
        }
    });
})();
};

ko.applyBindings(new IncompleteStoriesViewModel());


function ClientViewModel() {
//data
var self = this;
self.initialized = ko.observable(false);
self.clients = ko.observableArray();
(function () {
    $.ajax({
        url: lucidServer.getClients(1),
        success: function (data) {
            ko.mapping.fromJS(data, {}, self.clients);
            self.initialized(true);
        }
    });
})();
};

ko.applyBindings(new ClientViewModel());

My template files are fine, if I call one or the other in the html, they each work individually, but when I try to get them both to show up, only the first one renders, and the second one throws an error that 'stories is not defined' or 'clients is not defined'

I am sure I need to execute this differently, I just can't figure out how. My goal is to have up to 10-15 viewmodels rendering different templates on the same page.

4

2 回答 2

4

您必须创建一个包含所有视图模型的视图模型:

function ViewModel(){
    var self = this;

    self.clientViewModel = new ClientViewModel();
    self.storyViewModel = new IncompleteStoriesViewModel();
}

然后将绑定应用到整个页面:

ko.applyBindings(new ViewModel());

并相应地调整html:

<section id="Application">
    <ul data-bind="template:{name: 'clientList', foreach: clientViewModel.clients}">
    </ul>

    <ul data-bind="template:{name: 'storyList', foreach:storyViewModel.stories}">
    </ul>
</section>
于 2012-10-30T19:36:21.857 回答
3

Artem 的答案可能是更好的方法,但您确实有另一种选择。您可以调用applyBindings并使用第二个参数来指定要定位的元素。

ko.applyBindings(viewModelA, document.getElementById("one"));
ko.applyBindings(viewModelB, document.getElementById("two"));

这将允许在页面上绑定多个视图模型。

于 2012-10-30T19:48:46.840 回答