Backbone.js:运行 并在按键事件中显示 api 结果

Backbone.js: Run and display api results on keydown event

我正在使用 Backbone.js 进行编程 当用户在搜索框中键入查询时,我正在尝试 运行 一个 API 请求。但是,当我输入查询时没有任何反应。

这是我的 JAVASCRIPT:

$(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);
        });
    },
    //** 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({



    initialize: function () {

        this.model = new SearchList();

        this.list = $('#listing');

    },
    el: 'document',

    events: {

    "keydown" : "prepCollection"
    },
    prepCollection: function(){
        var name = $('input').val();
       var newUrl = "https://api.nutritionix.com/v1_1/search/" + name + "?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=26952a04&appKey=78e2b31849de080049d26dc6cf4f338c";
        this.model.set("url", newUrl);
        this.model.fetch({
            success: function (response, xhr) {
                console.log("Inside success");
                console.log(response.toJSON());
            },
            ERROR: function (errorResponse) {
                console.log(errorResponse)
            }
        });
        this.listenTo(this.model, 'sync', this.render);

    },

    render: function(){
        var terms = this.model;
        terms.each(function (term) {
            this.list.append("<li>" + term.get('field')["brand_name"] + "</li>")
        }, this);

    }
});
       var app = new App();
});

这是我的 HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container">
        <h1>Interactive Food Guide</h1>
        <div>
            <input type="text" id="searchBox"> <br/><br/>
        </div>
        <ul id="listing"></ul>
    </div>


    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

    <!-- Backbone and Underscore -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
    <!-- apps functionality -->
    <script src="js/app.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

url 是模型的 属性,不是属性。将属性视为您可能持久保存到服务器的东西。

变化:

this.model.set("url", newUrl);

收件人:

this.model.url = newUrl;

请注意,url 也可以是一个 returns 字符串的函数,并且已经有一个默认函数适用于一些更典型的 REST 情况:http://backbonejs.org/#Model-url

此外 JS 变量和对象键是区分大小写的,所以你的键应该是 error 也不是 ERROR.

完成 运行 项目后,我注意到其他一些错误:

  1. el: 'document' - 这是包括头部在内的整个文档,Backbone 与 body 或其中的内容一起使用。通过将其更改为 el: 'body'
  2. 来解决此问题
  3. 您正在尝试访问 field 属性 - 它实际上称为字段,您可以像这样访问它 term.get('fields').brand_name

其他奖励修复:在添加新结果之前清除列表,_.throttle prepCollection 这样如果字母输入速度很快,那么它只会进行 2 次搜索(一次在开头,一次在结尾输入结束)。更改为 _.debounce 以仅在输入末尾进行一次搜索。

Fiddle: http://jsfiddle.net/ferahl/2nLezvmg/1/