Limiting the scope of JavaScript includes...?

In a an application that contains different views that use different JavaScript visualizations, I am experiencing that the JS includes bite each other due to Vaadin’s ‘single page’ concept.

E.g. Both visualisation JS includes define var height, width. The first time one of these pages gets loaded, this goes well. The second time another page gets loaded, I get a nice SyntaxError: Identifier 'height' has already been declared, obviously since these variables are defined in the same global scope.

Is there a way to isolate JavaScript files’ scope to only the view they are included in…?

Of course, I could prefix all variables to make them unique, but I would rather not do that.

Thanks.

Are these JS files written by you or somebody else? JavaScript modules are automatically scoped to the module so they will not leak variables into the global scope. Instead you can choose what, if anything, you put into window.*.

Artur Signell:
Are these JS files written by you or somebody else? JavaScript modules are automatically scoped to the module so they will not leak variables into the global scope. Instead you can choose what, if anything, you put into window.*.

I have both actually:

Page page = UI.getCurrent().getPage();

// add D3v5 library
page.addJavaScript("frontend://js/v5/d3.js");

// add animation code
page.addJavaScript("frontend://js/v5/animation.js");

// start rendering animation
page.executeJs("alreadyRendered=false;renderAnimation();");

Perhaps I am not adding them in the right way…? Thanks for your thoughts.

try using the @JsModule annotation to include the scripts in the view.

@JsModule("./js/v5/d3.js")
@JsModule("./js/v5/animation.js")

If you still experience the same error, try including the scripts in the parentLayout instead, which your two views share.