Backbone.js collection 没有从 url 获取数据
Backbone.js collection not getting data from url
我的 collection 没有从我传递的 url 中获取数据。控制台报告 {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>"}]
this.collection.fetch().then(function(){
console.log(this.collection);
this.render();
}.bind(this));
fetch
是异步的,需要等它完成再检查it/rendering...
我的 collection 没有从我传递的 url 中获取数据。控制台报告 {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>"}]
this.collection.fetch().then(function(){
console.log(this.collection);
this.render();
}.bind(this));
fetch
是异步的,需要等它完成再检查it/rendering...