Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js will not bind two templates and viewmodels to the same page

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.

like image 924
ledgeJumper Avatar asked Nov 22 '25 01:11

ledgeJumper


1 Answers

You have to create a view model which will contains all your view models:

function ViewModel(){
    var self = this;

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

Then apply bindings to the entire page:

ko.applyBindings(new ViewModel());

And adjust html accordingly:

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

    <ul data-bind="template:{name: 'storyList', foreach:storyViewModel.stories}">
    </ul>
</section>
like image 187
Artem Vyshniakov Avatar answered Nov 23 '25 16:11

Artem Vyshniakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!