Backbone.js的迭代集合 [英] backbone.js iterate a collection

查看:115
本文介绍了Backbone.js的迭代集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了日志的集合。 API返回的结果作为JSON。我看到了previous话题,其中有人建议增加parse方法的集合。做如此,当我执行code,我没有得到任何输出到控制台。不过,我是新来的骨干,因此任何见解和/或指导,将AP preciated。我collection.each的理解可能不正确。

  VAR日志= ​​Backbone.Model.extend({});VAR LogList = Backbone.Collection.extend({
    型号:日志,
    网址:'API /日志',
    解析:功能(响应){
        返回response.logs;
    }
});VAR LogListView = Backbone.View.extend({    EL:$('#日志列表),    初始化:功能(){
        this.collection =新LogList();
        this.collection.fetch();
        this.render();
    },
    渲染:功能(){
        this.collection.each(功能(日志){
            的console.log('日志项目。,登录);
        });
    }
});$(文件)。就绪(函数(){
    的console.log('准备好了。');
    新LogListView();
});


解决方案

取是异步的。重写你的code调用一个回调渲染:

  VAR LogListView = Backbone.View.extend({EL:$('#日志列表),初始化:功能(){
    VAR自我=这一点;
    this.collection =新LogList();
    this.collection.fetch()。完成(功能(){
      self.render();
    });},
渲染:功能(){
    this.collection.each(功能(日志){
        的console.log('日志项目。,登录);
    });
}
});

I have set up a collection for Logs. The api returns the results as JSON. I saw a previous topic where it was suggested to add the parse method on the collection. Having done so, when I execute the code I am not getting any output to the console. Nevertheless, I am new to Backbone so any insight and/or guidance would be appreciated. My understanding of collection.each may not be correct.

var Log = Backbone.Model.extend({});

var LogList = Backbone.Collection.extend({
    model:  Log,
    url:    'api/logs',
    parse:  function(response) {
        return response.logs;
    }
});

var LogListView = Backbone.View.extend({

    el: $('#logs-list'),

    initialize: function() {
        this.collection = new LogList();
        this.collection.fetch();
        this.render();
    },
    render: function() {
        this.collection.each(function(log) {
            console.log('log item.', log);
        });
    }
});

$(document).ready(function(){
    console.log('ready.');
    new LogListView();
});

解决方案

Fetch is asynchronous. Rewrite your code to call render with a callback:

var LogListView = Backbone.View.extend({

el: $('#logs-list'),

initialize: function() {
    var self = this;
    this.collection = new LogList();
    this.collection.fetch().done(function(){
      self.render();
    });

},
render: function() {
    this.collection.each(function(log) {
        console.log('log item.', log);
    });
}
}); 

这篇关于Backbone.js的迭代集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