如何使用 backbone.js 删除此项目中的元素?

How can I remove elements in this project with backbone.js?

我正在 Backbone.js 中制作一个项目 在这个项目中,我可以单击搜索词以将它们添加到跟踪的食物列表中。之后,我可以选择将食物添加到餐中或移除食物。当我在跟踪的食物列表中的食物项目上单击删除时,我无法让删除按钮工作。

这是一个 JS fiddle 和我的代码:https://jsfiddle.net/Tiquismiquis/2nLezvmg/11/

这是我的JAVASCRIPT:

$(function(){

var Food = Backbone.Model.extend({

        defaults:{
            title: 'no information found',
            brand: 'no information found',
            calories: 'no information found',
            day: 'all'
        }
});

var AllFoods = Backbone.Collection.extend({model: Food});



var SearchList = Backbone.Collection.extend({

    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({

    el: 'body',

    events: {
    "input #searchBox" : "prepCollection",
    "click #listing li" : "track",
    "click #add": "addClicked",
    "click .destroy": "destroy"
    },

    initialize: function () {

        this.model = new SearchList();
        this.foods = new AllFoods();
        this.prepCollection =_.debounce(this.prepCollection, 1000);
        this.$total = $('#total span');
        this.$list = $('#listing');
        this.$tracked =$('#tracked');
        this.model.on('destroy', this.remove, this);


    },

    addClicked: function(e) {
        var $target = $(e.currentTarget).parent();
       var $selected = $target.find('#mySelect').val();

        var location = $target.attr('data-id');
        var currentFood = this.foods.get(location);


        switch($selected) {
            case 'Breakfast':
                $('#breakfast').append(currentFood.get('html'));
                break;
            case 'Lunch':
                $('#lunch').append(currentFood.get('html'));
                break;
            case 'Dinner':
                $('#dinner').append(currentFood.get('html'));
                break;
            case 'Snack':
                $('#snack').append(currentFood.get('html'));
                break;
            default:
                alert("Error: try again");
        }




    },

    destroy: function () {
       this.model.destroy();
    },

    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,brand_name,item_id,nf_calories&appId=26952a04&appKey=33b9262901d0068d4895736b5af19805";

       if (name == ""){
        this.$list.html("")
       }
       else{
        this.model.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);
       }

    },

    track: function(e){


        this.listenTo(this.foods, 'add', this.renderfoods);

        var $target = $(e.currentTarget);
        var item_name = $target.attr('data-name');
        var brand_name = $target.attr('data-brand');
        var calorieString = $target.attr('data-calories');
        var calorieAmt = parseFloat(calorieString);
        var foodid = $target.attr('data-id');

        var chooseday ='<form>What meal was this part of?: <select id="mySelect"> <option value="Breakfast">Breakfast</option><option value="Lunch">Lunch</option><option value="Dinner">Dinner</option><option value="Snack">Snack</option></select></form><button id="add" type="button">Add To Meal</button><button class="destroy" type="button">Remove</button>';

        var trackedhtml = '<li'+' data-id='+'"'+ foodid +'"'+'>' +"<strong>" + item_name + '</strong>'+ ' ('+ brand_name + ')'+' - '+ calorieAmt + ' Calories' + chooseday + '</li>'


        this.foods.add(new Food({ id: foodid, title: item_name, brand: brand_name, calories: calorieAmt, html: trackedhtml}));

    },

    renderfoods: function() {
        var total = 0;
        var trackedhtml = '';

       this.foods.each(function(food){
            trackedhtml = trackedhtml + food.get('html');
            total += food.get('calories');
       },this)
        this.$tracked.html(trackedhtml);
         this.$total.html(total);



    },

    render: function(){
        var terms = this.model;
        var wordhtml = '';
        terms.each(function (term) {
            wordhtml = wordhtml + '<li' + ' data-id=' + '"' + term.get('_id') +'"'+' data-name=' + '"' + term.get('fields')['item_name'] +'"'+ ' data-brand='+'"' + term.get('fields')['brand_name'] + '"' + ' data-calories='+ '"' + term.get('fields')['nf_calories'] + '"' + '>' +"<strong>" + term.get('fields')["item_name"] + '</strong>'+ ' ('+ term.get('fields')["brand_name"] + ')'+' - '+ term.get('fields')["nf_calories"] + ' Calories' + '</li>'
        }, this);
        this.$list.html(wordhtml);

    }
});
       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>Food Guide App</title>

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

            <div class="col-xs-6">
                <h1>Foods Tracked</h1>
                <ul id="tracked"></ul>
                <p id="total"><strong> total calories:</strong> <span>0</span></p>
            </div>
        </div>
        <div class="row">
            <div class=" text-center col-xs-12">
                <ul id="breakfast"></ul>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12">
                <ul id="lunch"></ul>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12">
                <ul id="dinner"></ul>
            </div>
        </div>

        <div class="row">
            <div class="col-xs-12">
                <ul id="snack"></ul>
            </div>
            <!-- TODO: Put food pyramid here -->
        </div>


    </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>

代码不是 backbone 风格,但如果你想从 DOM 中删除,你可以简单地做:

destroy: function(e){
  var $li = $(e.currentTarget).closest('li')
  this.foods.remove($li.attr('data-id'));
  $li.remove();
  //recalculate calories & stuff
}

工作 fiddle - https://jsfiddle.net/nitincool4urchat/2nLezvmg/15/