I have a JS library that uses has something like the following method:
this.on('doAction', function (args) {
console.log(args.name);
console.log(args.arg1 + ' ' 9 args.arg2);
});
this.trigger('doAction', {name: 'write', arg1: 1, arg2: 2});
But after advanced optimization objects properties name
, arg1
and arg2
will be a
, b
, c
, so I can't get them in doAction
handler. I know I can to use quotes for a property names to prevent it from changing, but is there any better approach like special util function like:
this.trigger('doAction', MYAPP.util.intoObject{name: 'write', arg1: 1, arg2: 2});
that allows me to save object property names?
The properties should all be renamed consistently. For instance your example compiled to:
this.c("doAction", function(a) {
console.log(a.name);
console.log(a.a + " " + a.b)
});
this.d("doAction", {name:"write", a:1, b:2});
You can see that the properties were renamed in a non-breaking fashion. This behaviour is always the case unless the experimental type-based optimizations are enabled, but even then this specific case should be properly handled.
If you need the properties to absolutely not be renamed, you can define an interface in an extern file and type cast your methods to be of that type.
/** @externs */
/** @interface */
function myInterface() {}
/** @type {number} */
myInterface.prototype.arg1 = 0;
And in your example:
this.on('doAction', /** @param {myInterface} args */ function (args) {
console.log(args.name);
console.log(args.arg1 + ' ' + args.arg2);
});
this.trigger('doAction',
/** @type {myInterface} */ ({name: 'write', arg1: 1, arg2: 2}));
I just ran into this problem when working with a jquery method requiring object based properties. I solved it by placing all the key names in quotes and then closure compiler didn't mess with them.
So the code above would become:
this.trigger('doAction', {'name': 'write', 'arg1': 1, 'arg2': 2});