Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Saturday, July 6, 2013

Debugging AngularJS Source with WebStorm

The great thing about AngularJS is that it comes with a very full featured test suite. This means that you can use tests if you:

  • want to play around and try to add new features in AngularJS 
  • or try to understand AngularJS internals
This is my quick guide on the steps I had to carry out to debug the code I downloaded. I'll be using windows and webstorm. Some of these are pretty standard steps if you know nodejs + karma but should be helpful nonetheless. All commands should be run the from main AngularJS folder. The git root folder (whatever you want to call it). Not the src folder. In particular the folder where you have package.json , Gruntfile.js, karma-config-* files.

Get AngularJS source

Download (git clone) from https://github.com/angular/angular.js

Make sure you have NodeJS installed 


Install the pre requisite global NodeJS packages

You need grunt and karma. Pretty painless after you have node: 
npm install -g grunt
npm install -g karma 

Download AngularJS prerequisite NodeJS packages

Run:
npm install

from the main AngularJS folder. This will basically read package.json and download any prerequisites. 

Setup your CHROME_BIN

I have this environment variable pointing to my chrome.exe (not chrome canary).

Build Angular

Build AngularJS (required if you want to run the tests):
grunt build

Run the karma server

Simple command: 
karma start karma-modules.conf.js --no-single-run --auto-watch --reporters dots
This should start chrome + run the tests (module tests in this case as I ran karma-modules.conf.js) 

Leave this command (i.e. karma) running in the background.

Now setup debug environment in WebStorm

