JavaScript Fundamentals with Angular and Lodash

39
JavaScript Fundamentals JavaScript Fundamentals with Angular and Lodash with Angular and Lodash Bret Little - @little_bret blittle.github.io/blog/ http://slides.com/bretlittle/js-fundamentals-angular-lodash

Transcript of JavaScript Fundamentals with Angular and Lodash

Page 1: JavaScript Fundamentals with Angular and Lodash

JavaScript FundamentalsJavaScript Fundamentalswith Angular and Lodashwith Angular and Lodash

Bret Little - @little_bret

blittle.github.io/blog/

http://slides.com/bretlittle/js-fundamentals-angular-lodash

Page 2: JavaScript Fundamentals with Angular and Lodash

JavaScript scope is not $scopeJavaScript scope is not $scope

Page 3: JavaScript Fundamentals with Angular and Lodash

Just because you can, doesn't mean you should

Caution!Caution!

Page 4: JavaScript Fundamentals with Angular and Lodash

<div class='active-users' ng-repeat='user in users | lodash:"filter":{active: true}'> {{ user.name }}</div>

var users = [ { 'name': 'barney', 'age': 36, 'active': true }, { 'name': 'fred', 'age': 40, 'active': false }]

_.filter(users, { 'active': true })// returns [{ 'name': 'barney', 'age': 36, 'active': true }]

Page 5: JavaScript Fundamentals with Angular and Lodash

<div class='selected-user'> {{ users | lodash:'findWhere':{active: true, age: 36} | lodash:'result':'name' }}</div>

var users = [ { 'name': 'barney', 'age': 36, 'active': true }, { 'name': 'fred', 'age': 40, 'active': false }]

_.result( _.findWhere(users, { 'active': true, 'age': 36 }), 'name')

// returns 'barney'

Page 6: JavaScript Fundamentals with Angular and Lodash

<div ng-repeat="i in 10 | lodash:'range'"> {{ $index }}</div>

_.range(10);// → [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Page 7: JavaScript Fundamentals with Angular and Lodash

<span>{{name | lodash:'capitalize'}}</span>

$scope.name = 'alfred';

<span>Alfred</span>

Page 8: JavaScript Fundamentals with Angular and Lodash

<span class='{{dynamicClassName | lodash:'kebabCase'}}'> Hello</span>

$scope.dynamicClass = 'someDyanmicClassName';

<span class='some-dyanmic-class-name'>Hello</span>

Page 9: JavaScript Fundamentals with Angular and Lodash

<span> {{value | lodash:'padLeft':10:0}}</span>

$scope.value = 123;

<span>0000000123</span>

Page 10: JavaScript Fundamentals with Angular and Lodash

<span> {{longVal | lodash:'trunc':28}}</span>

$scope.longVal = 'Crocodiles have the most acidic stomachof any vertebrate. They can easily digest bones, hoovesand horns.';

<span>Crocodiles have the most ...</span>

Page 11: JavaScript Fundamentals with Angular and Lodash

<div ng-repeat='user in users | lodash :"slice":(page * amountPerPage) :((page + 1) * amountPerPage)'> {{user.name}}</div><button ng-click='page = page - 1'>Previous</button><button ng-click='page = page + 1'>Next</button>

http://output.jsbin.com/zesuhuhttp://output.jsbin.com/zesuhu

Page 12: JavaScript Fundamentals with Angular and Lodash

angular.module('myApp') .filter('lodash', function() { return function(input, method) {

var args = [input].concat( Array.prototype.slice.call(arguments, 2) );

return _[method].apply(_, args); } });

Page 13: JavaScript Fundamentals with Angular and Lodash

JavaScript FundamentalsJavaScript Fundamentals

Higher-order FunctionsHigher-order Functions

ClosuresClosures

Scope & ContextScope & Context

Dynamic function invocationDynamic function invocation

ArgumentsArguments

JavaScript 2015JavaScript 2015

Page 14: JavaScript Fundamentals with Angular and Lodash

JavaScript does not have block scope;JavaScript does not have block scope;

it has lexical scope.it has lexical scope.

var something = 1;{ var something = 2;}console.log(something);

-> 2

Page 15: JavaScript Fundamentals with Angular and Lodash

var something = 1;

function run() { var something = 2; console.log(something);}

run();

console.log(something);

-> 2-> 1

Page 16: JavaScript Fundamentals with Angular and Lodash

var something = 1;

function run() { if (!something) { var something = 2; } console.log(something);}run();

-> 2

JavaScript Variable HoistingJavaScript Variable Hoisting

Page 17: JavaScript Fundamentals with Angular and Lodash

angular.module('myApp') .filter('lodash', function() { return function(input, method) {

var args = [input].concat( Array.prototype.slice.call(arguments, 2) );

return _[method].apply(_, args); } });

Page 18: JavaScript Fundamentals with Angular and Lodash

Higher-order FunctionsHigher-order Functions

"Functions that operate on other"Functions that operate on otherfunctions, either by taking them asfunctions, either by taking them asarguments or by returning them"arguments or by returning them"

http://eloquentjavascript.net/05_higher_order.htmlhttp://eloquentjavascript.net/05_higher_order.html

Page 19: JavaScript Fundamentals with Angular and Lodash

function greaterThan(n) { return function(m) { return m > n; };}

var greaterThan10 = greaterThan(10);

console.log(greaterThan10(11));// -> true

