Showing posts with label closuretools. Show all posts
Showing posts with label closuretools. Show all posts

Sunday, May 13, 2012

Dot vs square bracket notations in Closure

In javascript you can use square brackets and dot notation almost interchangeably:

a['property'] === a.property


Which is great and you can do things like:

function createGet(property, fn) {
  A['get'+property] = fn(A[property]);
}

so you can then put getters on an object (in this case A). e.g:

A.one = 1;
A.two = 2;
var sayNumber = function(num) {return "number is: " + num;};
createGet('one', sayNumber);
createGet('two', sayNumber);
A.getOne(); // "number is : 1"
A.getTwo(); // "number is : 2"

There are some other great uses as well such as the delegateEvents in backbone.js

But unfortunately in closure we can't do this because after compilation:


a['property'] !== a.property


This is because string literals will not be compiled, but properties with dot notation will be renamed. Fear not however because we don't actually need to mix these two and it does help if you think about these not being the same.

If you have a look at plastronjs you'll notice that setting a schema will look like:

var schema = {
  'prop1' : {
    get: function ...
    set: function ...
  },
  'prop2' : {
    get: function ...
    set: function ...
  }
};

so the properties have strings and the get and set don't. Closure will rename strings but not properties. The reason they are like this is that property will be called on using model.set() and model.get() that take a string as the first argument and those can either be sent or received through a sync. So basically prop1 and prop2 can be EXTERNAL. get and set are only ever used inside our program so they are INTERNAL.

so how about the options object that gets passed to a model? it takes:

'attr', 'sync', 'schema' etc. Why are those in quotes? Well the fact is that I've allowed you to just pass through ordinary properties at the top level, so who is to say when those are compiled (sat attr -> a) that you haven't defined 'a' as a property? I'm allowing you to mix external and internals so to be safe I have to use the quotes. In doing that I then have to refer to the options object for object['attr'] instead of object.attr so we're losing a little compiled space but making things much easier to pass through attributes.

Just to make things easier I've also given you a special method in mvc.Model which will allow you to get around typing the string every time you need an attribute. What we can do is bind a function to that attribute to make things easier. Say we have an attribute 'star' that is either true or false. If I reuse it a lot, instead of doing model.get('star') I'd like something a bit easier. mvc.Model#getBinder to the rescue. Now you can do this:

var star = model.getBinder('star');
star(); // true
star(false);
star(); // false

The getBinder method is simple and looks like this:

mvc.Model.prototype.getBinder = function(key) {
  return goog.bind(function(val) {
    if (goog.isDef(val)) {
      this.set(key, val);
    } else {
      return this.get(key);
    }
  }, this);
};

It will allow you to get and set through a function whose name can be compiled and also makes it easy to call.

So what is the moral of the story? Well there are three:

  1. If a property is visible externally or is mixed with external properties that use square brackets
  2. If a property is internal only to the project then use dot
  3. If you're using a lot of square brackets think about binding it to a function

Keep these in mind when you start and after a bit of practice you won't miss being able to mix notations, and it will certainly help you keep down differences between the compiled and uncompiled versions of your code.

Saturday, May 12, 2012

TodoMVC PlastronJS example



Here is a run through of how to get the todoMVC example, checkout the uncompiled code and how to compile changes you make.

If you're having trouble seeing the characters try clicking the youtube button on the video and watching it in fullscreen.

Thursday, April 5, 2012

How to start closure

I keep running over in my head just how far in to closure I should get. There is already a tutorial and the Closure: Definitive Guide are great starts. These will be enough to get you up and running for a simple application that runs locally (or on a local server if you went down the plovr route).

Once you have followed the tutorial and got everything setup you'll find your first problem will be XHR. If you are building a site that consumes XHR requests from another domain then running your page off a local server should suffice, the issue comes when you are trying to consume json from your own domain. Since you'll be running your page from localhost (or whatever you're using) you'll run in to cross domain issues.

The fix is pretty simple, use a proxy server. You're going to have to build one though, so what is the best way? Well we know javascript so node.js is probably a good option.

Building a proxy server in node.js is a bit beyond what this blog is about and it would be terrible of me to take you away from the experience of learning about node.js. Instead I'm just going to let you know the principle and let you go and find your own tutorial.

The idea is that you want to run the server on your localhost, read the requests as it comes in and if it should match something local then read that file and return it. Otherwise you want to copy the headers over to a new request and pipe the response back.

At catch we even decide whether to look at the uncompiled version of the code for development by putting a debug=1 in the query string parameters.

Tuesday, April 3, 2012

The Closure toolset

The Closure set of tools are a set of five components that help in creating web applications. You can check out their page to see the five different components. What we're going to look at here though is what they address.

Closure Compiler

The Closure Compiler is perhaps the most interesting part when you first hear about the closure toolset. The compiler will take your javascript and minify it. There are already minifiers but the compiler actually parses your code and makes it better by doing things like code inlining. This means that your code will also run faster. The compiler will also do some great things like type checking to pick up errors that could turn around and bite you later. There are some rules though when you use the compiler which is effectively like using a subset of the language. Perhaps the biggest difference is that you can't mix bracket and dot notation (i.e. person.name != person['name']).

An interesting alternative for projects where you don't want to go down the path of using a subset of javascript is UglifyJS

Closure Library

The Closure Library is built to work well with the compiler. It may look huge to begin with but most of that is comments and when you build your project you only include the code you use as opposed to other libraries where you need to include either the entire file or entire modules on the page. The closure library will allow you to do DOM manipulation, ajax, gives you UI components and also takes care of dependancy management through the reps_writer - a python script that goes through and figures out what order javascript needs to be loaded on to the page.

There are many alternatives which you can use instead. Thes include JQuery & JQueryUI, YUI, Sencha (ExtJS) and Dojo.

The library also gives a testing framework which is similar to other test frameworks like QUnit, mocha or jasmine.

Closure Templates

The Closure Templates, or Soy work with both javascript and java which allows them to be used on the client and server side. You can include some logic in them and extend their functionality through java plugins.

other temptlating solutions that you might consider are mustache, JQuery template and jade

Closure Linter

The Closure Linter checks your code style to make sure it is always readable by other people in your group.

Alternatives are JSHint and Crockford's original JSLint

Linters are well known for hurting people's feelings - so be sure to run them often, you can even get JSHint as a plugin for Textmate.

Closure Stylesheets

The latest recent addition to the closure toolset is Closure Stylesheets. This allows you to to write CSS in a more programmatical way. One of the large benefits with Closure stylesheets is the minification and class renaming which can save even more bytes.

Alternatives are LESS and SASS and compass. You may still want a CSS minifier to use afterwards and you can use Yahoo's

So it's a pretty complete set of tools - the only thing that is really missing is a way to structure your code (and perhaps an IDE). Next blog article I'm going to take you through creating a local application which will be followed by posts about building and serving your application on a server. In those I will introduce you to Plovr and talk about creating a node proxy script so you can test pages "live".

I'd also recommend you pick up the Closure Definitive Guide, which you can also get on Amazon for your kindle.