【发布时间】:2015-09-21 13:33:15
【问题描述】:
目前,我在使用 Backbone fetch() 获取正确的 JSON 对象并将其放入 Handlebars 模板时遇到问题。
见下面我的代码,我现在做了一个丑陋的解决方法来测试我的后端 API 当使用 *.toJSON() 转换为 JSON 时,它只是在中间添加了一个额外的对象,我不需要这个额外的对象
Object [0]
--> books
----> Object [0]
------> Array of book
--------> book
--------> cities
JSON
{
"books": [
{
"book": 00001,
"cities": [
"TEST"
]
},
{
"book": 00002,
"cities": [
"TEST"
]
},
{
"book": 00003,
"cities": [
"TEST"
]
}
],
"more": true
}
JavaScript
var Book = Backbone.Model.extend({
default: {
book: 0,
cities: ["TEST1", "TEST2", "TEST3"]
},
url: function () {
return ".list.json";
}
});
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json"
});
var BooksView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render');
this.collection = new Books();
this.collection.fetch();
this.source = $('.e-books-template').html();
// Use an extern template
this.template = Handlebars.compile(this.source);
var self = this;
this.collection.fetch({
success: function () {
self.render();
},
error: function () {
console.log("ERROR IN BooksView");
}
});
},
render: function() {
var collect = JSON.stringify(this.collection);
collect = collect.slice(1, -1);
var html = this.template($.parseJSON(collect));
this.$el.html(html);
}
});
var booksView = new BooksView({ });
$(document).ready(function(){
booksView.$el = $('.e-books-content');
});
【问题讨论】:
-
这就是我尝试过的,但这并不像我想要的那样工作,因为它在中间添加了额外的对象
标签: json backbone.js handlebars.js