2012-12-29 41 views
0

我有三種不同的視圖模板:「發佈」,「評論」,「添加新評論」。主要模板是「後」。我需要找出如何將「評論」和「添加新評論」模板放入「發佈」模板中的他們的div中。或任何其他方法,使這種結構:骨幹:模板動態視圖層次結構

 
    - post 
     - comments 
     - add new post form 
    - post 
    ... 

這是一個類似Facebook的牆

的JavaScript骨幹:

// Post View 
var PostView = Backbone.View.extend({ 
    template: $("#post").html(), 
    ... 
    render: function() { 
     var tmpl = _.template(this.template); 
     var thisPost = this.model.toJSON(); 
     this.$el.html(tmpl(thisPost)); 
    } 
}); 
var postView = new PostView(); 
postView.render(); 

// Comments List 
var CommentsListView = Backbone.View.extend({ 
    el: '#comments', // how to place it to #comments div in "post" template? This line doesn't work 
    ... 
    addNewCommentForm: function (post_id) { 
     var tmpl = _.template($("#addCommentTemplate").html()); 
     this.$('#addNewComment').append(tmpl()); // How to place it to #addNewComment div in "post" template? This line doesn't work 
    } 
}); 

HTML:

<script id="post" type="text/template"> 
    <%= text %> 
    <div id='comments'>...</div> 
    <div id='addNewComment'>...</div> 
</script> 

回答

1

有許多你的代碼有問題。首先,你並沒有將PostView.el放入DOM中。通過PostView.render(),您正在填充PostView.$el和隨後的PostView.el,但實際上並未將其放入頁面(DOM)中。此外,通過設置el,CommentsListView,您並不是真的在那裏做任何事情。如果您想將el設置爲現有元素,那麼您應該這樣做:el: $('#comments')。或者,如果您想要動態呈現CommentsListView並將其注入到DOM中,那麼您只需通過定義id屬性來使該元素具有「註釋」標識,如下所示:id: 'comments'。這些只是代碼中最明顯的兩個問題。我在這裏運行了一個半工作示例:http://codepen.io/jayd3e/pen/hAEDv