views:

42

answers:

1

I love how Google Closure compiler will optimize symbols in code. However, I have not found a good way to define public, exported functions that take configuration objects as parameters. Consider this code snippet:

goog.provide('foo');
goog.require('goog.dom');

/** @typedef {{
 *              id : string,
 *              clazz : string
 *           }}
 */
foo.config;

/**
 * Does some neat stuff
 * @param {foo.config} config
 */    
foo.myFoo = function(config) {
    var el = goog.dom.getElement(config.id);
    goog.dom.classes.add(el, config.clazz);
} 
goog.exportSymbol('foo.myFoo', foo.myFoo);

Now assume we load this script, and want to call myFoo as follows:

<script type="text/javascript">
foo.myFoo({
    id: 'unique-id',
    clazz: 'pretty'
});
</script>

If compiled, this would fail because id and clazz properties were compressed.

Does anyone know of an elegant way to implement and export configuration objects using the Google Closure compiler?

+1  A: 

My suggestion would be to simply annotate the parameter as {Object} and quote the keys, as below:

foo.myFoo({
    'id': 'unique-id',
    'clazz': 'pretty'
});

...

/**
 * Does some neat stuff
 * @param {Object} config
 */    
foo.myFoo = function(config) {
    var el = goog.dom.getElement(config['id']);
    goog.dom.classes.add(el, config['clazz']);
} 
nullptr