Knockout嵌套对象绑定不起作用(对象未定义)

时间:2016-02-24 13:36:52

标签: javascript knockout.js

所以我有四个模特:

  • 大厅(视图模型)
  • 消息
  • 广告活动
  • 运动

我让他们这样设置:

       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]);
        }

我有一个简单的绑定来查看聊天模型中的每条消息:

   <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>

添加了应用绑定:

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

但是我收到以下错误:

  

未捕获的ReferenceError:无法处理绑定“foreach:function   (){return chat.messages}“消息:未定义聊天

我已经尝试将它们全部放在一个模型中,像这样将它们分开。 Al排序,它只是不想工作。有什么建议?

2 个答案:

答案 0 :(得分:1)

您的问题是chat是可观察的,因此您应该致电chat().messages:)

答案 1 :(得分:1)

Lobby&#39; chatMessages类型的函数,因此使用绑定data-bind="foreach:chat.messages"转换为返回函数的Lobby.chat。因此,您需要将绑定更改为data-bind="foreach:chat().messages"