Flux architecture circular dependency - browserify

I have started learning Facebook's Flux architecture. I am trying to make a simple login screen. I have followed the flux-chat sample app to create the screen. I have a problem of circular dependency between ServerActionCreator and WebAPIUtils. Please see the code below.
ServerActionCreator.js
var AppDispatcher = require('../dispatcher/AppDispatcher');
var Constants = require('../constants/Constants');
var WebAPIUtils = require('../utils/WebAPIUtils');
var ActionTypes = Constants.ActionTypes;
module.exports = {
receiveLoginStatus: function(status){
AppDispatcher.handleServerAction({
type: ActionTypes.RECEIVE_LOGIN_STATUS,
status: status
});
},
loginSubmit: function(data){
WebAPIUtils.login(data);
}
}
WebAPIUtils.js
var ServerActionCreator = require('../actions/ServerActionCreator');
module.exports = {
login: function (data) {
//Mock server API call
var status = JSON.parse('{"status":"success"}');
ServerActionCreator.receiveLoginStatus(status);
}
};
As you can see ServerActionCreator depends on WebAPIUtils and WebAPIUtils depends ServerActionCreator.
I think, due to circular dependency WebAPIUtils becomes an empty object and I am getting "undefined is not a function" error when loginSubmit function in ServerActionCreator is called. Screenshot below.
How to handle this scenario? or Is there any alternative way? Any help is much appreciated.

Whenever you have a circular dependency between modules, a common solution is to either combine the modules or to create a third entity that will break the cycle.
In your case, I'd argue that you could move loginSubmit to a different action creators module. It's actually a user action, not a sever action, anyway. So maybe loginSubmit could go in UserActionCreators.js along with any number of other user action creator methods.
Another solution to your problem (and to circular dependencies in general) is to make your methods more pure, removing dependencies and instead passing in dependencies as arguments. So WebAPIUtils.login() could take a second argument, which would be the success callback. Thus:
WebAPIUtils.login(data, ServerActionCreator.receiveLoginStatus)

Related

StimulusJS - how to ensure controller has all the necessary targets?

I'm trying to find a way to make my Stimulus controller more robust and maintainable by checking that all the required targets are present. If something is missing, I would like it to fail fast and loud.
Below is what I'm using so far:
export default class extends Controller {
static targets = ['name'];
connect() {
if (!that.hasNameTarget) {
throw new Error('expected to find name target');
}
}
}
Perhaps someone knows of a more idiomatic/clean solution?
Option 1 - use the Stimulus debugger tooling
Stimulus has a debug mode that logs out info/warnings etc for Stimulus controllers. You can enable this by stimulus.debug = true;
You can call this in your own controllers via this.application.logDebugActivity() - see https://github.com/hotwired/stimulus/blob/main/src/core/application.ts#L95
export default class extends Controller {
static targets = ['name'];
connect() {
if (!that.hasNameTarget) {
this.logDebugActivity(this.identifier, 'error', { message: 'target missing'});
throw new Error('expected to find name target');
}
}
}
Option 2 - Use the window.onerror callback
If you keep your current code where an error is thrown, Stimulus will not 'break' anything where possible as all calls within Stimulus use try/catch.
However, you can ensure that your error does something 'loud' by creating a onerror function.
See docs - https://stimulus.hotwired.dev/handbook/installing#error-handling
See an example where this can be used for something like Sentry https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror
You could also just be really loud and block the UI with something similar to this.
window.onerror = (message, url, lineNo, columnNo, error) => {
document.body.style.backgroundColor = 'red';
window.alert(message);
}
Reminders
Remember to only enable these debugging features in local development, you can do this with something like Webpack environment variables but this will be different depending on your tooling.
In production though you may want to push your onerror calls to whatever logging infrastructure you have.
stimulus.debug mode is quite 'noisy' and may be too much information, depending on your set up.

Mocha and jsdom - How to set a window variable

