On Github rovolution / modern-web-dev
<!DOCTYPE html> <html ng-app> <head> <script> alert("Running this JavaScript!") //Immediately triggers an alert box when the page is loaded </script> <script type="text/javascript" src="main.js"></script> <!-- Loads in an external script --> </head> <body> </body> </html>
/* Variable Initialization/Declaration */ var myNumber = 5; var myString = "myString"; var myBoolean = false; /* Print Output To Debug Console */ console.log("my number is " + myNumber); // Output: "my variable is 5" console.log("my string is " + myString); // Output: "my string is myString" console.log( typeof myNumber ); // Output: "number" console.log( typeof myString ); // Output: "string" console.log( typeof myBoolean ); // Output: "boolean"
/* Object Initialization/Declaration */ var obj = { "prop1" : 5, prop2 : "value of property 2" }; obj.prop3 = false; // Add a property to an already defined object console.log( obj.prop1 ); // Output: 5 console.log( obj["prop2"] ); // Output: "value of property 2" console.log( typeof obj ); // Output: "object"
/* Array Initialization/Declaration */ var myArray = [1, 3, 4]; myArray.push(5); // Appends 5 to myArray myArray.pop(); // Remove the last value in the Array and returns it myArray.length; // Returns the number of elements in the Array /* Array is a type of object */ console.log( typeof myArray ); // Output: "object"
/* Basic Comparison Operators */ var a = 1; var b = 2; console.log( a > b ); // Output: false console.log( a < b); // Output: true console.log( a <= 1 ); // Output: true console.log( a >= 1 ); // Output: true /* Strict vs Loose Type Checking */ console.log( 0 == false ); // Output: true (loose check) console.log( 0 === false ); // Output: false (strict check) console.log( 0 != false ); // Output: false (loose check) console.log( 0 !== false ); // Output: true (strict check)
/* If-Else Statement */ var age = 15; if(age < 21) { console.log("You CANNOT drink legally in the United States!"); console.log("Go drink a soda!"); } else if(age === 21) { console.log("Its your first of being able to drink alcohol legally!"); console.log("Be responsible!"); } else { console.log("You are older than 21."); console.log("Still be responsible!"); } // Output: // console.log("You CANNOT drink legally in the United States!"); // console.log("Go drink a soda!"); /* Ternary Statement */ var val = (0 <= 15) ? "less than or equal to" : "greater than"; console.log(val); // Output: "less than or equal to"
/* For loop */ for(var i = 0; i < 5; i++) { console.log(i); } /* Output: prints the numbers 0-4 */ /* While loop */ var i = 0; while (i<5) { console.log(i); i++; } /* Output: prints the numbers 0-4 */ /* Loop through object properties */ var myObject = { prop1 : 1, prop2 : 2, prop3 : 3 }; for(var key in myObject) { console.log("key: " + key + ", value: " + myObject[key]); } /* Output: prints each key, value pair "key: prop1, value: 1" "key: prop2, value: 2" "key: prop3, value: 3" */
/* Function Initialization/Declaration */ function myFunction() { if(arguments[0]) { console.log("This is my function with arg " + arguments[0]); } else { console.log("This is my function!"); } } myFunction(); // Output: "This is my function!" myFunction(1); // Output: "This is my function with arg 1" var mySecondFunction = function(arg) { console.log("This is my other function with arg " + arg); }; mySecondFunction(2); // Output: "This is my other function with arg 2" (function() { console.log("Immediately Invoked Function Expression (IIFE)"); })() // Output: "Immediately Invoked Function Expression (IIFE)" // Can add functions as properties to an object var myCoolObject = {}; myCoolObject.printFoo = function() { console.log("Foo"); };
var user = { name : "Al Grasso", printName : function() { console.log("Username: " + this.name); } } user.printName(); /* Output: "Username: Al Grasso" */
/* Base prototype */ var fruit = { "color" : null, "shape" : null, "price" : 1.50 } /* Orange constructor */ function Orange() { this.color = "orange"; this.shape = "round"; this.makeJuice = function() { console.log("Made orange juice!"); } } Orange.prototype = fruit; /* Bananas constructor */ function Banana() { this.color = "yellow"; this.shape = "long curving cylinder"; } Banana.prototype = fruit; var myOrange = new Orange(); var myBanana = new Banana(); console.log(myOrange.color); // Output: "orange" console.log(myBanana.color); // Output: "yellow" console.log(myOrange.price); // Output: 1.50 console.log(myBanana.price); // Output: 1.50 myOrange.makeJuice(); // Output: "Made orange juice!" myBanana.makeJuice(); // TypeError: Object #<Banana> has no method 'makeJuice' console.log( myOrange instanceof Orange ) // Output: true console.log( myOrange instanceof Object ) // Output: true console.log( myOrange instanceof Banana ) // Output: false
var a = 1; function funcOne() { a = 2; } funcOne(); console.log(a); // Output: 2 var b = 1; function funcTwo() { var b = 2; } funcTwo(); console.log(b); // Output: 1 function funcThree() { function funcFour() { console.log("Four"); } funcFour(); } funcThree(); // Output: "Four" funcFour(); // ReferenceError: funcFour is not defined
function printA() { console.log(a); var a = 1; } printA(); // Output: Any guesses? Try inputting it into the console printNumber(4); // Output: "The number is 4" function printNumber(num) { console.log("The number is " + num); } printFoo(4); // TypeError: undefined is not a function var printFoo = function(foo) { console.log(foo); }
function throwError(message) { throw Error("ERROR: " + message); } try { console.log("This will print to the console"); throwError("You've got problems!"); console.log("This will not print to the console"); } catch(error) { console.log(error.message); // Output: "You've got problems!" }
/* Select the HTML element with id = element1 & bind a click event to it */ $("#element1").on('click', function(e) { e.preventDefault(); console.log("clicked on element1!"); }); /* Unbind the 'click' event from all elements with the class tag 'listing' */ $(".listing").off('click');
{ "key1" : 1, "key2" : "two", "key3" : [1, { "key" : "value" }], "key4" : true }
[ { "id" : 0, "username" : "agrasso", "email" : "agrasso@mitre.org", }, { "id" : 1, "username" : "rkalkur", "email" : "rkalkur@mitre.org", } ]
{ "message" : "User rkalkur was deleted!" }
var Employee = Backbone.Model.extend({}); /* Create instance of Employee */ var ceo = new Employee({ name : "Al Grasso" });
var EmployeeList = Backbone.Collection.extend({ model: Employee, url: '/employees' }); /* Create instance of EmployeeList */ var employees = new EmployeeList(); /* Bind a callback fn to employee's add event */ employees.bind('add', function() { console.log("Employee was added to employees"); }); /* Fetch list of all employees from server */ employees.fetch(); // Sends HTTP request - GET '/employees'
var EmployeeListView = Backbone.View.extend({ events : { "click li" : "triggerEmployeeClickedMsg" // View event binding }, initialize : function() { this.listenTo(this.collection, 'reset', this.render); }, render : function() { var thisView = this; // Store view context in thisView thisView.$el.empty(); // Clear the existing list // Add each employee to the list _.each(thisView.collection.models, function(employee) { var employeeListing = "<li>" + employee.get('name') + "</li>"; thisView.$el.append(employeeListing); }); }, triggerEmployeeClickedMsg : function() { alert("Employee listing was clicked!"); } }); /* Create instance of EmployeeListView */ var employeeListView = new EmployeeListView({ el : 'ul#employeeList' // DOM element that view will correspond to });
Implementations:
<script id="employeeListingTemplate" type="text/template"> <li class="employee-listing"> <div class="name"><@= name @></div> <!-- Outputs the 'name' property of the object passed to the template rendering --> <div class="email"><@= email @></div> <ul class="projects"> <@ _.each(projects, function(project) { @> <!-- Can embed code into template if need be --> <li><@= project.name @></li> <@ }) @> </ul> </li> </script>
/* JS Code */ var employeeListingTemplate = $("employeeListingTemplate").html(), employeeObject = { "name" : "Frank Johnson", "email" : "fjohnson@superdupercorp.org" "projects" : [ { "name" : "The Super Duper Project" }, { "name" : "The TOP SECRET Super Duper Project" } ] }, compiledTemplate = _.template(employeeListingTemplate, employeeObject); // NOTE: You can now append 'compiledTemplate' to any part of your DOM
<!doctype html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> </head> <body ng-controller="UsersCtrl"> <ul> <li ng-repeat="user in users"> <div class="name">{{ user.name }}</div> <div class="email">{{ user.email }}</div> </li> </ul> </body> </html>
function UsersCtrl($scope, Users) { $scope.users = Users.query(); }
$resource('/users');
Steep learning curve!