如何将Backbone fetched对象转换为正确的Handlebars JSON对象?

时间:2015-09-21 13:33:16

标签: json backbone.js handlebars.js

目前我遇到了一个问题,即使用Backbone fetch()获取正确的JSON对象并将其放入Handlebars模板中。

请参阅下面的代码,我现在做了一个丑陋的解决方法来测试我的Backend 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');
});

1 个答案:

答案 0 :(得分: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()
    });
    
  3. 演示http://jsfiddle.net/nikoshr/8jdb13jg/