Adam Krasny

Ruby, Rails, and AngularJS developer. Coding enthusiast.

Read this first

Simplify async code with generators and promises

Asynchronous code is a necessary part of life when developing in JavaScript. Why not make it easy on yourself?

Start with promises. They reduce the need for callback functions and practically eliminate nested callbacks. If you aren’t already using them, you should be. My favorite library for promises is https://github.com/petkaantonov/bluebird

Then we have generators. They are a new feature introduced in ES6. You can read more about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

Even when using promises, async code can become unwieldy. Take a look at the following code.

getUser(id).then(function (user) {
  return getCompany(user.companyId).then(function(company) {
    return getUser(company.ceoId);
  });
});

Assume id is already set and that all functions return promises. The code will return the user object for the CEO of the

Continue reading →


Start using ES6

JavaScript is the unavoidable language that everyone loves to hate. Unnecessary type coercion, lack of proper class constructs, and dynamic function context are just a few things that are, at best, an annoyance and, at worst, can cause hard to find bugs in your code.

What if I told you there was an easy way to fix most of this frustration?

EcmaScript 6 is the new standard that will drive JavaScript engines. The first update to the language since EcmaScript 5 was standardized in 2009, 6 years ago. That’s around the time of iOS 3 and Android 2.0.

https://babeljs.io/ is a tool that let’s you transpile your ES6 code into ES5. This gives you access to all of the awesome functionality that ES6 introduces. Generators, arrow functions, classes, template strings, destructuring, enhanced object literals, and modules are features that will improve your code and make coding more pleasant.

With

Continue reading →


AngularJS: Simple, reusable directives

Directives in Angular give you the power to do a lot. Sometimes, you need to do a lot. Most of the time you just need something simple that will get the job done. Here are a few examples of reusable directives that do only what they need to do.

First, a directive that can be applied to a button group. Keep in mind this isn’t restricted to a button group, and if you think creatively, it can come be applied in a lot of places.

  mod.directive('radioValue', function () {
    return {
      restrict: 'A',
      require: '^ngModel',
      scope: {
        radioValue: '='
      },
      link: function (scope, elem, attrs, ngModelCtrl) {
        elem.on('click', function () {
          scope.$apply(function () {
            ngModelCtrl.$setViewValue(scope.radioValue);
          });
        });
        scope.$watch(function() {
          return ngModelCtrl.$modelValue;
        },

Continue reading →


Getting started with Gulp

This is the first in a short series about setting up a sane gulpfile that works for development and production.

Having recently switched from Grunt, I find Gulp to be easier to use and maintain, and I want to share what I’ve learned so far.

 Initial setup

This guide assumes you already have nodejs installed. There should also be a ‘package.json’ in your root application directory, which can be created using npm init. From there, gulp should be installed globally using npm install -g gulp and inside of our project dependencies using npm install --save-dev gulp.

Our first gulpfile will be simple and I will use it to introduce several important plugins.

 Plugins

Install the following gulp plugins using npm npm install --save-dev <plugin>

  • gulp-changed - Run tasks on changed files only.
  • gulp-clean - Clean up build artifacts.
  • gulp-connect - Development http server with live reload.

Continue reading →


Angular and Slim

Another layer of abstraction? Why not. In comes Slim, a lightweight
templating engine.

http://slim-lang.com/

Slim saves you a bit of hassle when you’re writing HTML. IDs and classes
are much easier to identify and assign, attributes are defined
identically to HTML, no more closing tags, and a lot of miscellaneous
utility.

#item-ctn
  .list-item ng-repeat='i in items'
    h1() {{i.name}}
    span.timestamp() {{i.timestamp}}

vs

<div id="item-ctn">
  <div class="list-item" ng-repeat="i in items">
    <h1>{{i.name}}</h1>
    <span class="timestamp">{{i.timestamp}}</span>
  </div>
</div>

If you use grunt for your build workflow this task will come in handy.

https://github.com/matsumos/grunt-slim

Continue reading →


ngBindHtml and Showdown to Render Markdown

An easy way to store formatted text content without having to worry about storing HTML is by using Markdown. Markdown allows you to add headers, links, code blocks, and all other necessary formatting to a string without using any kind of special characters.

Markdown

This kind of content is easily stored in a database as a string. Retrieving it is a breeze as well. So what’s left? Rendering it on the client.

Showdown

Showdown is a Markdown parser (is that what it’s called?). It can take a
Markdown string and process it into an HTML string. We can assign the
value on our controller since we need to mark it as trusted first.

$scope.markdownHtml = $sce.trustAsHtml(new Showdown.converter().makeHtml(md);

A few important points in this code sample.

new Showdown.converter().makeHtml() // This will take your Markdown string and return an HTML string.

$sce // A service that provides

Continue reading →


Debugging AngularJS

Knowing how to debug your code is just as important as writing it.

The most obvious way to debug code is to use debugger statements in your JavaScript or just breakpoints through Chrome developer tools (or your favorite browser). This works great for fixing code that is executed in a controller, filter, or directive. The bigger problem is view logic that may not be in a controller or simply debugging why certain things aren’t working properly on the view.

One neat trick is to make use of angular.element. Check out the docs

Angular Element

angular.element()

An alias for jQuery, if it is available, otherwise it will use an angular specific jQuery lite implementation. Refer to the documentation for specific DOM functions available through jqLite because they can differ from jQuery quite a bit.

More importantly, check out the extended functions angular provides:

controller(name)

Continue reading →


$event, where does it come from?

ngClick, ngMousedown, ngMouseup, and every directive event handler in Angular provide the $event parameter in callbacks. I will show you how to do this with your own directives.

Angular provides an extremely useful service known as $parse. Take a look at the documentation here:

ngParse

So it looks like we can take any Angular expression, convert it to a function, and invoke it in the context of a specific scope and using locals we define. Perfect. Let’s see how we can utilize this when creating a directive for drag and drop.

app.directive('drag', ['$parse', function($parse) {
  return function(scope, elem, attrs) {
    var cb = $parse(attrs.drag);

    elem.on('dragstart', function(e) {
      scope.$apply(function() { cb(scope, { $event: e }); });
    });
  }
}]);

Couple of things to note. I protected against minification by using the array syntax to import the $parse service into

Continue reading →


Isolate Scope Helpers

Author’s note - This has changed in Angular 1.2. Directives with isolated scopes will only share this isolated scope with other directives that explicitly request it. It will no longer impact regular directives.

Isolate scope is a concept which can be really useful. If a directive ever needs to create or manipulate it’s own variables that it will use in a template, you want it to have an isolated scope. Also the ‘@’, ‘&’, and ‘=’ shortcuts seem like they could be really easy shortcuts to reading attributes into a directive. Knowing all of this, I still find myself rarely using them and I’ll tell you why.

Anybody developing with AngularJS needs to be familiar with scope prototypical inheritance. Read about it here. There is one key point I would like to highlight:

scope: { … } - the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your

Continue reading →


Protecting Against Minification

AngularJS is an interesting beast. The official documentation can be severely lacking. Trying to find answers or examples on the internet frequently turns into a hassle.

Something that I feel that should be covered is ensuring that your Angular code is protected from minification. When using Rails asset pipeline, for example, your JavaScript will be minified by default. This will actually break Angular code unless you explicitly protect against it. A lot of times you won’t even realize there is an issue until you deploy in production.

Assuming we have our application module defined

var app = angular.module('application'); 

this is how you sometimes find controllers defined in examples

app.controller('sampleCtrl', function($scope) {

});

but this will break when minified. AngularJS will internally look at the name of the parameter defined, in this case $scope, to inject the

Continue reading →