forked from sf-wdi-19-20/modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
72 lines (57 loc) · 1.89 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
$(function() {
// form to create a new pet
var $newPet = $('#new-pet');
// element to hold our list of pets
var $petsList = $('#pets-list');
// pets template (this is a function)
var petsTemplate = _.template($('#pets-template').html());
console.log("this is the compiled template");
console.log(petsTemplate);
// start with seed data
var pets = [
{name: "Sprinkles", species: "cat"},
{name: "Bagel", species: "dog"},
{name: "Fluffy", species: "dinosaur"}
];
// append our existing pets (from seed data) to `$petsList`
_.each(pets, function (pet, index) {
var $pet = $(petsTemplate(pet));
console.log($pet);
// $pet.attr('data-index', index);
$petsList.append($pet);
});
// submit form to create a new pet
$newPet.on('submit', function(event) {
event.preventDefault();
// create new pet object from form data
var petName = $('#pet-name').val();
var petSpecies = $('#pet-species').val();
var petData = {name: petName, species: petSpecies};
// store our new pet in the `pets` array
pets.push(petData);
console.log(pets);
var index = pets.indexOf(petData);
// append new pet to `$petsList`
var $pet = $(petsTemplate(petData));
$pet.attr('data-index', index);
$petsList.append($pet);
// reset the form and add autofocus back to first input
$newPet[0].reset();
$('#pet-name').focus();
});
// remove pets from model and view
$petsList.on("click", ".delete", function () {
var $pet = $(this).closest(".pet");
var index = $pet.attr('data-index');
// remove pet from the `pets` array (model)
pets.splice(index, 1);
console.log(pets);
// remove pet from the DOM (view)
$pet.remove();
// reset indexes in DOM to match `pets` array
// $.each loops through DOM elements
$('.pet').each(function(index) {
$(this).attr('data-index', index);
});
});
});