运行并显示keydown事件的api结果

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

本文关键字:api 结果 事件 keydown 显示 运行      更新时间:2023-09-26

我正在用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也可以是一个返回字符串的函数,并且已经有一个默认函数可以用于一些更典型的REST情况:http://backbonejs.org/#Model-url

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

运行项目后,我注意到其他一些事情是错误的:

  1. el: 'document' -这是整个文档,包括头部,主干工作与body或它里面的东西。修改为el: 'body'
  2. 您正在尝试访问field属性-它实际上被称为字段,您可以像这样访问term.get('fields').brand_name

其他额外的修复:清除列表之前附加新的结果,_.throttle prepCollection,这样,如果字母被快速键入,那么它将只做2个搜索(一个在开始,一个在输入的结束)。将_.debounce更改为只在输入的末尾进行一次搜索。

小提琴:http://jsfiddle.net/ferahl/2nLezvmg/1/