Main.js is initialized several times in preview

Hey,

I have this very annoying issue with Fuse. It’s been around for a while. Maybe it’s a bug or maybe I’m doing something wrong, anyway here’s the case:

I have a main UX that contains the main.js

<JavaScript File="js/Main.js" />

Inside that Main.js I have a MessageHandler.js that adds messages to view.

var MessageHandler = require('js/MessageHandler');

MessageHandler has a public method addNew() and I call this method on Main initialization few times to add some starting messages. MessageHandler has a data Observable that contains the messages. These are shown in MainView.ux.

Problem is that when I save the MainView.ux, the Main.js is initialized several times and all starting messages are added to data Observable again. Plus if I add more messages to the by clicking the button in UX those are added too. I expose this Observable for my MainView.ux like this:

module.exports.data = MessageHandler.data;

Also when the Main.js is initialized several times it starts to make the refreshing the preview very slow in larger project.

Probably easier if you try it out your self. I have stripped down a project that shows the issue.

http://www.simppa.fi/fuse/TestJSInit.zip

You should be able to reproduce this issue by building a local preview and then saving the MainView.ux again.

I’m on OSX and Fuse version is 0.20.2 (6524)

Thanks for the test case! We’ve seen this issue pop up a few times. I’ll make sure we have tickets on it internally and follow up.

Hi!

Sorry this took so long.

The behavior you are seeing is actually expected behavior in Fuse preview. Fuse does not completely reset the app in preview, it only recompiles and re-executes the minimal number of files.

This means that when MainVew.ux is edited, MessageHandler is not reset, resulting in an accumulation of event listeners etc.

The way to work around this is that whenever you subscribe an event listener, you must remember to add a corresponding unsubscribe. If you want the subscription to last the entire lifetime of your current module, you can use this pattern:

 var someGlobalModule = require("someGlobalModule");

 function eventHandler() {...}

 someGlobalModule.addListener(eventHandler);

 // Make sure the eventHandler is removed when the module is disposed
 module.disposed.push(function() { someGlobalModule.removeListener(eventHandler); })

I hope that helps, and again sorry for the long wait!