【问题标题】:How to convert Backbone fetched object to proper Handlebars JSON Object?如何将 Backbone 获取的对象转换为正确的 Handlebars JSON 对象?
【发布时间】:2015-09-21 13:33:15
【问题描述】:

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

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

【问题讨论】:

  • 这就是我尝试过的,但这并不像我想要的那样工作,因为它在中间添加了额外的对象

标签: json backbone.js handlebars.js


【解决方案1】:
  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/

【讨论】:

  • 我试过这个,但是当我添加解析时,我在日志“Uncaught SyntaxError: Unexpected token”中得到一个错误,我检查了官方文档,它应该是正确的,但是这不是不行。
  • 某处有错字?这是一个模拟您的设置的演示 jsfiddle.net/nikoshr/8jdb13jg
  • 我也这么认为,但添加“解析”会给出此错误。我什至只是复制/粘贴,仍然是同样的错误。
  • 对不起,我的 HTML 中有一个逗号,而不是一个点 :-(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 2023-03-17
  • 2021-10-14
  • 1970-01-01
  • 2023-04-03
  • 2014-11-05
  • 1970-01-01
相关资源
最近更新 更多