我认为我在骨干中做错了,所以我有一个集合,模型和路线:
路线
AisisWriter.Collections.Posts = Backbone.Collection.extend({
model: AisisWriter.Models.Post,
// Build the url based on blog id.
url: function() {
url = '/api/v1/blogs/' + AisisWriter.blog_id + '/posts/'
return url;
}
});
集合
AisisWriter.Routers.Posts = Backbone.Router.extend({
posts: null,
routes : {
'': 'index'
},
initialize: function() {
var writer_posts = new AisisWriter.Collections.Posts();
this.posts = writer_posts.fetch();
},
index: function() {
console.log(AisisWriter.blog_id, this.posts);
}
});
模型
AisisWriter.Models.Post = Backbone.Model.extend({
initialize: function() {},
getTitle: function() {
return this.get('title');
},
getContent: function() {
return this.get('content');
},
getTags: function() {
return this.get('tag_names');
},
getCategories: function() {
return this.get('category_names');
},
getComments: function() {
return this.get('comments');
},
});
当集合索引路由执行时,我得到以下内容:
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
注意:以上是非扩展对象的控制台输出。
这...我猜我会或应该期待什么,接受我认为我会收回我的帖子对象因为this.posts.getTitle()
不起作用。
那么在获取帖子对象方面我做错了什么?在这个巨大的对象里面,我看到一个包含我的json对象的ResponseJSON对象 - 我希望这样我可以做this.posts.getTitle()
;
答案 0 :(得分:0)
fetch()是一个异步调用,因此您需要等待来自服务器的响应。将作业分配到n#34;帖子"在成功处理程序中:
var that;
AisisWriter.Routers.Posts = Backbone.Router.extend({
posts: null,
routes : {
'': 'index'
},
initialize: function() {
},
index: function() {
that = this;
var writer_posts = new AisisWriter.Collections.Posts();
writer_posts.fetch({
reset: true,
success: function (collection, response, options) {
console.log(AisisWriter.blog_id, collection);
that.posts = collection;
},
error: function (collection, response, options) {
}
});
}
});
答案 1 :(得分:0)
我认为这是双重的: Why can I not use this.posts out side the success function?
所以我向你提出了建议。如果你想访问this.posts,你应该在initialize函数中将观察者添加到你的集合中:
this.listenTo(this.writer_posts, 'reset', this.test);
多数民众赞成我称之为Backbone方式。
另一方面,很难理解你想做什么。例如,您正在尝试从集合中获取标题...
var writer_posts = new AisisWriter.Collections.Posts();
this.posts = writer_posts.fetch();
然后
this.posts.getTitle()
它不起作用,因为它是Collection。而且您不需要创建单独的方法来从模型中获取标题,标记等。您可以直接访问标题:
this.model.get('title');
或
this.model.toJSON().title;