0.0.2-4 • Published 11 years ago

nm-utils v0.0.2-4

Weekly downloads
16
License
-
Repository
github
Last release
11 years ago

nm-utils

nm-utils is a library of useful JavaScript functions. Currently, it includes 2 functions:

callFunction - A safe way to call a function without the need to check that the callback parameter is indeed a function. This function takes care of calling the callback as well as passing any number of parameters you'd like. Additionally, it can also set the context of the callback.

parseBool - parses string values as boolean. Especially useful parsing incoming parameters (e.g. url parameters which are sent as string).

Usage

Installing

npm install nm-utils

callFunction example - without setting the context:

(function() {
    var utils = require('../lib/utils');

    var doAsyncOperation = function(callback) {
        // do some asyn operations here...
        utils.callFunction(callback);
    };

    doAsyncOperation(function() {
        console.log('async operation completed!');
    });

})();

callFunction example - including setting the context:

(function() {
    var utils = require('../lib/utils');

    function User(name, email) {
        this.name = name;
        this.email = email;

        this.whoAmI = function() {
            return 'My name is: ' + this.name + ', my email is: ' + this.email;
        };
    }

    var loadUser = function(callback) {
        // assuming we got the name and email from an async operation
        var name = 'John Doe', email = 'john@doe.com',
            user = new User(name, email);
        utils.callFunction({callback:callback, context:user});
    };

    loadUser(function() {
        console.log('User load completed. ', this.whoAmI());
    });

})();

parse example:

(function() {
    var utils = require('../lib/utils'),
        trueInput = 'true', falseInput = 'false',
        trueVal = utils.parseBool('true'), falseVal = utils.parseBool('not-true');

    console.log("'" + trueInput + "' is " + trueVal + ", while '" + falseInput + "' is " + falseVal);

})();