为什么Backbone view.collection是'undefined'?

时间:2014-08-14 10:25:53

标签: javascript backbone.js

var Chat = Backbone.Model.extend({
  messageList: new MessageList(),
  messageListView: new MessageListView({collection: this.messageList}),

 switchChannel: function(channel) {
     this.messageList.fetch({url: 'channels/'+channel, reset: true})
 }
});

在其他文件中:

var MessageList = Backbone.Collection.extend({
  model: Message,
})

var MessageListView = Backbone.View.extend({
  initialize: function(){
    console.log(this.collection)
    this.listenTo(this.collection, 'reset', this.render);
},

为什么我将我的收藏作为' undefined'?

console.log(this.collection) - >未定义

1 个答案:

答案 0 :(得分:0)

我发现了这个错误:

var Chat = Backbone.Model.extend({
messageList: new MessageList(),
messageListView: new MessageListView({collection: this.messageList}),
...

初始化必须在'initialize'函数

var Chat = Backbone.Model.extend({
  initialize: function(){
    this.messageList = new MessageList();
    this.messageListView = new MessageListView({collection: this.messageList});
}