Skip to content

Restricting object generation

thepian edited this page Oct 11, 2012 · 2 revisions

By default a generator will create a new Object every time. You can however restrict it to return the same instance every time, to reuse previous ones based on the parameters.

Restrictions are applied just as the DOM is ready. You can change the restrictions at any point before that. It is often useful to keep them separate from the constructor declarations, so you can configure a different set of restrictions for testing.

function OpenWindow(url) {
    // called when window is opened
}
OpenWindow.args = [
    ObjectType({ name:"url", "default":location, preset:true })
]
OpenWindow.discarded = function(instance) {
    // called window is closed
}; 
Resolver().set("windowing.OpenWindow", Generator(OpenWindow));  

Singleton

The simplest use of OpenWindow would be to create it for the current browser window. The first time you call the generator an instance is created and returned. Whenever you call it the same instance is returned.

Resolver()("windowing.OpenWindow").restrict({ singleton:true });

When the browser loads a new URL the discarded function is called for the instance just before.

The discarded functions are called in the reverse of the restrict calls to limit the situations of problematic cleanup dependencies.

Singleton Lifecycle

You might want to create the instance as soon as the window DOM is ready, and make it follow the life of the page. Note that in a future version where partial page replacement, the replacement is a lifecycle event that will recreate the object for the new URL.

Resolver()("windowing.OpenWindow").restrict({ singleton:true, lifecycle: "page" });

Reuse per Identifier

(not implemented yet)

If you specify an identifier function, or true for one named 'identifier' instances are reused by the value returned by the function.

OpenWindow.identifier = function(url) {
    return url.href? url.href : String(url);
}
...
Resolver()("windowing.OpenWindow").restrict({ identifier:true });

No Restrictions

You can remove previously set restrictions by calling restrict with no parameters.

Resolver()("windowing.OpenWindow").restrict({});

Clone this wiki locally