Skip to content

Instantly share code, notes, and snippets.

@ca0v
Last active December 29, 2015 17:18
Show Gist options
  • Save ca0v/7702794 to your computer and use it in GitHub Desktop.
Save ca0v/7702794 to your computer and use it in GitHub Desktop.
Reloads modules and widgets when corresponding AMD module is modified on the server. Uses SignalR Hub for notification. Facilitates development of widgets and singletons without the need to refresh the browser. State is captured during "unload".
define(["dojo/dom-construct", "dijit/registry"], function (domConstruct, registry) {
return function (myHub) {
myHub.client.reload = function (mid) {
var mods = mid.split(",");
// call unload on old modules
require(mods, function () {
var factories = Array.prototype.slice.apply(arguments);
var state = mods.map(function (mid, i) {
return factories[i].unload ? factories[i].unload(mid) : {};
});
// call unload on old widgets
var widgets = registry.toArray()
.filter(function (w) {
return !!w.unload;
})
.filter(function (w) {
return factories.some(w.isInstanceOf);
});
// capture widget state
var widgetState = widgets.map(function (w) {
var base = w.constructor._meta.bases[0];
var factoryIndex = factories.indexOf(base);
return {
state: w.unload(),
parentNode: w.domNode.parentNode,
factoryIndex: 0 <= factoryIndex ? factoryIndex : null,
constructor: 0 > factoryIndex ? w.constructor : null
};
});
// destroy widgets
widgets.forEach(function (w) {
w.destroyRecursive();
});
// unload old modules if possible
require.undef && mods.forEach(require.undef);
// load new modules and call reload with state from prior module
require(mods, function () {
var factories = arguments;
mods.forEach(function (mid, i) {
factories[i](state[i]);
});
widgetState.map(function (state) {
factory = state.constructor || factories[state.factoryIndex];
var w = new factory(state.state, domConstruct.create("div", {}, state.parentNode));
});
});
});
};
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment