Archive for the ‘JavaScript’ Category

oliverm

The Gist of Code Sharing

Wednesday, April 17th, 2013

Agile development teams often need to share code while in the heat of battle.

At the high end of the scale, there are publicly-accessible repositories, such as GitHub. Creating a GitHub project is obviously overkill for those wishing to simply pass a few key lines of code to their buddy in the next seat.

For stand-alone, runnable demo code, sites like Plunker and JSFiddle  are great. You will see references to these sites wherever HTML, CSS and JavaScript bugs are reported; for example stackoverflow and the AngularJS Google Group.

But again, maybe overkill for just a few lines.

So what are the other options for code sharing?

  • Email – I suppose, but there may be delays in receiving the email if your server is slow.
  • Skype or other messaging service – Alright, but you lose history eventually.
  • USB Key (sneaker-net) – It works, but it is hard to share it with a lot of people and history is also an issue.
  • Gist – This has been around a couple of years but I’ve only just discovered it since it is baked into IntelliJ/WebStorm. Gist is a GitHub sub-project and is associated with your GitHub account. For example, my GitHub account is at https://github.com/oliverm2112 and my Gists are at https://gist.github.com/oliverm2112. Gist allows developers to post snippets of code in various languages and features in-place editing and syntax highlighting.

Here is a Gist home page and a code sample:

 

 

 

 

Here is a shot of IntelliJ/WebStorm’s abilitity to create a Gist from within the IDE:

Hopefully you will find this a useful way to share information.

alaint

AngularJS – Promises

Wednesday, April 3rd, 2013

AngularJS comes with promise/deferred APIs that are simple to set up and are also built into the $http API. The Angular promise is basically a guarantee that some code will be fulfilled after other parts are done.

Single Promise:

1
2
3
4
5
6
7
8
9
10
11
myApp.controller('myController', ['$scope', '$q', function ($scope, $q) {
    var defer = $q.defer();

    defer.promise.then(function () {
        $scope.$emit('shoutEvent', {'message' : 'I kept my promise!'});
    });

    $scope.$on('someEvent', function (event, data) {
        defer.resolve();
    });
}]);

In the above example we create a new instance of a deferred object which exposes a promise. Next, we access the promise and add the callback that we need. We can now resolve the promise when the ‘someEvent’ is received.

Multiple Promises:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
myApp.controller('myController', ['$scope', '$q', function ($scope, $q) {
    var defer1 = $q.defer(),
        defer2 = $q.defer();

    $scope.$on('someEvent', function (event, data) {
        defer1.resolve();
    });

    $scope.$on('someOtherEvent', function (event, data) {
        defer2.resolve();
    });

    $q.all([defer1.promise, defer2.promise]).then(function () {
        $scope.$emit('shoutEvent', {'message' : 'I kept my promise to all of you'});
    });
}]);

As shown above, when we need to wait for multiple promises to resolve and take action, we can use the $q.all() method to combine them into one promise.

These examples show how AngularJS promises are powerful. But, this post just touches a few of their features. There are other features you might be interested in such as chaining promises with return values, using them in templates and rejecting promises.

You can read more about them in the AngularJS documentation.

oliverm

JavaScript Object Creation Times

Tuesday, November 6th, 2012

By Oliver Merk – principal consultant

There are three common ways to create JavaScript objects.

The one most of us learned first was the constructor call:

1
var myObj = new Object();

Then we got clever and impressed our friends by using object literal syntax:

1
var myObj = {};

Now, with the latest version of ECMAScript, we can use:

1
var myObj = Object.create(proto);

…where proto is the object to be used as the prototype of the new object. You will typically set this to null or {}.

Which of these three do you think is the fastest? Which is the slowest?

The results may surprise you as much as they did me.

Follow this link and have your JavaScript Console open when you click the Run test button:

http://downloads.newyyz.com/NTGBlogPosts/jsobject/

Derek Santos

5 Cool Things About CoffeeScript

Monday, October 22nd, 2012

By Derek Santos – consultant

I’ve been experimenting with CoffeeScript lately and wanted to pass along some things I really like about it.

1. It writes very good JavaScript

CoffeeScript compiles to JavaScript that follows best practices and sticks to JavaScript’s good parts. For example:

  • == always turns into ===
  • Code automatically gets wrapped with a self calling function to protect its scope
  • var declarations always get moved to the top

2. It’s readable

Whitespace is meaningful in CoffeeScript (which can be hard to get used to at first), but consider the following example:

