underscore.js模板||绑定/追加主干

时间:2014-04-01 10:16:29

标签: javascript jquery backbone.js underscore.js-templating

我前几天在这个应用上问过问题;经过一些好的建议,我继续前进,我现在认为这是一个不同的问题。 以前,我没有在屏幕上显示任何显示/没有错误或任何console.logs。在完成它之后,我现在有了我的模型/视图和一些渲染功能。

我认为问题在于我的模板或我的追加。下面是现在的完整代码。有//评论,我认为可能存在一些问题。 任何有关这方面的帮助将不胜感激。

编辑:: 感谢Niranjan的建议。我做了一些你提到的改变;我带走了计数器和样本数据。随着这些新的变化,我的newsFeed.js不再被阅读,因此我不知道如何填充我的收藏。当我在console.log中输出我的集合时,我得到一个显示默认值的空数组,但是首先没有读取json文件,我该如何处理它?<​​/ p>

编辑#2 :: 再次感谢Niranjan。根据您建议的更改和我自己的一些更改,我现在有以下代码。我现在面临的问题是,我的阵列是否被填充了太多次。 JSON文件总共有8个条目,由于我的模板中的_.each语句,它循环8次,我只希望它循环一次,然后将数组拆分成单独的条目。我尝试在我的回复解析期间首先拆分它,但这不起作用,你对此有什么建议吗?

代码下方的

是指向代码和html / broswer内容的实时视图的链接,包括指向JSON文件的链接。

我的最终目标是点击一个标题并显示相应的内容。

        (function(){        

    var NewsFeedModel  = Backbone.Model.extend({
        defaults: {
            title: '',
            content: ''
        }
    });

    var NewsFeedCollection  = Backbone.Collection.extend({
        model: NewsFeedModel,
        url : 'newsFeed.js',
            parse: function(response) {
                console.log('collection and file loaded');
             return response.responseData.feed.entries;
            }
    });

    var NewsFeedView = Backbone.View.extend({
        el : '.newsContainer ul',
        template: _.template($("#feedTemp").html()),  
        initialize: function(){ 
         var scopeThis = this;
            _.bindAll(this, 'render');

                this.collection.fetch({
                    success: function(collection){
                        scopeThis.render();
                    }
                });

                this.collection.bind( 'add',  this.render, this);
                console.log('View and Template read');
    },  
    render: function () {
            this.$el.html(this.template({
            feed: this.collection.toJSON() 
      }));
      console.log(this.collection.toJSON());
    }

});

 var newsFeedCollection = new NewsFeedCollection();


    var newsFeedView = new NewsFeedView({
    collection: newsFeedCollection
});

var title = newsFeedCollection.find('title');
var content = newsFeedCollection.find('content > title'); 

$(document).on("click", "#add", function(title, content) { 
    console.log("I have been clicked"); 

    if($(title) == $(content)){
    console.log('they match');
    }
    else{
    console.log('they dont match');
    }
$('.hide').slideToggle("slow");


});


}());

这是我的下划线模板。

   <div class="span12">
<script id="feedTemp" type="text/template">
    <% _.each(feed, function(data) { %> 
       <div id = "titleContent"> 
         <a href='#' id ="add"> <%= data.title %> </a>
             <div id="content" class="hide">
                <%= data.content %>
             </div> 
       </div>
<% }); %>
</script>           
</div>

我使用谷歌硬盘作为试验场;完整的HTML /代码的链接。 https://docs.google.com/file/d/0B0mP2FImEQ6qa3hFTG1YUXpQQm8/edit [代码视图] https://googledrive.com/host/0B0mP2FImEQ6qUnFrU3lGcEplb2s/feed.html [浏览器视图] https://docs.google.com/file/d/0B0mP2FImEQ6qbnBtYnVTWnpheGM/edit [JSON文件]

1 个答案:

答案 0 :(得分:0)

您的代码中还有很多东西可以改进。 这是 JSFIDDLE

请仔细阅读代码中提到的评论。

要在Underscore的模板中试用,请检查Underscore's Template Editor

<强>模板:

<button id=add>Add</button>
<div class="newsConatiner">
    <ul></ul>
</div>
<script id="feedTemp">
    <% _.each(feed, function(data) { %> 
        <div id = "titleContent"> 
            <h2> <%= data.title %> </h2>
            <div id="content">
                <%= data.content %>
            </div> 
        </div>
   <% }); %>
</script>

<强>代码:

(function () {

    var NewsFeedModel = Backbone.Model.extend({
        //url: 'newsFeed.js',
        defaults: {
            title: '',
            content: ''
        }
    });

    var NewsFeedCollection = Backbone.Collection.extend({
        model: NewsFeedModel,
        url: 'newsFeed.js',
        parse: function (response) {
            console.log('collection  and file loaded');
            return response.responseData.feed.entries;
        }
    });

    var NewsFeedView = Backbone.View.extend({
        el: '.newsConatiner',
        //template should not be inside initialize
        template: _.template($("#feedTemp").html()),
        initialize: function () {
            _.bindAll(this, 'render');
            this.render();

            //ADD event on collection
            this.collection.bind('add', this.render, this);
            console.log('View and Template read');
        },
        /*
        This initialize will fetch collection data from newsFeed.js.
        initialize: function () {
            var self = this;
            _.bindAll(this, 'render');

            this.collection.fetch({
                success: function(collection){
                    self.render();
                }
            });
            //ADD event on collection
            this.collection.bind('add', this.render, this);
            console.log('View and Template read');
        },

         */
        render: function () {
            //This is how you can render
            //Checkout how this.collection is used
            this.$el.html(this.template({
                feed: this.collection.toJSON()
            }));
        }
    });
    //Initialized collection with sample data
    var newsCounter = 0;
    var newsFeedCollection = new NewsFeedCollection([{
        title: 'News '+newsCounter++,
        content: 'Content'
    }]);

    //Created view instance and passed collection
    //which is then used in render as this.collection
    var newsFeedView = new NewsFeedView({
        collection: newsFeedCollection
    });
    $('#add').click(function(){
        newsFeedCollection.add(new NewsFeedModel({
            title: 'News ' + newsCounter++,
            content: 'Content'
        }));
    });
}());
相关问题