将主干集合填充到表中

Populate Backbone Collection to table

本文关键字:填充 集合      更新时间:2023-09-26

我已经获取了JSON数据,但在表中填充它时遇到了困难。有什么帮助吗?

我已经有响应json数据:

data                                    Object { 4c064462f170f63d57f55ab55e6b36f1={...}, b4f68bc5c045d2e88840995a47f7ddf5={...}}
    4c064462f170f63d57f55ab55e6b36f1    Object { rowid="4c064462f170f63d57f55ab55e6b36f1", id="1", qty="3", more...}
    b4f68bc5c045d2e88840995a47f7ddf5    Object { rowid="b4f68bc5c045d2e88840995a47f7ddf5", id="6", qty="2", more...}

这是我的JS代码

var Feed = Backbone.Model.extend({  
     });
var Stream = Backbone.Collection.extend({    
    url: function () {
        return BASE_URL + 'api/remotejson';
    },
    model: Feed,
    parse: function (response) {        
        var tags = response.data;
        return tags;
    } }); 
var FeedView = Backbone.View.extend({
    tagName: "tr",
    template: $("#feedTemplate").html(),
    render: function () {
        var tmpl = _.template(this.template);
        this.$el.html(tmpl(this.model.toJSON()));
        return this;
    } });  
var StreamView = Backbone.View.extend({
    el: $("#main-section"),
    initialize: function () {        
        this.collection = this.options.collection;
        this.render();
        this.collection.on("add", this.renderFeed, this);        
    },
    render: function () {
        var that = this;
        this.collection.fetch({success: function () {
                _.each(that.collection.models, function (item) {
                    that.renderFeed(item);
                }, this);       
            }
        });
    },
    renderFeed: function (item) {        
        var feedView = new FeedView({
            model: item
        });
        this.$el.find('#options-table tbody').append($(feedView.render().el).hide().fadeIn('slow'));
    },    
    loadMore: function () {
        this.collection.page += 10;
        this.render();        
    } });

这是我的html模板

<div id="main-section">
    <table class="table table-striped" id="options-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Quantity</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <script id="feedTemplate" type="text/template">
        <td><% rowid %></td>
        <td><% qty %></td>
    </script>
    <script type="text/javascript">
        $(document).ready(function() {
            var collection = new Stream();
            var streamView = new StreamView({collection: collection});
        });
    </script>
</div>

数据必须是完美的键值对才能初始化模型。您可以在解析中检查和修改数据

var Feed = Backbone.Model.extend({  
    parse : function(resp){
      return _.values(resp.data)[0]
          }
     });

在您的流视图中,设置标志以执行解析

renderFeed: function (item) {        
        var feedView = new FeedView({
            model: item,
            parse:true
        });
        this.$el.find('#options-table tbody').append($(feedView.render().el).hide().fadeIn('slow'));
    },