There are many times that I've needed to execute some code after a number of events have fired, and I've come up with counters and such but I feel there must be a better way.
For example, say five files need to be loaded, after which a UI component will become active.
If I set up a counter that increments each time a file is requested, then decrements each time one has loaded, I run the risk that the first two or three files may somehow get completely loaded before my code gets around to requesting the fourth and fifth, which would mean that my counter would be at zero when I still have two files to load, thus allowing the UI component to be prematurely activated.
There are some cases where you could know the number that need to be loaded before the requests go out, but it's possible that the first file contains the paths (and therefore the number of) files. (And this file-loading scenario is only an example of the pattern I'm trying to explain.)
Does anyone have an elegant solution for this? (Does my description make sense?) Thanks!
You could do something with a task framework like spicelib
Using that as an example
Create a FileRecursionLoadTask which grabs a file and completes when that file and any references it makes are loaded.
Add each FileRecursionLoadTask to a SequentialTaskGroup.
When the TaskGroup is completed, then you know all of the file loads have completed.
There are also plenty of other task frameworks which you might like better. For example, Spring ActionScript also has one.
Before executing a request, store a reference (a unique request uri, the loader object or a special command object) in a list. When a loader has finished, remove that object and call a function that checks if there are remaining active tasks in the list.
This isn't specific to file requests nor request in general, it can be used for anything that needs to wait for multiple actions to finish. Multiple list can be used to process multiple types of action at the same time. The object stored in the list could be implemented as a command object, which could provide more information about the task. This is called command pattern.
If you're doing just loading, like Jacob, I would also suggest a library that handles loading
If the case of a more complicated situation like mixing loaders and other event listeners, I would suggest using an event that fires whenever there is any change to any of the dependencies. In addition all the objects/classes would have a state.
Then I would create a listener adding function for the class that would need to do the function or initiate it, that would have 3 parameters
object with event dispatcher (assuming they all use the same update event) ie. assetLoader
name of object state ie. headerLoaded
state value's desired ie. true
the function would add the listener to a chain of listeners, and any time any of the listeners fires, all objects would check if the state value.
This would allow for regression as well (like when a user presses a button, the content starts loading, but then the user presses cancel, even if all the assets load, the state of one object would be false, thus not allowing the item to complete) If you were using counters, it would be the equivalent to adding instead of subtracting, but much more reliable.
Looking for a design pattern? Try the command pattern (http://johnlindquist.com/2010/09/09/patterncraft-command-pattern/)
(The video is a great example of what command pattern is and how it works - using Starcraft as an example.
The implementation is that you queue your load commands so that they do not execute out of order, and you can add the enable or disable commands to your command que. So the command pattern will play back your commands something like: load, load, load, enable ui item, load, load, enable another item
Good luck
Related
How to check if a UiInstance is already running? I need to know so that I know whether to use UiApp.getActiveApplication() or UiApp.createApplication(); The issue is that the functions may not be called in a particular order.
No offense but this question doesn't make a lot of sense to me... There can be only one UiApp instance and in a standalone app it must start with a doGet() so I wonder how you could start an app without starting by the app creation ?
Once you have created this instance it lives as long as you close your browser window of you hide all the possible source of user actions (for example hiding all the widgets or disabling all the buttons) and everything that happens in between is either the result of a handler call or a direct function call in the script, all of which are necessarily subsequent and therefor using getActiveApplication().
If I missed something (which is entirely possible of course) please explain.
Edit : following your comment :
In case you use UiApp embedded in a document the situation is a bit different but not so much :
2 different cases :
Dialogs :each time you create a new one it will appear "over" the existing one but won't be "aware" of it, i.e none of the first UI values will be available to the next one. So it's a better idea to close each one before creating a new one (app.close();return app;) otherwise you'll have to manually close each "layer" successively since I guess it wouldn't be a good idea to keep the dialog on the screen all along :-)
Data passing from one instance to the other must be handled using some kind of storage.
Sidebar : what I'd suggest is to create a starting UI in the sidebar that creates the Ui (showing a welcome message or a menu for example) and let all the other function get this Ui Instance using getActiveApplication() , that will avoid the UI "flashing" while it's been redrawn and allow you to play with all the values all along.
In both case the choice is really yours but the practice I suggest works better and gives you full control on what happens.
I'm building a crossplatform HTML/Javascript app for iOS and Android using PhoneGap and jQueryMobile, and I am upgrading my app with (among others) a few new fields in one table of the local database (localdatabase/websql).
The challenge
I want to make sure that when the database is expanded with the new table fields, the existing user data, the user data will not be removed or become locked in an inaccesible older version of the database.
The background:
My app has a local database of the user's data (incomes and expenses, plus a few settings). These data need to be persitent, and the way to go, back when I started, was using the HTML5 localDatabase functionality, since that is both persistent, and available for the iOS and Android browsers as well as for most desktop browsers.
I am using a Javascript plugin/library/thingy called persistenceJS to make dealing with the localdb a little easier. But my question is not really specific to persistenceJS.
I am working on a new version of the app, which makes uses of a few new fields in the Settings table. So when these users download the new app and run it, it must test if their Settings table contains this field or not, and if not it must create the field.
How do I do this testing? I see two lines of thought:
Use the database label... that's used in the openDatabase function. This seems to be used by some developers to store a version number.
My trouble with this option is I only know how to use openDatabase to, well, open a database (and create a new one if none exists), and run a callback specifically if the database did not yet exist.
So if I open the table while specifying something like "v2" in the label, will it create a new table? If so, will it copy the old table's values into the new one?
Check for the existence of the table fields...
I could use openDatabase and then test for the existence of the table fields. If they don't, I could add them. The test would be run every time a user opens their app, which seems a little primitive.
By the way:
I know webSQL/localDb has been deprecated by the overlords, but it's still my tool and I want to stick to it for now.
I've found the answer here: http://blog.maxaller.name/2010/03/html5-web-sql-database-intro-to-versioning-and-migrations/.
Basically, you just apply the changeVersion method with the old and the new version label. If you didn't have a label, then the old label is "". While relabeling, webSQL quietly applies the new schema to the old database. Which in my case means adding the new fields.
The tutorial I linked to is really awesome (and so is the functionality).
I'm adding another answer because I've learned more about localDb opendatabase and migrating it.
As a reminder, openDatabase takes these parameters:
name - (string) name of the database
version label - (string) the version you want to open
display label - (string) a pretty useless display name that seems to be used nowhere
max size - (int) largest safe size is 5 * 1024 * 1024
newly created -= (function) to be fired if the db did not previously exist
It's wisest to assign the output of openDatabase to a variable. I.e.
myapp.db = openDatabase('mydb','','My database',5*1024*1024,newlyCreatedCallback);
First off, it seems wise to make use of the 'newly created' callback that's available as the fifth argument of openDatabase. It will fire only if there was no database with the parameters you specified. To prevent this callback from firing when your database did already exist, make sure you have the name, display label and maximum size set to exactly the values that were used to first create the database.
The reason to do this is that if the database was first created, you know for sure that you will not need to do any migrations. You can go straight to a function that adds tables and fields. I recommend using persistenceJS, a tool that helps you read and manipulate the local database.
Before calling openDatabase, it's wise to use jQuery to create a custom event 'dbopen' whose handler will execute migrations. This handler can be triggered by two events. The first is the 'newly created' callback we just discussed. The second is a setInterval that you define after call openDatabase. The interval must check for the existence of the myapp.db variable that you assigned the openDatabase output to.
The reason to create the dbopen custom event is that if you added a 'newly created' callback which triggers a whole bunch of events and continues the flow of your code afterwards, you will want a similar process for the 'not newly created' scenario. There is no callback for openDatabase that does this, so you will have to manually detect the creation of the local database and trigger 'dbopen' as soon as it has come into existence.
I use a window.setInterval for this. Make sure that you create the custom 'dbopen' event using jquery's .one() function, which will fire at most once. Otherwise if the database was newly created, you will fire the open event once when the 'newly created' callback fires, and once when the myapp.db variable comes into existence.
I have a tabbed dialog that has 4 tabs. The parent component is an mx:TabNavigator and each of the tab's views are custom MXML components inside an s:NavigatorContent. The data for 3 of the tabs has to be sent as one unit to a back end service. I'm trying to work out the best way to have the 3 tabs access the data that's to be sent down as one unit. I currently have one .mxml file that defines the top level mx:TabNavigator with each of the 4 tabs representing the s:NavigatorContent defined in it's own separate.mxml file to keep the file sizes fairly short. My current approach is to have each of the tabs load their data from the back end service in their creationComplete handlers and store it in a common class for the data model shared by the 3 tabs. This solution is OK except:
The creation complete handler for the first tab is called on application startup even though it's not the first visible component (i.e. there are other parts of the UI that the user sees first). I'd prefer to have true lazy loading where the data is not loaded until the tab becomes visible to the user.
If the user edits data on the first tab, then navigates to the second tab for the first time without hitting the apply button, changes made in the first tab are lost, because the creation complete handler of the 2nd tab will load the data model shared by the 3 tabs.
What I ideally want is:
True lazy loading; data is not loaded until the user clicks on a tab and it becomes visible.
Have it so that when the user hits apply on any of the 3 tabs the current entries on each of the 3 tabs is sent down to the back end service.
Thanks very much if anyone can advise on this. I can explain in further detail if needed.
I'm trying to work out the best way to have the 3 tabs access the data
that's to be sent down as one unit.
Best is always subjective. The easiest way is going to be to create a single variable for your shared data, and pass that instance into each relevant tab.
In some cases you may store the data in some central location, and the use Dependency Injection to inject that data into the relevant tab components that need it. Dependency Injection is implemented by a bunch of Flex frameworks, such as RobotLegs or Swiz.
An alternate option is to use a Singleton approach or static variables on a class to share the data between your multiple tabs.
My current approach is to have each of the tabs load their data from
the back end service in their creationComplete handlers
Why use creationComplete? The creationComplete event is fired after the component has completed it's layout routines and layout routines of it's children, and then everything is ready to use. I assume the act of loading more data, will force a lot of your components to have to go through their rendering process again. You may consider moving this into an earlier spot during the lifecycle, such as initialize or preinitialize.
1) The creation complete handler for the first tab is called on
application startup even though it's not the first visible component
(i.e. there are other parts of the UI that the user sees first). I'd
prefer to have true lazy loading where the data is not loaded until
the tab becomes visible to the user.
This would be expected behavior, based on the way that TabNavigators initialize. You can look at creationPolicy for more information. You can rewrite your 'load data' method to operate on the show method of the component, perhaps?
2) If the user edits data on the first tab, then navigates to the
second tab for the first time without hitting the apply button,
changes made in the first tab are lost, because the creation complete
handler of the 2nd tab will load the data model shared by the 3 tabs.
You can force a save of the data on the hide event of the component. Or possibly on the change event o the TabNavigator.
Could someone explain when does local SharedObject triggers event handlers added via addEventListener?
I have tried and it doesn't trigger, after flushing.
For example i have two object.swf both in separate browser tabs.
I'm adding data inside object.swf on one tab and want event to be triggered in object.swf from another tab.
Is it possible with native functionality and without remote type of SharedObject?
Ofc i could write infinite loop and check local storage for changes, but it's the last solution i would like to implement. :D
I was reading docs and played with example over there, but it doesn't trigger event, even if it is added before flushing.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html
Thanks.
Only remote shared objects dispatch events. If you want to communicate between two swfs, try LocalConnection instead. http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/LocalConnection.html
I'm trying to restart my flash piece with a restart button. I use gotoAndPlay(0), but nothing happens. I'm sure the click event handler is being called because I used a trace statement to verify.
rs.addEventListener(MouseEvent.CLICK, restart);
function restart(event:MouseEvent):void {
gotoAndPlay(0);
}
The first frame is frame 1, not 0.
Not sure why adobe decided against making frames zero-based, but they did :/
If you have added objects to the stage, like buttons or graphics, but never actually used the stage's timeline, the stage will start and stay at the first frame. So 'gotoAndPlay' wont work in this case. It would be only useful to restart an animation anyway, as it won't reset any code on its own.
You need to decide what parts you actually want to reset and what parts you can keep. You probably don't want to remove assets from memory you loaded at the beginning just to download them again. Some objects may be kept, others should be removed.
As far as I know there is no easy way to reset a flash application, other than maybe reloading the whole page. Here are some general steps to 'reset' an application by hand:
Create a method for your initialization code:
object creation, adding to the display list, adding event listeners.
On a click: remove all objects from the stage, remove all their event listeners.
Call the initialization method again.
Ideally you set the references in your init method to a new variable so the old ones can be garbage collected. Depending on the code structure you may have to manually set some to null. Make sure you don't keep any references to objects you don't need any more.