无法从REST

时间:2015-12-31 12:57:39

标签: javascript php rest backbone.js

我已经正确编写了一个简单的REST api和几个骨干模型。我的父模型称为Topic,子模型称为Questions

我正在尝试在REST api上调用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网址:

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

Backbone View:这是我认为错误的地方......(下面的控制台日志打印出一个空对象)

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();
});

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

1 个答案:

答案 0 :(得分:1)

topics处理程序中的参数successshadowing变量topics

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

topics的引用现在将发送到您的收藏集,因此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);
  }
})