2015-09-21 37 views
0

目前我的問題是找回正確的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'); 
}); 
+0

您是否在尋找HTTP演示:// backbonejs。 org /#Collection-toJSON? – nikoshr

+0

這就是我所嘗試的,但這並不是我想要的方式,因爲它在中間添加了額外的對象 – Eve

回答

2
  1. Backbone集合需要一個模型數組,但是您的JSON提供了一個帶有books鍵下的數組的對象。 Parse the server response格式化數據:

    var Books = Backbone.Collection.extend({ 
        model: Book, 
        url: ".list.json", 
        parse: function(data) { 
         return data.books; 
        } 
    }); 
    
  2. 通過http://backbonejs.org/#Collection-toJSON傳遞您的數據到您的模板,

    // directly as an array in your template 
    var html = this.template(this.collection.toJSON()); 
    
    // under a books key 
    var html = this.template({ 
        books: this.collection.toJSON() 
    }); 
    

而且http://jsfiddle.net/nikoshr/8jdb13jg/

+0

我試過這個,但是當我添加解析時,在日誌「Uncaught SyntaxError:Unexpected token」中得到一個錯誤,我檢查了這個官方文件,它應該是正確的,但這是行不通的。 – Eve

+0

某處有錯字嗎?這是一個模擬你的設置的演示http://jsfiddle.net/nikoshr/8jdb13jg/。 – nikoshr

+0

我也這麼認爲,但添加「解析」是給這個錯誤。我甚至只是複製/粘貼,仍然是同樣的錯誤。 – Eve