我正在学习Backbone.js。我可以找到1,001个Backbone.js教程,但似乎没有一个涵盖从RESTful应用程序接口获取数据。我发现的其他解决方案似乎都不适合我的特定问题。
摘要
当创建模型(包含静态数据)并将其添加到集合中时,以下代码可以工作,但当我使用测试RESTful服务时,视图不会呈现,但我可以在控制台中看到响应。
我确信我错过了一些简单的东西,但我不能确定它是什么。
这是我的小提琴:https://jsfiddle.net/Currell/xntpejwh/
如果您想在这里查看代码片段,可以参考下面的代码片段。
测试RESTful接口:https://jsonplaceholder.typicode.com/
HTML:
<div id="js-spa-container"></div>
JS:
var Post = Backbone.Model.extend();
var Posts = Backbone.Collection.extend({
model: Post,
url: 'https://jsonplaceholder.typicode.com/posts',
initialize: function(){
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
},
fetchSuccess: function (collection, response) {
console.log('Fetch response: ', response);
},
fetchError: function (collection, response) {
throw new Error("Books fetch error");
}
});
var PostView = Backbone.View.extend({
tagName: 'li',
render: function() {
this.$el.html(this.model.get('title'));
return this;
}
});
var PostsView = Backbone.View.extend({
render: function() {
var _this = this;
this.collection.each(function(post) {
// Put the current post in the child view
var _postView = new PostView({ model: post });
// Render the post and append it to the DOM element of the postsView.
_this.$el.append(_postView.render().$el);
});
}
});
var posts = new Posts();
var postsView = new PostsView({ el: '#js-spa-container', collection: posts });
postsView.render();
发布于 2019-10-25 13:55:41
当您使用REST API时,您需要一种机制来等待请求成功后再执行操作。
这里有一个简单的解决方案:https://jsfiddle.net/wnxhq98p/
posts.fetch({
success: postsView.render.bind(postsView),
error: this.fetchError
});
一种常见的模式是获取视图的initialize
中的集合,并在成功时调用它的render
。
或者创建集合,在视图的initialize
中设置收集事件侦听器,它将适当地呈现视图,然后在骨干路由器中获取集合,但是为了使其他组件有机会设置侦听收集的事件,收集获取不能立即在initialize
上发生
https://stackoverflow.com/questions/58550187
复制相似问题