Higher-order FunctionsHigher-order Functions

note note nn is still available within is still available within

the returned functionthe returned function

Page 20: JavaScript Fundamentals with Angular and Lodash

ClosuresClosures

"A closure is a special kind of object that"A closure is a special kind of object thatcombines two things: a function, andcombines two things: a function, and

the environment in which that functionthe environment in which that functionwas created."was created."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closureshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Page 21: JavaScript Fundamentals with Angular and Lodash

function makeFunc() { var name = "Pangolin"; function displayName() { debugger; alert(name); } return displayName;};

var myFunc = makeFunc();myFunc();

ClosuresClosures

Page 22: JavaScript Fundamentals with Angular and Lodash

var counter = (function() { var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { increment: function() { changeBy(1); }, decrement: function() { changeBy(-1); }, value: function() { return privateCounter; } }; })();

console.log(counter.value()); // logs 0counter.increment();console.log(counter.value()); // logs 1

Practical ClosuresPractical Closures

Page 23: JavaScript Fundamentals with Angular and Lodash

angular.module('myApp') .filter('lodash', function(someService) { return function(input, method) {

var args = [input].concat( Array.prototype.slice.call(arguments, 2) );

return _[method].apply(_, args); } });

Page 24: JavaScript Fundamentals with Angular and Lodash

angular.module('myApp') .filter('lodash', function() { return function(input, method) {

var args = [input].concat( Array.prototype.slice.call(arguments, 2) );

return _[method].apply(_, args); } });

Page 25: JavaScript Fundamentals with Angular and Lodash

function sayHello() { for (var i = 0, iLength = arguments.length; i < iLength; i++) { console.log('Hello', arguments[i]); }}

sayHello('Chester Nimitz', 'Raymond Spruance');

Dynamic ArgumentsDynamic Arguments

-> Hello Chester Nimitz-> Hello Raymond Spruance

Page 26: JavaScript Fundamentals with Angular and Lodash

angular.module('myApp') .filter('lodash', function() { return function(input, method) {

var args = [input].concat( Array.prototype.slice.call(arguments, 2) );

return _[method].apply(_, args); } });

Page 27: JavaScript Fundamentals with Angular and Lodash

angular.module('myApp') .filter('lodash', function() { return function(input, method) {

var args = [input].concat( Array.prototype.slice.call(arguments, 2) );

return _[method].apply(_, args); } });

Page 28: JavaScript Fundamentals with Angular and Lodash

JavaScript ContextJavaScript Context

The environment in which a functionThe environment in which a functionexecutes.executes.

the the this this keywordkeyword

Context is most often determined byContext is most often determined byhow a function is invokedhow a function is invoked

Page 29: JavaScript Fundamentals with Angular and Lodash

Function Statement ContextFunction Statement Context

function billMe() { console.log(this);

function sendPayment() { console.log(this); } sendPayment();}

billMe();

The context for forThe context for for

function statement isfunction statement is

the global objectthe global object

Page 30: JavaScript Fundamentals with Angular and Lodash

Object ContextObject Context

var obj = { foo: function(){ return this; }};

obj.foo();

obj.foo() === obj; // true

Page 31: JavaScript Fundamentals with Angular and Lodash

Constructor ContextConstructor Context

function Legate(rank) { this.rank = rank;}

var legate = new Legate(100);console.log(legate.rank);

Page 32: JavaScript Fundamentals with Angular and Lodash

Dynamic Function ContextDynamic Function Context

function add(c, d){ return this.a + this.b + c + d;}

var o = {a:1, b:3};

add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

Page 33: JavaScript Fundamentals with Angular and Lodash

Function.prototype.bindFunction.prototype.bind

var myWidget = { type: 'myAwesomeWidget',

clickCallback: function() { console.log(this.type); }}

document.getElementById('submit').addEventListener( 'click', myWidget.clickCallback.bind(myWidget));

Page 34: JavaScript Fundamentals with Angular and Lodash

jQueryjQuery

$( "li" ).each(function myIterator(index) { $( this ).text();});

jQuery controls the context of the callbackjQuery controls the context of the callback

and and thisthis becomes each becomes each lili element element

Page 35: JavaScript Fundamentals with Angular and Lodash

AngularAngular

angular.module('app') .controller('Customers', function() { var vm = this; vm.title = 'Customers'; });

Angular controls the context of the controller.Angular controls the context of the controller.

With With controllerAscontrollerAs the context the context becomesbecomes

bound to the template.bound to the template.

Page 36: JavaScript Fundamentals with Angular and Lodash

angular.module('myApp') .filter('lodash', function() { return function(input, method) {

var args = [input].concat( Array.prototype.slice.call(arguments, 2) );

return _[method].apply(_, args); } });

Page 37: JavaScript Fundamentals with Angular and Lodash

import _ from 'lodash';import angular from 'angular';

angular.module('app') .filter('lodash', function() { return (input, method, ...args) => ( _[method].apply(_, [input, ...args]) ) });

Page 38: JavaScript Fundamentals with Angular and Lodash

1. http://ryanmorr.com/understanding-scope-and-context-in-javascript/

2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

4. http://eloquentjavascript.net

5. JS 2015-2016 - https://babeljs.io/

6. Axel Rauschmayer - http://www.2ality.com/

ResourcesResources

Page 39: JavaScript Fundamentals with Angular and Lodash