无法从REST加载主干视图/模板


Backbone view/template fails to load from REST

我已经正确地编码了一个简单的RESTapi和几个主干模型。我的父模型称为Topic,子模型称为Questions

我试图在RESTapi上调用一个get方法,并以一种可呈现的方式向用户显示接收到的Topic对象。我收到了json(可以在Chrome的网络选项卡中看到),但它没有正确发送到视图。

型号:

var Topic = Backbone.Model.extend({
    urlRoot: ROOT + '/topic',
    idAttribute: 'topicId',
    initialize: function () {
        this.questions = new Questions([], {parent: this});
    },
    toJSON: function () {
        var json = Backbone.Model.prototype.toJSON.call(this);
        json.questions = this.questions.toJSON();
        return json;
    }
});
var Topics = Backbone.Collection.extend({
    model: Topic,
    url: ROOT + 'topic',
    parse: function (response) {
        return response.results;
    }
})

REST URL:

http://localhost/Project/index.php/rest/resource/topic/

主干视图:我认为这就是错误所在…(下面的控制台日志打印一个空对象)

var TopicListView = Backbone.View.extend({
      el: '.page',
      render: function () {
        var that = this;
        var topics = new Topics();
        topics.fetch({
          success: function (topics) {
              console.log(topics);
            var template = _.template($('#topic-list-template').html(), {topics: topics.models});
            that.$el.html(template);
          }
        })
      }
    });

使用上述功能:

var topic = new Topic();
topic.fetch();
topicListView = new TopicListView();
var Router = Backbone.Router.extend({
    routes: {
        "": "home"
    }
});
var router = new Router;
// render topic list for 'home'
router.on('route:home', function () {
    topicListView.render();
});

编辑:解决方案:覆盖集合中的解析函数被证明是错误的。我想知道为什么。。。

success处理程序中的参数topics隐藏变量topics

该参数包含已解析的JSON响应,而不是Backbone Collection。你不需要这样,所以你可以删除这个论点。

topics的引用现在将指向您的Collection,因此topics.models将具有您期望的值。

topics.fetch({
  success: function () { // argument removed here so `topics` is no longer shadowed
    var template = _.template($('#topic-list-template').html(), { topics: topics.models });
    that.$el.html(template);
  }
})