Backbone.js集合没有从url获取数据

时间:2015-08-10 16:26:28

标签: backbone.js

我的收藏品没有从我传递的网址中获取数据。控制台报告{length:0,models:Array [0],_ byId:Object}。 JSON肯定存在,否则会导致错误。我错过了什么?

JS:

$(document).ready(function(){

    // Model
    var Article = Backbone.Model.extend({
        defaults: {
        title: '',
        body: ''
      }
    });

    // Collection
    var Articles = Backbone.Collection.extend({
        model: Article,
        url: 'http://local.headless.com/apps/test.json'
    });

    // View
    var ArticlesView = Backbone.View.extend({
        el: $("#article-container"),

        initialize: function(){
            this.collection = new Articles;
            this.collection.fetch();
            console.log(this.collection); // Nothing here
            this.render();
        },
        render: function(){
          //var template = _.template( $("#article-template").html(), {} );
          //this.$el.html(template(this.collection.toJSON()));

        },

  });


    var articleView = new ArticlesView();

});

JSON:

[{"title":"<a href=\"\/node\/2\" hreflang=\"en\">Basic Page 2<\/a>","body":"<p>This is basic page 2<\/p>"},{"title":"<a href=\"\/node\/1\" hreflang=\"en\">This is a basic page<\/a>","body":"<p>This is the content for basic page 1<\/p>"}]

1 个答案:

答案 0 :(得分:1)

this.collection.fetch().then(function(){
    console.log(this.collection);
    this.render();
}.bind(this));

fetch是异步的,您需要在检查/渲染之前等待它完成...