I know you're not supposed to do this, but I'm trying to write some tests with legacy code still using requirejs that have a few window variables floating around.
Basically I'm trying to write a mocha test and include some predefined global variables that a different file would use later. I'm trying to do the following, but it seems the global variable "container" isn't populated when accessing it later.
global.document = require('jsdom').jsdom('<html></html>');
global.window = document.defaultView;
global.$ = require('jquery')(window);
// this should be available everywhere as far as I can tell...
global.container= {};
global.window.container= global.container;
// legacy scripts still using requirejs, so we need to load the require config here
var requirejs = require('testing-setup').requirejs;
// chai is nice
require('chai').should();
describe('model tests', function () {
var model;
// before we begin the tests, we need to require in all the necessary modules
before(function (done) {
window.container= {
dateFormat: false
};
requirejs(['Model', 'common', 'date'], function (Model) {
// load some dummy data out of a file
model= new Model(require('./test-data.js').item);
done();
});
});
// run some more tests down here, I'll spare you those
});
The script being loaded called "common" above has a reference to the global "container" object that lives on the window. Apparently what I have is not correct. Is there no way to set up a shared global variable in jsdom? I know it's not the standard way of doing things, so please spare the lectures. Refactoring all that legacy code right now is not really a feasible option.
Ah, it turns out this is the correct way of doing it. It appears the jsdom/nodejs differentiate the difference between window and global. If you want something to be available everywhere in every file in that session, it needs to be on the global namespace. The window is explicitly window.

Knockout components using OOP and inheritance

