Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google JavaScript closure: defining a structure passed to many functions

As I'm strengthening my JavaScript code using the Google closure compiler, I ran in a problem for which I don't see an answer I like.

I have a simple class with 4 functions as such:

open:  function(settings) { ... },
close: function(settings) { ... },
hide:  function(settings) { ... },
show:  function(settings) { ... }

As you can see all the functions take in an object named settings. I can easily declare the settings with a strong typing definition such as:

/**
 * @param {{p1: string, p2: number, p3: function(string)}} settings The settings.
 */
open: function(settings) { ... };

This works, only I need to copy/paste the @param definition for each one of the open, close, hide, and show functions. So if I add a parameter, I'm to make sure that I update all 4 functions!

Is there a way to declare a type and then reuse it multiple times, without having to declare an actual JavaScript object? Something like this maybe?

/**
 * @deftype {{...}} some_name
 */

Or would you do that as an external definition so at least the execution environment doesn't see that definition?

P.S. the object in question never saves the settings. It uses that structure to hold data it generates (such as an identifier) and to know what the user wants the different functions to do. Each caller can have a different set of settings and the object itself can still act like a singleton (I need only one instance of the object to manage any number of windows).

like image 414
Alexis Wilke Avatar asked Sep 15 '26 09:09

Alexis Wilke


1 Answers

Yes, you can use @typedef:

/**
 * @typedef {{p1: string, ...}}
 */
var Settings;

and later:

/**
 * @param {Settings} settings The settings.
 */
open: function(settings) { ... };
like image 124
Felix Kling Avatar answered Sep 17 '26 23:09

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!