Thursday, May 21, 2015

jQuery event namespacing

jsfiddle

var obj = $({});

function log(evt, obj, src) {
    $('#log').append(obj + ':' + evt.type + '.' + evt.namespace + ' ' + src + '\n');
}

obj.on('save.billing', function (evt, obj) {
    log(evt, obj, 'save base');
});

obj.on('save.billing.widget', function (evt, obj) {
    log(evt, obj, 'save widget');
});

obj.on('save.billing.consumer', function (evt, obj) {
    log(evt, obj, 'save consumer');
});

//triggers base, widget, and consumer
obj.trigger('save.billing', 1);
//remove widget listeners
obj.off('.billing.widget');
//triggers base and consumer
obj.trigger('save.billing', 2);
//remove all billing listeners
obj.off('.billing');
//triggers nobody
obj.trigger('save.billing', 3);

Monday, April 20, 2015

Grunt-JSDoc prevent output of source code

By default JSDoc will include your source code in the resulting documentation.  To prevent this from happening when using grunt-jsdoc you'll have to create an external configuration file:

gruntfile:
build: {
    options: {
        destination: '<%= path %>/doc',
        configure: 'conf.json'
    }
}

conf.json
{
  "source": {
    "include": "app/js/ascendon.service.js"
  },
  "templates": {
    "default": {
      "outputSourceFiles": false
    }
  }
}

Tuesday, April 7, 2015

Browserify and Grunt using jQuery from a CDN

Below is a sample configuration in which jQuery, backbone, and underscore are all referenced externally so that they are not included in the browserify bundle. Notice also that there is a transform for underscore templates in the grunt config. The resulting bundle is built as a standalone so that the module can be instantiated by our clients.  You'll need to npm install browserify-shim and modify your package.json file.  After building this module your html page will also need to reference jQuery because the jQuery code will not be in the bundle.

package.json
{
  "name": "packageName",
  "version": "15.3.1",
  "devDependencies": {
    "browserify": "9.0.7",
    "browserify-shim": "3.8.3",
    "grunt": "0.4.5",
    "grunt-browserify": "3.6.0",
    ...
  },
  "browser": {
    "jquery": "./app/js/lib/jquery-1.11.2.min.js",
    "backbone": "./app/js/lib/backbone-1.1.2.min.js",
    "underscore": "./app/js/lib/underscore-1.8.3.min.js"
  },
  "browserify": {
    "transform": [ "browserify-shim" ]
  },
  "browserify-shim": {
    "jquery": "global:$",
    "underscore": "global:_",
    "backbone": "global:Backbone"
  }
}

gruntfile browserify options
    js: {
        src: ['app/js/main.js'],
        dest: 'app/js/company.modulename.js'
    },
    options: {
        transform: ['node-underscorify'],
        browserifyOptions: {
            standalone: 'company.modulename'
        }
    }