Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

6/17/2013

Coffeescript + Requirejs

There are great things that can really help you in your development workflow. One of them is Coffeescipt.
Coffeescript alone is a great concept that tries to avoid "bad parts and embrace good parts of Javascript".
But when you combine Coffeescript with one more powerful tool like Requirejs, then nothing can stop you from writins amazing apps.
Since I am using Requirejs for a while, I was trying to find a way not to compile manually Coffee code from the main require file. I found this plugin which lets you write you coffee code, without worry about compiling. How does it work ?

First go to git-plugin page and follow instructions how to install everything. It is pretty straightforward. After that it is possible to write code like this:


//
require([ "modules/cs!modules/iterator","libs/jquery-1.9.1"],  
    (iterator,jquery) ->
    $("button").on("click",(e)->
    console.log iterator.next()
        )
    )
//

This great plugin auromatically compiles coffeescript code to native javascript. It is important to include plugin module properly ( with exclamation point ). The good part is that plugin will load code from the coffee version, and convert it to javascript.

Here is where magic happens:

//
    load: function (name, parentRequire, load, config) {
            var path = parentRequire.toUrl(name + '.coffee'); // plugin is reading file with coffee extension
            fetchText(path, function (text) 
//

Happy Coding

6/14/2013

A taste of functional javascript

There is some real power in functional programming, compared to imperative which is a basis for OOP paradigm. One of them is immutable state.
In a languages that supports state change ( imperative family ) mutability is a double edged sword - you can create awesome control flow ( if you know ) or you can quickly get lost in a jungle of your own variables.
Functional paradigm elegantly avoids state change, by not separating function from the value that is returned. So in FP ( functional programming ) function IS a value. There are some variations and some languages supports state change and mutability to the certain degree, but when we talk about FP we think mostly about functions that are values.

Here is one example of FP. It is written first in Coffeescript, and then in vanilla Javacript:

# data
arr = ["chicken","pig","donkey","horse","cow"]

#main function definition
each = (data,iterator,transform)->
    iterator(data,transform)

#transformer
toUpper=(args)->
    console.log args.toUpperCase() + " farm"

#iterator
iterate = (data,upper)->
    for key,val in data
        upper(key)

#call everything
each(arr,iterate,toUpper)
#

Vanilla Javascript ( compiled ):
// Generated by CoffeeScript 1.6.2
(function() {
  var arr, each, iterate, toUpper;

  arr = ["chicken", "pig", "donkey", "horse", "cow"];

  each = function(data, iterator, transform) {
    return iterator(data, transform);
  };

  toUpper = function(args) {
    return console.log(args.toUpperCase() + " farm");
  };

  iterate = function(data, upper) {
    var key, val, _i, _len, _results;

    _results = [];
    for (val = _i = 0, _len = data.length; _i < _len; val = ++_i) {
      key = data[val];
      _results.push(upper(key));
    }
    return _results;
  };

  each(arr, iterate, toUpper);

}).call(this);
//
Notice the elegance of  functions passing as arguments to other functions, without effecting anything outside them. It is called function composition, and it is the main "sugar" of FP.

Happy Coding


5/28/2013

Awesome TODOMVC project

Look no further - this awesome project will give you everything you need to know about javascript. Take a walk through Todomvc examples and you'll be enlightened. It is incredibly usefull to take a look at just Vanilla.js, as a starting point.That way we can see pure javascript in action - outside of  framework solutions. And later, you can move on to other examples. Authors covered all known and unknown modern javascript framworks and libraries.
Backbone, jQuery, Angularjs, Ember, Dojo, Yui - and even Dart :)
And of course everything starts with pure js.

For example, injecting HTML without templates usage looks like this:

function View() {

  this.defaultTemplate =

'
  • '+'
    ',
    +''
    +''
    +''
    +'
    '+'
  • '; };

    It looks like a string concatenation horror :)

    Or a helper functions, for DOM query, that binds function to global object:

    window.$ = document.querySelectorAll.bind(document);
    window.$$ = document.querySelector.bind(document);
    
    

    Here's a link to TODOMVC GitHub page

    Happy Coding

    5/26/2013

    How to save Backbone collection to the server ?


    Backbone Collection doesn't have save method, it is only avaliable on the Model instances. So how can we save collections to the server ?

    There are couple of workarounds. I found  one very elegant solution, which wraps model around collection. It is opposite to common pattern in which collection is a wrapper around models.

    Here is a basic skeleton of this idea:

    //
    // collection class extended
    var CDShop = Backbone.Collection.extend();
    
    // collection instance 
    var CDShopInstance = new CDShop([
        {
            title: "Blue Train",
            author: "John Coltrane"
        },
        {
            title: "Intercontinental",
            author: "Joe Pass"
        },
        {
            title: "Confirmation",
            author: "Charlie Parker"
        }
    
    ]);
    
    // model class extended
    var MusicShop = Backbone.Model.extend({
        defaults: {
            title: "",
            author: ""
        },
        // passing collection as a property of instance
        model: CDShopInstance,
        // imaginary url 
        urlRoot: "/shop"
    });
    // model instance 
    var musicShopInstance = new MusicShop;
    
    // testing returns three objects from the collection
    console.log(musicShopInstance.model.toJSON());
    
    // now we can save out collection to the server  
    musicShopInstance.save();
    //
    

    Happy Coding.

    5/25/2013

    Bash script helper for fetching remote JS libs

    I created a small bash-script, to help me fetch most freqently used JS libraries for client side development:

    #!/bin/bash
    
    url http://code.jquery.com/jquery-latest.js>jquery.js
    curl https://raw.github.com/documentcloud/underscore/
    master/underscore.js>underscore.js
    curl https://raw.github.com/documentcloud/backbone/
    master/backbone.js>backbone.js
    
    

    Although these libs can be fetched manually, or like a part of for example Yeoman project or Bower, I found that sometimes I don't need all the functionallity that comes with package managers. So this script is ideal for a fast production setup.

    It can be found on my Git repo.

    Happy Coding.

    5/21/2013

    Triggering globally custom events in Backbone

    If you want to implement traditional publish/subscribe pattern, you can do a very cool trick with Backbone custom events model.

    // create a basic model
    var Model = Backbone.Model.extend({
        defaults: {
            color:"red",
            name: "bmw"
        }
    });
    
    // create a view for that model
    var ModelView = Backbone.View.extend({
    tagName: "h4",
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.html(this.model.get("color"));
        return this;
    }
    });
    
    // create a route
    var Route = Backbone.Router.extend({
        routes: {
        "home": "showHome"
    },
    showHome: function(){
        Vent.trigger("init");
    }
    });
    
    // create instances
    var model = new Model;
    var modelView = new ModelView({model:model});
    new Route;
    
    // start a history
    Backbone.history.start();
    
    // create a global Vent object, and extend it with Backbone event model (with the help //of underscore.js - which is Backbone dependency ):
    var Vent = _.extend({},Backbone.Events);
    
    // append everything to the DOM, with the help of custom global event:
    Vent.on("init",function(){
    $(document.body).append(modelView.el);
    });
    

    The most important part of this code is attaching custom event handler to the URL route. We made that event  globally accessible, by attaching it to the global Vent object. Vent object is triggering custom init event , which is responsible for appending content the DOM.  We subscribed to that custom Init event  through on method of the global Vent object. This is very basic example, just to show the power of custom events.

    Happy coding.