Created
April 14, 2014 21:42
-
-
Save abahler/10684720 to your computer and use it in GitHub Desktop.
Pulling a to-do list from a JSON file using the map( ) function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Code lesson from "Learning Web App Development" by Semmy Purewal | |
// Chapter 5: "The Bridge" | |
// Need to call getJSON before we call main() | |
var main = function (toDoObjects) { | |
// Disallow bad aspects of JS by running in strict mode | |
"use strict"; | |
// Now main has access to our toDo list! | |
// But let's reformat our JSON so we can easily deal with it | |
var toDos = toDoObjects.map(function (toDo) { | |
// Return the description of this object | |
return toDo.description; | |
}); | |
// All our old code from Chapter 4, Example 3 should work as it did before. | |
$(".tabs a span").toArray().forEach(function(el){ | |
// Create click handler for the element | |
$(el).click(function(){ | |
var $element = $(el); | |
var $content; | |
var $input; | |
var $button; | |
var i; | |
$(".tabs a span").removeClass("active"); | |
$element.addClass("active"); | |
$(".content").empty(); | |
if ( $element.parent().is(":nth-child(1)") ) { | |
// Use a FOR loop to iterate in reverse. First create the ul element | |
$content = $("<ul>"); | |
// Then build the list of <li>'s, starting the counter at the length. | |
for (i = toDos.length - 1; i >= 0; i--) { | |
$content.append($("<li>").text(toDos[i])); | |
} | |
} else if ( $element.parent().is(":nth-child(2)") ) { | |
// Includes the closing tag | |
$content = $("<ul>"); | |
toDos.forEach(function (todo) { | |
$content.append($("<li>").text(todo)); | |
}); | |
} else if ( $element.parent().is(":nth-child(3)") ) { | |
// Create your elements to mimic what was done earlier in this chapter | |
$input = $("<input>").attr("type", "text").attr("placeholder", "Enter a new to-do..."); | |
$button = $("<button>").text("+"); | |
$button.click(function(){ | |
if ($input.val() !== "") { | |
toDos.push($input.val()); | |
$input.val(""); | |
} | |
}); | |
$content = $("<div>").append($input).append($button); | |
} | |
$(".content").append($content); | |
return false; | |
}); | |
}); | |
/* | |
Need to 'fake' a click to append content in the first tab. | |
Without this, you'd need to explicitly click on the first tab when arriving to the page. | |
*/ | |
$(".tabs a:first-child span").trigger("click"); | |
}; // end main() | |
$(document).ready(function () { | |
$.getJSON("todos.json", function (toDoObjects) { | |
// call main() with the to-dos as an argument | |
main(toDoObjects); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment