目前我的問題是找回正確的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