Backbone.js:填充我的集合,然后将其附加到页面

时间:2015-08-21 14:45:21

标签: javascript json backbone.js

我在backbone.js工作。在下面的代码中,我调用了Nutritionix API,以便使用JSON响应填充我的集合。我无法填充我的集合并将结果作为列表附加。我这样做是为了测试我的集合是否已正确填充,以及测试它是否会附加到页面。但是,当我在浏览器中测试代码时,我没有看到字段[brand_name]属性附加到页面。我的收藏是否正确填充?如何查看附加到页面的前述属性?我的代码出了什么问题?

这是我的Javascript:

saveState: true

这是我的HTML

$(function(){

    var SearchList = Backbone.Collection.extend({
        url: "https://api.nutritionix.com/v1_1/search/taco?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=26952a04&appKey=78e2b31849de080049d26dc6cf4f338c",

        initialize: function(){
            this.bind("reset", function(model, options){
            console.log("Inside event");
            console.log(model);
            });
        }

    });

    var terms = new SearchList();

    terms.fetch({
        success: function(response,xhr) {
             console.log("Inside success");
             console.log(response.toJSON());
        },
        ERROR: function (errorResponse) {
               console.log(errorResponse)
        }
    });


    // The main view of the application
    var App = Backbone.View.extend({

        // Base the view on an existing element
        el: $('.container'),

        initialize: function(){

            this.listenTo(this.model, 'sync', this.render);

            // Cache these selectors
            // this.total = $('#total span');
            this.list = $('#listing');


        },

        render: function(){

            // Calculate the total order amount by agregating
            // the prices of only the checked elements
            terms.each(function(term){

                this.list.append("<li>"+ term.get('field[brand_name]')+"</li>");

            }, this);

        }
    });

});

2 个答案:

答案 0 :(得分:0)

我认为这里的主要问题是您忘记了实例化您的应用:

new App();

其次,您需要使用正确的结构来引用您的数据:

term.get('hits')

术语是模型,其中包含命中

的数组

最后,您需要在视图中收集集合,并在您的观看集合上监听同步:

this.listenTo(this.collection, 'sync', this.render);

我更新了你的app.js:

$(function(){

var SearchList = Backbone.Collection.extend({
    url: "https://api.nutritionix.com/v1_1/search/taco?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=26952a04&appKey=78e2b31849de080049d26dc6cf4f338c",

    initialize: function(){
        this.bind("reset", function(model, options){
        console.log("Inside event");
        console.log(model);
        });
    }

});

// The main view of the application
var App = Backbone.View.extend({

    // Base the view on an existing element
    el: $('.container'),

    initialize: function () {

        this.collection = new SearchList();

        this.collection.fetch({
            success: function (response, xhr) {
                console.log("Inside success");
                console.log(response.toJSON());
            },
            ERROR: function (errorResponse) {
                console.log(errorResponse)
            }
        });

        this.listenTo(this.collection, 'sync', this.render);

        // Cache these selectors
        // this.total = $('#total span');
        this.list = $('#listing');


    },

    render: function(){

        var context = this;
        this.collection.each(function (term) {
            _.each(term.get('hits'), function (item) {
                context.list.append("<li>" + item.fields.brand_name + "</li>");
            });

        }, this);

    }
});
new App();
});

正确的方法是不要使用 var context = this; ,而是使用视图中的元素。我只是想指出你正确的方向: - )

答案 1 :(得分:0)

我可以在代码中看到一些错误:

  1. url返回的JSON是一个对象,你应该在集合中收取的是数组&#34; hits&#34;那是在对象里面。该过程的逻辑在方法&#34;解析&#34;中定义。该系列。

  2. 声明了该集合。当在视图中指示侦听您的集合时,您将遇到问题,因为在视图可以实例化之前调用fetch方法,因此在执行获取时视图无法实现

  3. 以下是您的code评论。

    $(function(){
    
    var SearchList = Backbone.Collection.extend({
        url: "https://api.nutritionix.com/v1_1/search/taco?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=26952a04&appKey=78e2b31849de080049d26dc6cf4f338c",
    
        initialize: function(){
    
        },
    
        //** 1. Function "parse" is a Backbone function to parse the response properly
        parse:function(response){           
            //** return the array inside response, when returning the array
            //** we left to Backone populate this collection
            return response.hits;
        }
    
    });
    
       // The main view of the application
    var App = Backbone.View.extend({
    
        // Base the view on an existing element
        el: $('.container'),
    
        initialize: function(){
    
            //** 2. the view must listen to an object inside in the view
            //** so we create a new instance of SearchList and save it into model var of the view
            this.model = new SearchList();
            this.model.fetch();
    
            this.listenTo(this.model, 'sync', this.render);
    
            // Cache these selectors
            // this.total = $('#total span');
            this.list = $('#listing');
        },
    
        render: function(){
            //** 2. Continue
            var terms = this.model;
    
            // Calculate the total order amount by agregating
            // the prices of only the checked elements
            terms.each(function(term){
    
                this.list.append("<li>"+ term.get('fields')["brand_name"]+"</li>");
    
            }, this);
    
        }
    });
    
    //** Create an instance of the view to start the program
    var foo = new App();
    

    });

    此致