2015-09-21 35 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