目前我的问题是找回正确的JSON对象,并使用Backbone fetch()获取并将其放入Handlebars模板中。如何将Backbone抓取的对象转换为正确的Handlebars JSON对象?
看下面我的代码,我已经做了一个丑陋的解决方法,现在测试我的后端API 当转换为JSON与* .toJSON(),它只是添加一个额外的对象之间,我不需要这额外的对象
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');
});
您是否在寻找HTTP演示:// backbonejs。 org /#Collection-toJSON? – nikoshr
这就是我所尝试的,但这并不是我想要的方式,因为它在中间添加了额外的对象 – Eve