簡體   English   中英

如何使用骨干.js刪除該項目中的元素?

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

我正在Backbone.js中創建一個項目。在這個項目中,我可以單擊搜索詞以將其添加到跟蹤的食物列表中。 之后,我可以選擇將食物添加到餐中或將食物移除。 在跟蹤的食物列表中單擊某個食物上的刪除時,我無法使該刪除按鈕起作用。

這是一個帶有我的代碼的JS小提琴: 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>

該代碼不是主干樣式,但是如果您要從DOM中刪除,則只需執行以下操作:

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

工作小提琴-https: //jsfiddle.net/nitincool4urchat/2nLezvmg/15/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM