gpt4 book ai didi

javascript - 主干 View /模板无法从 REST 加载

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:00 26 4
gpt4 key购买 nike

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

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

型号:

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/

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

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

最佳答案

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

参数包含已解析的 JSON 响应,而不是主干集合。你不需要那个,所以你可以删除参数。

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

关于javascript - 主干 View /模板无法从 REST 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com