duanlun4411 2015-08-03 08:02
浏览 70
已采纳

如何使用backbone.js划分JSON集合结果

Current the results of my json is this.

<div id="item-list">
   <div class="row" id="featured-item">
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
   </div>
</div>

Is that possible to make it like this?

<div id="item-list">
   <div class="row">
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
   </div>
   <div class="row">
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
   </div>
   <div class="row">
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
   </div>
   <div class="row">
      <div class="col-md-6"><p>Content Righ Here</p></div>
      <div class="col-md-6"><p>Content Righ Here</p></div>
   </div>
   <div class="row">
      <div class="col-md-6"><p>Content Righ Here</p></div>
   </div>
</div>

Here is my current jS code:

var Feed = Backbone.Model.extend({
    url: function () {
        //API LINK HERE
    },  
    defaults: {
        // SOME ATTRIBUTES HERE
    }
});

var Stream = Backbone.Collection.extend({    
    url: function () {
        //API LINK HERE
        return link;
    },
    page: 0,
    sort: 'date_created',
    order: 'desc',
    limit: 12,
    model: Feed,
    parse: function (response) {        
        $('.total_records').text(response._count);       
        var tags = response.data;
        this.totalRecords = response._count;
        return tags;
    }
}); 

// Master view
var DirectoryView = Backbone.View.extend({
    el: $("#main-section"),
    initialize: function () {   
        this.collection = this.options.collection;
        this.isLoading = false;
        this.render();
        this.collection.on("add", this.renderFeed, this);        
    },
    events: {
        'click #loadmore-feed' : 'loadMore'
    },
    render: function () {
        var that = this;
        this.isLoading = true;
        this.collection.fetch({success: function () {
                _.each(that.collection.models, function (item) {
                    that.renderFeed(item);
                }, this);
                that.isLoading = false;
                $("abbr.timeago").timeago();

                that.$el.find('#load-more-container').html(
                    _.template($('#load-more-template').html())
                );              
            }
        });

        if(!this.collection.totalRecords) {
            $('#load-more-container').hide();
        }
    },  
    loadMore: function () {
        $('#load-more-container').hide();
        if(this.collection.totalRecords > this.collection.page) {
            this.collection.page += 12;
            this.render();  
            $('#load-more-container').show();
        }      
    },
    renderFeed: function (item) {        
        var optionsView = new OptionsView({
            model: item
        });

        this.$el.find('#item-list > div').append($(optionsView.render().el).hide().fadeIn('slow'));

    }  
});

var OptionsView = Backbone.View.extend({
    tagName: "div",
    className: "col-md-6",
    template: $("#emp-list-item").html(),
    render: function () {
        var tmpl = _.template(this.template);        
        this.$el.html(tmpl(this.model.toJSON()));
        return this;
    }
}); 

HTML Code

<div id="main-section">
    <div id="item-list">
        <div class="row" id="featured-item"></div>
    </div>
    <div id="load-more-container"></div>
</div>
<!-- backbonejs view template -->
<script id="emp-list-item" type="text/template">      
    <p>Content Righ Here</p>
</script>
<script id="load-more-template" type="text/template">
    <p>
        <div class="progress xs progress-striped">
            <div class="progress-bar progress-bar-primary" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                <span class="sr-only">60% Complete (warning)</span>
            </div>
        </div>
        <div class="tcenter">
            <a href="javascript:void(0)" id="loadmore-feed">Load more</a>
        </div>  
    </p>
</script>

<!-- Script for autoloading on mobile device -->
<script type="text/javascript">
    $(document).ready(function() {
        var paginatedItems = new Stream();
        var directoryView = new DirectoryView({collection: paginatedItems});
        $(window).scroll(function() {
            if (directoryView.$el.is(':visible') && !directoryView.isLoading && $(window).scrollTop() + $(window).height() > getDocHeight() - 400 ) {
                directoryView.loadMore();         
            }
        });
    });
</script>
  • 写回答

1条回答 默认 最新

  • douan7601 2015-08-04 20:14
    关注

    Your question title concerns JSON but your example concerns HTML, which are totally different concerns. I cannot tell if you mean "can I produce this type of HTML structure" or "can I make my collection hold this structure of data."

    Without addressing core issues, you should still move the fetch out of the render, and make the render something that happens on success. For instance:

    initialize: function(models) {
        // ...do stuff...
        if (!models)
             this.fetch({success: this.render, error: this.error});
        _.bindAll(this, 'render', 'error', 'render');
    },
    

    In your success, you should prepare for render:

    render: function(collection) {
        var modelsFlat = collection.models;
        var nested = _(list).chain().partition(function(x) {
    
            // below makes an array of evens and odds indices
    
            return (_(list).indexOf(x) % 2) == 0;  
    
        }).zip()           // this turns columns into rows, ie [[1,3,5],[2,4,6]] => [[1,2],[3,4],[5,6]]
          .value();        // this unwraps (no more chaining)
    
        _(nested).each(function(n) {
            var inner = new Backbone.Collection(n);
            var innerView = new OptionsView(inner);
            innerView.render();
        });
        // Do the rest of your current render
    }
    

    And your new DirectoryItemView is pretty much the OptionsView, which involves no server-side stuff.

    So this:

    1. Calls the fetch on initialize of the outer view to get the outer collection
    2. On success calls render
    3. On render, reorganizes each pair of items into a new little collection
    4. On each collection, creates a new inner OptionsView with that collection, and renders it
    5. Finishes by rendering the rest of the outer view.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况