Create a new WebStorm project from your AngularJS folder. Edit your run configurations: 
(Don't mind that I already have debug karma setup, you will not). 

Add a remote debug config: 

Add set it up as follows. Call it whatever you want but url to open and remote url are important: 
http://localhost:9876/debug.html
http://localhost:9876/base


Great. Now set a breakpoint, Start debugging and watch the magic happen. 

Thursday, June 27, 2013

AngularJS minification

Just downloaded angular source. Its no secret that AngularJS uses google closure tools. In case you are wondering how here is the grunt config:


This uses the custom grunt task as follows:

And the contents of the grunt task are just calling google closure compiler with proper arguments:


Friday, June 7, 2013

Why use semicolons in JavaScript

I always use semicolons even though they are optional in JavaScript. A key reason for me is convention and javascript minification (although closure compiler will rewrite your js with semicolons inserted). But if you want to know what else could go wrong even if you do not do minification there is actually only one case. When a line starts with `(` it should have a semicolon before it.

An Example

When you have an immediately executed function to create a new scope:

// define a function with assignment
var fn = function () {
   //...
} // semicolon missing at this line

// then execute some code inside a new scope
(function () {
    //...
})();

Will get interpreted as :

var fn = function () {
    //...
}(function () {
    //...
})();

The second function will fail with a "... is not a function" error at runtime.

Another example 

// careful: will break
a = b + c
(d + e).print()
// Will get interpreted as:
a = b + c(d + e).print();

Alternate Solution

 A potential solution if you want to be a cowboy and not use semicolons everywhere is to use a semicolon before ‘(‘:

; (d + e).print()

Its also potentially a good idea when your file starts with '(' since if someone (who does not use semicolons) does concatenation of your file it might become a problem. 

An example was from this answer: http://stackoverflow.com/a/1169596/390330

Thursday, June 6, 2013

Inspect all the event handlers on a DOM Element


Here’s how chrome Developer Tools make it super simple. Just inspect an element and look inside the Event Listeners section as shown:


Expand any event and you can see what element level the event is handled on e.g. here blur is handled on document as well as the div:

You can even jump to the function body (this is a minified file so it’s all on line 1) by clicking on the filename

As an aside: there is no way to do this in your own code http://stackoverflow.com/a/2623352/390330

Tuesday, May 28, 2013

Trick question : Closures in Javascript

Closures are one of the most powerful features of the Javascript language. If there is one thing that makes JS so versatile, it has to be closures. But they can be tricky if you do not understand:
  1. Closures capture the variable not just its value.
  2. Scope only changes using functions in Javascript.
So the question, What does the following code print:

var funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

The intuitive answer is 0,1,2,3…9 . However that is not the case. This is because each function in setup captured the variable i and not its value. When the for loop finished the variable i has a value 10 and therefore all functions print out 10. You now understand what (1) means. 

Now let’s make these functions print 0,1,2,3…9. The solution would be to create a new variable within the scope of the for loop so that each function gets a new variable. Now the only way to create a new scope is using a function (2). Lets say you don't know this and try the following which will not work. It will print 9 instead of 10 however since that is the last value that gets assigned to foo:

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    var foo = i;
    funcs.push(function () {
        console.log(foo)
    });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

To fix this we use the concept of immediately executing functions i.e. we declare a function (to create a new scope) and immediately execute it (to fall into that scope). The following will work. :

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    (function () {
        var foo = i;
        funcs.push(function () {
            console.log(foo)
        });
    })();
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

You now understand (2). You can find the code here : http://jsfiddle.net/basarat/U9brW/

As a aside you might think the following is a good idea (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {       
    funcs.push(function () {
        var foo = i;
        console.log(foo)
    });   
}

But it’s actually no different than (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}

Because the only variable that is captured by the function is still i from the outer scope.

Saturday, May 11, 2013

NodeJS Debugging with WebStorm

WebStorm makes getting started with NodeJS a breeze. I made a short video tutorial to show this that you can check out on youtube http://www.youtube.com/watch?v=6bKsDoFj83o also embedded below:


Wednesday, May 8, 2013

TypeScript AMD with RequireJS

Using TypeScript files with RequireJS is incredibly simple. However using JS files that are not aware of RequireJS can be a bit tricky. Also mixing Typescript with JavaScript all along using RequireJS can use a bit more documentation. So ... I made a video. Check it out here: http://www.youtube.com/watch?v=4AGQpv0MKsA

Covers Using TypeScript with RequireJS, using a non RequireJS file with TypeScript when in the RequireJS mode and a RequireJS Module with TypeScript.

Thursday, May 2, 2013

TypeScript Deep Dive

I recently gave an indepth advanced talk on TypeScript at Melbourne ALT.NET:
http://www.meetup.com/Melbourne-ALT-NET/events/115068682/

I had a lot of fun preparing the slides for this presentation. They are based on RevealJS / HTML. I addtionally strapped in TypeScript / Angular / RequireJS for my future talks.

You can find the slides here: https://github.com/basarat/TypeScriptDeepDive and I encourage you to use these in your own talks and contributions are appreciated.

Slides embedded here as well (click on slide to make active and press f to go fullscreen):

Monday, April 8, 2013

Typescript interface implementation gotcha

One thing to note when an interface is implemented in typescript is that for each function only the following are checked:
  • Number of parameters
  • The function return type

Based on this the following is perfectly valid code:


However the following is an error as expected.



You can see a discussion regarding the same : https://typescript.codeplex.com/workitem/350 

Sunday, April 7, 2013

Typescript static constructors for classes

Typescript does not currently provide a syntax for C# style static constructors. However you can get the same effect with the pair:
  • A non void static function
  • A static variable assignment used to call that function:




Foot note:  There is a request for a dedicated syntax to be added to typescript here : https://typescript.codeplex.com/workitem/862

e.g. (Non working / Proposed syntax) :



Sunday, March 17, 2013

Real private static class members in Typescript

The default implementation of private in typescript classes is a compiler enforced constraint only. Which means that if it is used from Javascript your members are still available.

If you really really want to prevent this then the following is one solution for private static members:


That is surround your class with a module and declare your private static variables in that module.

Thursday, March 14, 2013

Quick smooth fade in transition with Jquery

This is what I use when I need to test a quick smooth fade in transition with Jquery

// hide and show this element                          
$selector.css('opacity', 0).animate({ 'opacity': 1 }, 400);

The reason why I don’t use .hide and .fadeIn is that it causes the layout to jump which opacity avoids.

Wednesday, March 6, 2013

Typescript function signatures

Typescript provides two distinct methods of providing function signatures and these vary with either being in module , class or interface.

Here is a sample on playground  for your convenience.


Monday, November 12, 2012

TypeScript is Awesome!

TypeScript has quickly become my current favorite language. If you haven't heard of it yet then go here : http://www.typescriptlang.org/

Why?
Any self respecting developer that does javascript work should definitely check it out. I really like the ideas in javascript and the ability to modify the language according to my liking but I really really miss the great tooling / typo checking we get with static typing.

I strongly suggest you look at Ander's talk here : http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript (also embedded below) to get an idea of the awesomeness that becomes at your disposal:


Its open source. The tooling will be awesome. Developers, Developers, Developers.

Its better than CoffeeScript
In my opinion typescript is going to be as awesome for Javascript as LESS has proved to be for CSS. And in case you haven't heard of LESS its a superset of CSS that compiles down to CSS (example of popularity, twitter bootstrap uses it : http://twitter.github.com/bootstrap/extend.html ). Similarly TypeScript is a Superset of Javascript, all your javascript is still valid TypeScript. Super Cool. You are not learning a new language, you are extending your knowledge of a language.

So to learn typescript === learn javascript + more goodness

The community Loves it
The response from the community is what makes me really happy, and raises my faith in human support of all that is righteous and good :) . My measure of community response Stackoverflow : http://stackoverflow.com/questions/tagged/typescript And its not the number of questions they got in one month. Its the the number of votes on the accepted solutions. People are monitoring it a lot, in their own time. Always a good sign.

All your definitions are us
This is quickly becoming the definitive resource for all the typescript definitions your heart can desire : https://github.com/borisyankov/DefinitelyTyped Love the open source 

Monday, October 29, 2012

KnockoutJS tip : when to use brackets?

I simply love the knockout.JS framework. It makes the migration from silverlight to javascript / html so much more comfortable.

One point of confusion in knockout JS you might feel is when do you have to use brackets in front of observable and when can you ignore them? 

e.g. in the knockout intro tutorial : http://learn.knockoutjs.com/#/?tutorial=intro 

This: 

will work just as well as: 


Then whats the difference?  is actually a function since ko.observable returns a function : 



My solution:
In code ALWAYS use ().You have to, otherwise you will remove the ko.observable function on assignment which is bad. And on reading you would get the function not the value you wanted. 

In simple data-bind attributes NEVER use (). Because it will not work to two way data binding, i.e If I had bound value: firstName() to the input it would not have worked.  

In calculated data-bind attributes e.g. value: firstName() + lastName() , use brackets since you want one way binding and basically running arbitrary javascript :) 

Enjoy! 

Sunday, October 7, 2012

Best programming tutorials for JavaScript: With videos!

There is lots you can read about javascript.

But I have always found videos to be a great way to learn real world programming. You get to see people think. You get to see people perform. Great for finding productivity tips that have a HUGE impact.

Here is my playlist for JavaScript (the language) :

Playlist 1:


Some tips: 

Javascript has only one number type
and it is equivalent to double, floating point type
If you are dealing with money, multiply with 100, do arithmetic, divide by 100 :)


And if you cannot get enough, Playlist 2:


You can find all the slides for "Crockford on JavaScript" here : http://www.slideshare.net/douglascrockford/presentations

Enjoy!

Saturday, October 8, 2011

Comparison of Knockout.js and Backbone.js

Knockout.js is a great micro javascript library that allows you to make MVVM style applications with Javascript. To learn more about knockout.js check out there awesome live (in the browser tutorial) at :
http://learn.knockoutjs.com/


But enough about what is Knockout. Lets move on the how cool is knockout. A sample TODOs was provided by Scott Messinger about how cool Knockout.js is as compared to Backbone.js.

In backbone.js :

And in Knockout.js:

Enjoy!