I was hoping I could get some input on how to use Knockout components in an object-oriented fashion using Object.create (or equivalent). I'm also using Postbox and Lodash, in case some of my code seems confusing. I've currently built a bunch of components and would like to refactor them to reduce code redundancy. My components, so far, are just UI elements. I have custom input boxes and such. My initial approach was as follows, with some discretion taken to simplify the code and not get me fired :)
// Component.js
function Component() {
var self = this
self.value = ko.observable()
self.initial = ko.observable()
...
self.value.subscribeTo('revert', function() {
console.log('value reverted')
self.value(self.initial())
}
}
module.exports = Component
// InputBox.js
var Component = require('./Component')
var _ = require('lodash')
function InputBox(params) {
var self = this
_.merge(self, params) // quick way to attach passed in params to 'self'
...
}
InputBox.prototype = Object.create(new Component)
ko.components.register('input-box', InputBox)
Now this kind of works, but the issue I'm having is that when I use the InputBox in my HTML, I pass in the current value as a parameter (and it's also an observable because the value is retrieved from the server and passed down through several parent components before getting to the InputBox component). Then Lodash merges the params object with self, which already has a value observable, so that gets overwritten, as expected. The interesting part for me is that when I use postbox to broadcast the 'revert' event, the console.log fires, so the event subscription is still there, but the value doesn't revert. When I do this in the revert callback, console.log(self.value(), self.initial()), I get undefined. So somehow, passing in the value observable as a parameter to the InputBox viewmodel causes something to go haywire. When the page initially loads, the input box has the value retrieved from the server, so the value observable isn't completely broken, but changing the input field and then hitting cancel to revert it doesn't revert it.
I don't know if this makes much sense, but if it does and someone can help, I'd really appreciate it! And if I can provide more information, please let me know. Thanks!
JavaScript does not do classical inheritance like C++ and such. Prototypes are not superclasses. In particular, properties of prototypes are more like static class properties than instance properties: they are shared by all instances. It is usual in JS to have prototypes that only contain methods.
There are some libraries that overlay a classical-inheritance structure onto JavaScript. They usually use "extends" to create subclasses. I don't use them, so I can't recommmend any in particular, but you might look at Coffeescript if you like the classical-inheritance pattern.
I often hear "favor composition over inheritance," but I generally see a lot of emphasis on inheritance. As an alternative, consider Douglas Crockford's "class-free object-oriented programming", which does away with inheritance entirely.
For what you're trying to do here, you probably want to have InputBox initialize itself with Component, something like:
function InputBox(params) {
var self = this
Component.bind(self)(); // super()
_.merge(self, params) // quick way to attach passed in params to 'self'
...
}
The new, merged, value will not have the subscription from Component, because the subscription is particular to Component's instance of the observable, which will have been overwritten.
To everyone who responded, thank you very much! I've found a solution that works better for me and will share it here in case anyone is interested.
// Component.js (only relevant parts shown)
function Component(params) {
var self = this
_.merge(self, params)
self.value.subscribeTo('some event', function() {
// do some processing
return <new value for self.value>
}
module.exports = Component
// InputBox.js
var Component = require('./component')
function InputBox(params) {
var self = this
Component.call(self, params)
}
By taking this approach, I avoid the headache of using prototypes and worrying about the prototype chain since everything Component does is done directly to the "inheriting" class. Hope this helps someone else!

How to override dojo's domReady

I want to override dijit._CssStateMixin's domReady() method.
Is there any way to override that instead of changing the listener mechanism in Dojo.
I tried overriding _cssMouseEvent() method in simple javascript, but it still does invoke dijit's _cssMouseEvent() from domReady().
I have tried following approach:
dojoConfig = {
map: {
'dijit/_CssStateMixin': {
'dojo/domReady': 'app/noop'
}
}
};
I have added 'app' folder and then 'noop.js' inside that.
noop.js has nothing in it:
define([], function () {
return function () {};
});
Even after this I can see that dijit.js's _CssStateMaxin domReady() getting called from listener.apply (code snippet pasted below)
var addStopImmediate = function(listener){
return function(event){
if(!event.immediatelyStopped){// check to make sure it hasn't been stopped immediately
event.stopImmediatePropagation = stopImmediatePropagation;
return listener.apply(this, arguments);
}
};
}
If your ultimate goal is to prevent the domReady callback in dijit/_CssStateMixin from running, your simplest bet is likely to re-map dojo/domReady to a different module that doesn't call the callback at all, when loaded via dijit/_CssStateMixin.
NOTE: Stripping out these handlers might have adverse visual effects on Dijit widgets which inherit _CssStateMixin, since it may hinder the application of Dijit CSS classes related to hover and focus. But if your concern is that _CssStateMixin is hampering performance, it may at least be worth a try to confirm or deny your suspicion.
First we have to create a simple module that returns a function that does nothing, which we will later substitute for dojo/domReady when loaded by dijit/_CssStateMixin, so that it can still call domReady but it won't execute the callback it passes.
For simplicity's sake I'll assume you already have a custom package that you can easily add a module to; for this example I'll assume it's called app. Let's create app/noop:
define([], function () {
return function () {};
});
Now let's configure the loader to map app/noop in place of dojo/domReady specifically when loaded by dijit/_CssStateMixin:
var dojoConfig = {
...,
map: {
'dijit/_CssStateMixin': {
'dojo/domReady': 'app/noop'
}
},
...
};
Now the offending domReady callback should no longer be run.
If you're curious about map, you can read more about it in this SitePen FAQ.

How to register component interface in wxwebconnect?

I'm doing an experiment with wxWebConnect test application, incorporating the xpcom tutorial at "http://nerdlife.net/building-a-c-xpcom-component-in-windows/"
I adapt MyComponent class as necessary to compile together with testapp.exe (not as separate dll), and on MyApp::OnInit I have the following lines:
ns_smartptr<nsIComponentRegistrar> comp_reg;
res = NS_GetComponentRegistrar(&comp_reg.p);
if (NS_FAILED(res))
return false;
ns_smartptr<nsIFactory> prompt_factory;
CreateMyComponentFactory(&prompt_factory.p);
nsCID prompt_cid = MYCOMPONENT_CID;
res = comp_reg->RegisterFactory(prompt_cid,
"MyComponent",
"#mozilla.org/mycomp;1",
prompt_factory);
Those lines are copied from GeckoEngine::Init(), using the same mechanism to register PromptService, etc. The code compiles well and testapp.exe is running as expected.
I put javascript test as below :
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const cid = "#mozilla.org/mycomp;1";
obj = Components.classes[cid].createInstance();
alert(typeof obj);
// bind the instance we just created to our interface
alert(Components.interfaces.nsIMyComponent);
obj = obj.QueryInterface(Components.interfaces.nsIMyComponent);
} catch (err) {
alert(err);
return;
}
and get the following exception:
Could not convert JavaScript argument arg 0 [nsISupport.QueryInterface]
The first alert says "object", so the line
Components.classes[cid].createInstance()
is returning the created instance.
The second alert says "undefined", so the interface nsIMyComponent is not recognized by XULRunner.
How to dynamically registering nsIMyComponent interface in wxWebConnect environment ?
Thx
I'm not sure what is happening here. The first thing I would check is that your component is scriptable (I assume it is, since the demo you copy from is). The next thing I would check is whether you can instantiate other, standard XULRunner components and get their interface (try something like "alert('Components.interfaces.nsIFile');" - at least in my version of wxWebConnect this shows an alert box with string "nsIFile".
Also, I think it would be worth checking the Error Console to make sure there are no errors or warnings reported. A magic string to do that (in Javascript) is:
window.open('chrome://global/content/console.xul', '', 'chrome,dialog=no,toolbar,resizable');