2014-01-30 26 views
0

如何解決?「未定義」問題「無法調用方法」

查看:

App.Views.ModelsIndex = Backbone.View.extend({ 
    tagName: 'div', 
    initialize: function() { 
     this.template = _.template($('#container').html()); 

     // Cannot call method 'on' of undefined 
     this.model.on('change', this.render, this); 
    }, 
    render: function() { 
     $(this.el).html(this.template({'model' : this.model})); 
     return this; 
    } 
}); 

路由器:

App.Routers.Models = Backbone.Router.extend({ 
    routes: { 
     '': 'index', 
     'admin/:id' : 'show' 
    }, 
    initialize: function() { 
     this.collection = new App.Collections.Models(); 
     this.collection.fetch(); 
    }, 
    index: function() { 
     view = new App.Views.ModelsIndex({'collection' : this.collection}); 
     $('#container').html(view.render().el); 
    }, 
    show: function(id) { 
     alert('entry id:' + id); 
    } 
}); 

收藏:

App.Collections.Models = Backbone.Collection.extend({ 
    url: "/app_dev.php/partner/api/users/1" 
    , model: App.Models.Model 
}); 

回答

2

您的路由器通過收集到您的視圖構造

new App.Views.ModelsIndex({'collection' : this.collection}); 

,但你在視圖中使用的模型:

this.model.on('change', this.render, this); 

選擇一個,並堅持下去:

App.Views.ModelsIndex = Backbone.View.extend({ 
    initialize: function() { 
     this.template = _.template($('#container').html()); 
     this.collection.on('change', this.render, this); 
    } 
    ... 
}); 
+0

非常感謝!剛開始學習Backbone ... –

相關問題