Jay
Jay

Reputation: 1033

Knockout nested objects bindings not working (objects undefined)

So I have four models:

And I have them set up like so:

       Lobby: function(Messages, Campaigns) {
            var self = this;
            self.chat = new Messages();
            self.campaigns = new Campaigns();
        },
        Campaigns: function() {
            var self = this;
            self.campaigns = ko.observableArray();
        },
        Messages: function() {
            var self = this;
            self.message = ko.observable("");
            self.messages = ko.observableArray();
        },
        Campaign: function(campaign) {
            var self = this;
            var status = ["In Lobby", "In Game", "Finished"];
            self.Id = ko.observable(campaign.Id);
            self.url = ko.observable("/matchmaking/" + campaign.Id);
            self.mapName = ko.observable(campaign.Map);
            self.mapImage = ko.observable("/Images/"+ campaign.Map +".jpg");
            self.notes = ko.observable(campaign.Notes);
            self.status = ko.observable(status[campaign.status]);
        }

And I have a simple binding to view the each message in the chat model:

   <div id="chat-messages" data-bind="foreach:chat.messages" style=" max-height: 250px; min-height: 80px; overflow-y: auto;">
                        <div data-bind="text:$data"></div>
                    </div>

Apply bindings is added:

  ko.applyBindings(this.viewModel); //where this.viewModel is an instance of Lobby

However I get the following error:

Uncaught ReferenceError: Unable to process binding "foreach: function (){return chat.messages }" Message: chat is not defined

I've tried putting them all in one model, splitting them out like this. Al sorts, it just doesn't want to work. Any suggestions?

Upvotes: 0

Views: 224

Answers (2)

artm
artm

Reputation: 8584

Lobby's chat is a function of Messages type so using the binding data-bind="foreach:chat.messages" translates to Lobby.chat which returns a function. So you need to change your binding to data-bind="foreach:chat().messages"

Upvotes: 1

Sam
Sam

Reputation: 1707

your problem is that chat is an observable and as such you should call chat().messages :)

Upvotes: 1

Related Questions