JavaScript

if (devices !== null && devices !== undefined) {
    devices.push({
	name : 'iPhone 6',
	manufacturer : 'Apple'
    });
}

CoffeeScript

if devices?
    devices.push
	name : 'iPhone 6'
	manufacturer : 'Apple'

It’s a simple example, but you can see how CoffeeScript removes the unnecessary syntax and reads more like a sentence.

3. String Interpolation

This is one thing I will admit is tedious in JavaScript (and some other languages). We’ve all had to do this before.

html = '<div>';
html += '<h2>' + title + '</h2>';
html += '<p>' + body + '</p>';
html += '<span>' + footer + '</span>';
html += '</div>';

In CoffeeScript, this would be accomplished with:

html =
"""
<div>
	<h2>#{title}</h2>
	<p>#{body}</p>
	<span>#{footer}</span>
</div>
"""

A templating engine could be used to give the same result, but that also adds extra weight to your project. This is not so in CoffeeScript since it just gets compiled into pure JavaScript and makes it much cleaner.

4. Classes and Inheritance

If you are coming from a classical programming language such as Java, CoffeeScript allows you to structure your code in a way that is familiar to you. CoffeeScript also has some helpful nuggets like using => instead of -> to bind a particular scope to your functions.

5. It’s fantastic for writing unit tests

If you are reluctant to try CoffeeScript because you are afraid of how it will affect your project, I strongly urge you to try writing your unit tests in CoffeeScript. This way, you’ll be learning it in a risk-free environment while still providing value to your projects. You’ll find that your tests will be incredibly easy to read and author using CoffeeScript.

Here is a sample Jasmine test written in CoffeeScript:

describe 'controller', ->
    target = app.mycontroller

    it 'should call a service and return a response', ->
        target.makeRequest (result) ->
            expect(result).toBe('success!')
seanh

A Coffee Break with CoffeeScript

Tuesday, July 31st, 2012

Yesterday we were having a little water-cooler conversation admiring CoffeeScript.

I had a look at this a while ago, when I was first investigating JavaScript. I remember liking it then, and looking at the syntax again, I think it’s pretty cool.

Today, I Googled around to check out some criticism from people that had actually used it, and I found some interesting links, including the “A Case Against Using CoffeeScript

There were a number of points, which really just point out that you can write bad code in any language. That’s not really a strike against CoffeeScript. Just don’t expect it to be idiot proof.

The real grind is debugging, since you write in CoffeeScript and debug in JavaScript. The workflow is complicated, and reading generated code is way worse than hand-written code.

Of the big advantages, CoffeeScript saves you from some of the big syntax gotchas in JavaScript (e.g. accidentally creating a global variable, and automatic semicolon insertion).  But there are other alternatives such as using a tool like JSLint.

If CS were run directly by a VM in the browser with debugger support…well then we’d have something. Apparently coffeescript is influencing the future of JavasScript.

For now, what you gain in readability you lose in debuggability. Make fewer bugs that take longer to debug, or make more bugs that are easier to debug, where’s the break-even point?

For now, I’ll continue with JavaScript and read and write carefully, with help from JSLint.

But don’t take my opinion, there’s a great debate on it here: http://net.tutsplus.com/articles/interviews/should-you-learn-coffeescript/

The skinny: Definitely worth learning, maybe not worth using except for simpler one person projects.

 

 

oliverm

BlackBerry Hackathons – Come out and Play(Book)!

Wednesday, May 16th, 2012

I’m currently in Bogotá, Colombia taking part in my third Hackathon on behalf of RIM. These hackathons are two-day events where local developers get the opportunity to interact directly with experts in PlayBook development. They also get a free PlayBook just for showing up!

We typically have a team of three experts covering AIR, HTML5/WebWorks and Native development. Most of the events have been focused on game development, but I’ve also done one centred around business apps using WebWorks.

Developers, either in teams or individually, work some long hours over the two day period. At the end of the second day, their apps are judged and winners awarded additional prizes. Nothing like a bit of competition to bring out the best in a dev team!

And with BB10 on the horizon, there’s a lot of anticipation from developers. Keep your eyes open for an event coming to your city this summer. Hope to see you there!

oliverm

JavaScript Developer Survey

Sunday, December 4th, 2011

Looks like this is turning into an annual event. Given JavaScript’s importance in the Mobile/HTML5 space, it will be interesting to see how developers are using it:

