Backbone.js:使用RESTful API时视图不会呈现

问题描述 投票:0回答:1

我正在学习Backbone.js。我可以找到一千一百个Backbone.js教程,但是似乎都没有涉及从RESTful API获取数据的教程。我发现的其他解决方案似乎都不适合我的特定问题。

摘要

以下代码在创建模型(包含静态数据)并将其添加到集合中时起作用,但是当我使用测试RESTful服务时,视图将无法呈现,但可以在控制台中看到响应。

我确定我缺少简单的东西,但不能指望它是什么。

这是我的小提琴:https://jsfiddle.net/Currell/xntpejwh/

下面是代码段,如果您希望在此处查看它们。

测试RESTful API: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();
backbone.js
1个回答
1
投票

[使用REST API时,您需要一种机制来等待请求成功后再执行操作。

这是一个简单的解决方法:https://jsfiddle.net/wnxhq98p/

posts.fetch({
  success: postsView.render.bind(postsView),
  error: this.fetchError
});

一种常见的模式是在View的initialize中获取集合,并在成功调用后将其命名为render

或在视图的initialize内创建集合,设置集合事件侦听器,它将适当地渲染视图,然后在Backbone路由器内部获取集合,但是要使此工作正常,在initialize上获取集合必须不发生,以便让其他组件有机会设置事件以侦听集合

© www.soinside.com 2019 - 2024. All rights reserved.