JavaScript Fundamentals with Angular and Lodash
-
Upload
bret-little -
Category
Engineering
-
view
338 -
download
1
Transcript of 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
JavaScript scope is not $scopeJavaScript scope is not $scope
Just because you can, doesn't mean you should
Caution!Caution!
<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 }]
<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'
<div ng-repeat="i in 10 | lodash:'range'"> {{ $index }}</div>
_.range(10);// → [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<span>{{name | lodash:'capitalize'}}</span>
$scope.name = 'alfred';
<span>Alfred</span>
<span class='{{dynamicClassName | lodash:'kebabCase'}}'> Hello</span>
$scope.dynamicClass = 'someDyanmicClassName';
<span class='some-dyanmic-class-name'>Hello</span>
<span> {{value | lodash:'padLeft':10:0}}</span>
$scope.value = 123;
<span>0000000123</span>
<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>
<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
angular.module('myApp') .filter('lodash', function() { return function(input, method) {
var args = [input].concat( Array.prototype.slice.call(arguments, 2) );
return _[method].apply(_, args); } });
JavaScript FundamentalsJavaScript Fundamentals
Higher-order FunctionsHigher-order Functions
ClosuresClosures
Scope & ContextScope & Context
Dynamic function invocationDynamic function invocation
ArgumentsArguments
JavaScript 2015JavaScript 2015
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
var something = 1;
function run() { var something = 2; console.log(something);}
run();
console.log(something);
-> 2-> 1
var something = 1;
function run() { if (!something) { var something = 2; } console.log(something);}run();
-> 2
JavaScript Variable HoistingJavaScript Variable Hoisting
angular.module('myApp') .filter('lodash', function() { return function(input, method) {
var args = [input].concat( Array.prototype.slice.call(arguments, 2) );
return _[method].apply(_, args); } });
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
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
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
function makeFunc() { var name = "Pangolin"; function displayName() { debugger; alert(name); } return displayName;};
var myFunc = makeFunc();myFunc();
ClosuresClosures
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
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); } });
angular.module('myApp') .filter('lodash', function() { return function(input, method) {
var args = [input].concat( Array.prototype.slice.call(arguments, 2) );
return _[method].apply(_, args); } });
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
angular.module('myApp') .filter('lodash', function() { return function(input, method) {
var args = [input].concat( Array.prototype.slice.call(arguments, 2) );
return _[method].apply(_, args); } });
angular.module('myApp') .filter('lodash', function() { return function(input, method) {
var args = [input].concat( Array.prototype.slice.call(arguments, 2) );
return _[method].apply(_, args); } });
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
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
Object ContextObject Context
var obj = { foo: function(){ return this; }};
obj.foo();
obj.foo() === obj; // true
Constructor ContextConstructor Context
function Legate(rank) { this.rank = rank;}
var legate = new Legate(100);console.log(legate.rank);
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
Function.prototype.bindFunction.prototype.bind
var myWidget = { type: 'myAwesomeWidget',
clickCallback: function() { console.log(this.type); }}
document.getElementById('submit').addEventListener( 'click', myWidget.clickCallback.bind(myWidget));
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
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.
angular.module('myApp') .filter('lodash', function() { return function(input, method) {
var args = [input].concat( Array.prototype.slice.call(arguments, 2) );
return _[method].apply(_, args); } });
import _ from 'lodash';import angular from 'angular';
angular.module('app') .filter('lodash', function() { return (input, method, ...args) => ( _[method].apply(_, [input, ...args]) ) });
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