http://dailyjs.com/2011/12/01/javascript-developer-survey-2011/

 

oliverm

Links roundup

Friday, November 4th, 2011

Here are a few unrelated links I’d like to pass on for your reading pleasure.

  1. Opportunistic Refactoring by Martin Fowler, author of the best programming book ever (Refactoring).  I’ve been preaching this one for a long time: “while you’re in there, refactor any smelly code, but don’t get caught in a death spiral”.
    http://martinfowler.com/bliki/OpportunisticRefactoring.html 

  2. jQuery4u – lots of great jQuery plug-in round-ups. I’m starting to visit this almost daily now.
    http://www.jquery4u.com/ 

  3. Finally, for you old KDE 3 fans, the beast is still alive and well. I loaded this onto a VM and started feeling very sentimental for the old days when KDE didn’t suck and I didn’t have to settle for Gnome.
    http://www.osnews.com/story/25283/KDE_3_5_Fork_Trinity_Releases_Third_Major_Update 

As usual, I look forward to your comments on any of these.

Oliver

Derek Santos

Object Oriented JavaScript – Part 3

Monday, October 3rd, 2011

By Derek Santos – Consultant

Go to Part 1
Go to Part 2

In Part 2 of this series, I covered inheritance in JavaScript.  In this post, I’ll mention what else is possible with Object Oriented JavaScript and provide some resources.

JavaScript can support most Object Oriented Principles including:

  • Classes
  • Constructors
  • Inheritance
  • Encapsulation
  • Polymorphism

I’ve already covered Classses, Constructors and Inheritance.  If you’re interested in learning more about Encapsulation and Polymorphism in JavaScript, this is a great article to read.

Another post written by Douglas Crockford that covers some more advanced topics for Object Oriented JavaScript can be found here. He shows how to create some of your own convienence methods to make OOJS a little easier.

A list of popular JavaScript frameworks

There are a ton of JavaScript frameworks out there.  A lot of them use the pricinples discussed in this series.  Here is a list of some common frameworks:

  • JQuery – Everyone knows this one, it’s arguably the most popular
  • Prototype – Another well known framework, similar to JQuery
  • Mootools - A compact JS framework for more advanced JS development
  • Dojo - Seems to have pretty good adoption, includes UI widgets as well
  • Mochikit - Another lightweight js framework
  • JavaScriptMVC – An Model-View-Controller implementation for JavaScript
  • YUI Library – Yahoo’s JavaScript UI Library
  • Jo - A mobile framework for HTML5 and JS.
  • FuseJS - Another framework like jquery and prototype.

The list goes on. I’d love to hear peoples opinions about these frameworks and any other frameworks you might be using.

Derek Santos

Object Oriented JavaScript – Part 2

Monday, September 12th, 2011

By Derek Santos – Consultant

Go to Part 1
Go to Part 3

In a previous post, I covered the basics of Object Oriented JavaScript. In this post, we’ll take a closer look at inheritance.  Remember that JavaScript is a prototypal language. Instead of the traditional “is a” relationship, JavaScript inheritance has a “is now a” or “has become a” relationship.  The reason for this is that JavaScript is an interpreted language, and does not get compiled.   In classical OOP, inheritance means a subclass “is and has always been a” type of its superclass.  In JavaScript, an object always starts off as an independent entity and can then be assigned a relationship to some other object.  Let’s look at some examples.

Inheriting from another object

To make an object inherit from another object, you use the objects prototype property.

function Device() {}
Device.prototype.startUp = function () {
    alert('device start up');
}

function AndroidPhone() {}
AndroidPhone.prototype = new Device(); //AndroidPhone inherits from Device

var device = new AndroidPhone();
device.startUp();

Overriding methods

To override a method, simply define it in your new object.

AndroidPhone.prototype.startUp = function () {
    alert("AndroidPhone starting up...");
}

Calling methods on the superclass

There is no super property in JavaScript (unless you create one yourself). Instead you need to use the “call” method.

AndroidPhone.prototype.startUp = function () {
    Device.prototype.startUp.call(this);
}

The call method accepts an argument specifying the this property. It is used to define the context in which you are calling the method. In this case “this” will refer to AndroidPhone.

Digging Deeper

There’s a lot you can do with JavaScript inheritance. There are countless examples and libraries out there that try to make OOP in JavaScript easier and more streamlined. In my next post, I’ll take a look at some of those libraries and see how OOP in JavaScript can be made easier.