我有一个我知道正在获取整个集合的集合,但是如何访问从fetch中返回的数据?
/js/views/idea.js
define([
'jquery',
'underscore',
'backbone',
'collections/ideas'
], function($, _, Backbone, IdeasCollection) {
var IdeasView = Backbone.View.extend({
el: $('#container'),
render: function(){
this.collection = new IdeasCollection();
console.log( this.collection.fetch() ); // I can see data
var data = {};
var template = _.template( $('#ideasView').html(), data);
$('body').removeClass().addClass('blog');
this.$el.html( template );
}
});
return IdeasView;
});
/js/collections/ideas.js (简称简称。)
var IdeasCollection = Backbone.Collection.extend({
url: '/api/ideas',
model: IdeaModel
});
答案 0 :(得分:1)
fetch
是异步的。您必须使用事件绑定样式。
var IdeasView = Backbone.View.extend({
initialize: function () {
this.collection = new IdeasCollection();
this.listenTo(this.collection, 'sync', this.render);
this.collection.fetch();
},
render: function(){
var template = _.template( $('#ideasView').html(), this.collection.toArray());
$('body').removeClass().addClass('blog');
this.$el.html( template );
}
});
return IdeasView;
});
答案 1 :(得分:0)
另一种方式。
var that = this;
this.collection = new IdeasCollection();
this.collection.fetch({success: function (){
that.render();
}});