2012-10-27 73 views
0

我正在學習骨幹路由。我剛剛使用骨幹構建了一個小應用程序。但路線不起作用。我在控制檯需要幫助骨幹路由

Uncaught TypeError: Cannot read property 'el' of undefined

這裏得到這個錯誤是我的代碼

$(function() { 
/****************************/ 
var documents = [ 
    new Backbone.Model({ 
     title: 'Title One', 
     content: 'This is content for JS module' 
    }), 
    new Backbone.Model({ 
     title: 'Title Two', 
     content: 'Module Systems Module Systems Module Systems Module Systems Module Systems' 
    }) 
]; 

var contentsView = Backbone.View.extend({ 
    tagName: 'ul', 
    render: function() { 
     _(this.collection).each(function (document) { 
      this.$el.append(new DocumentListView({model: document}).render().el); 
     }, this); 
    } 
}); 

var DocumentListView = Backbone.View.extend({ 
    tagName: 'li', 
    render: function() { 
     this.$el.html(this.model.get('title')); 
     return this; 
    } 
}); 

var DocumentRouter = Backbone.Router.extend({ 
    routes: { 
     'contents': 'contents' 
    }, 
    contents: function() { 
     $('body').html(new contentsView({collection: documents}).render().el); 
    } 
}); 

var router = new DocumentRouter(); 
Backbone.history.start(); 

router.navigate('contents', {trigger:true}); 
/****************************/ 
}); 

這是根據控制檯消息出現上述錯誤行

$('body').html(new contentsView({collection: documents}).render().el);

怎麼能我解決了這個問題?

回答

0

你應該從你的contentView渲染函數返回這個。 。

var contentsView = Backbone.View.extend({ 
     tagName: 'ul', 
     render: function() { 
      _(this.collection).each(function (document) { 
       this.$el.append(new DocumentListView({model: document}).render().el); 
      }, this); 
     return this; 
     } 
    }); 

如果你的意思是要追加contentsview身體,使用這樣的 $( '身體')追加(新contentsView({集合:文件})渲染()$ EL);

如果contentsView是唯一的內容意味着body標籤,這樣使用

var contentsView = Backbone.View.extend({ 
      el : 'body', 
      tagName: 'ul', 
      render: function() { 
       _(this.collection).each(function (document) { 
        this.$el.append(new DocumentListView({model: document}).render().el); 
       }, this); 
      return this; 
      } 
     }); 
contentsView.render(); 
+0

呀設法找到了我自己的錯誤的構造。我正要回答我自己的問題,但現在你這樣做了,謝謝。 – 2619