Imported module default.register is not a function - javascript

I'm trying to port a Node/React system over to ES6 although I'm encountering an error when compiling.
GameSettingsStore.js:91 Uncaught TypeError: _dispatcher_AppDispatcher__WEBPACK_IMPORTED_MODULE_1__.default.register is not a function at Module../src/client/stores/GameSettingsStore.js
This line that appears to be throwing an error comes from this specific line/function:
import AppDispatcher from '../dispatcher/AppDispatcher';
AppDispatcher.register((payload) => {
const { action } = payload;
switch (action.actionType) {
case Constants.ActionTypes.SET_CONTROLS_SIZE:
GameSettingsStore._setControlsSize(action.controlsSize);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.SET_GRAPH_MODE:
GameSettingsStore._setGraphMode(action.graphMode);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.TOGGLE_HOYTKEYS_STATE:
GameSettingsStore._toggleHotkeysState();
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.IGNORE_USER:
GameSettingsStore._ignoreUser(action.username);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.APPROVE_USER:
GameSettingsStore._approveUser(action.username);
GameSettingsStore.emitChange();
break;
default:
GameSettingsStore.emitChange();
break;
}
return true;
});
And then the dispatcher system I'm using is the old Facebook one:
import invariant from 'invariant';
export default function () {
let _lastID = 1;
const _prefix = 'ID_';
function Dispatcher() {
this.$Dispatcher_callbacks = {};
this.$Dispatcher_isPending = {};
this.$Dispatcher_isHandled = {};
this.$Dispatcher_isDispatching = false;
this.$Dispatcher_pendingPayload = null;
}
Dispatcher.prototype.register = function (callback) {
const id = _prefix + _lastID++;
this.$Dispatcher_callbacks[id] = callback;
return id;
};
Dispatcher.prototype.unregister = function (id) {
invariant(
this.$Dispatcher_callbacks[id],
'Dispatcher.unregister(...): `%s` does not map to a registered callback.',
id
);
delete this.$Dispatcher_callbacks[id];
};
Dispatcher.prototype.waitFor = function (ids) {
invariant(
this.$Dispatcher_isDispatching,
'Dispatcher.waitFor(...): Must be invoked while dispatching.'
);
for (let ii = 0; ii < ids.length; ii++) {
const id = ids[ii];
if (this.$Dispatcher_isPending[id]) {
invariant(
this.$Dispatcher_isHandled[id],
'Dispatcher.waitFor(...): Circular dependency detected while '
+ 'waiting for `%s`.',
id
);
continue;
}
invariant(
this.$Dispatcher_callbacks[id],
'Dispatcher.waitFor(...): `%s` does not map to a registered callback.',
id
);
this.$Dispatcher_invokeCallback(id);
}
};
Dispatcher.prototype.dispatch = function (payload) {
invariant(
!this.$Dispatcher_isDispatching,
'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.'
);
this.$Dispatcher_startDispatching(payload);
try {
for (const id in this.$Dispatcher_callbacks) {
if (this.$Dispatcher_isPending[id]) {
continue;
}
this.$Dispatcher_invokeCallback(id);
}
} finally {
this.$Dispatcher_stopDispatching();
}
};
Dispatcher.prototype.isDispatching = function () {
return this.$Dispatcher_isDispatching;
};
Dispatcher.prototype.$Dispatcher_invokeCallback = function (id) {
this.$Dispatcher_isPending[id] = true;
this.$Dispatcher_callbacks[id](this.$Dispatcher_pendingPayload);
this.$Dispatcher_isHandled[id] = true;
};
Dispatcher.prototype.$Dispatcher_startDispatching = function (payload) {
for (const id in this.$Dispatcher_callbacks) {
this.$Dispatcher_isPending[id] = false;
this.$Dispatcher_isHandled[id] = false;
}
this.$Dispatcher_pendingPayload = payload;
this.$Dispatcher_isDispatching = true;
};
Dispatcher.prototype.$Dispatcher_stopDispatching = function () {
this.$Dispatcher_pendingPayload = null;
this.$Dispatcher_isDispatching = false;
};
return Dispatcher;
}
I'd much prefer to use a better alternative, or at least fix this issue if anyone could point me in the right direction?

The default export looks like an (obsolete) wrapper function. You might need to "unwrap" it first:
import AppDispatcherWrapper from '../dispatcher/AppDispatcher';
const AppDispatcher = AppDispatcherWrapper();
AppDispatcher.register((payload) => {
// ...
});

Related

javascript multiple function callback syntax

I can't wrap my head around callback syntax, can you please help me re-write my code so that it executes in this order:
MenuBuilder.load()
MenuBuilder.draw()
Translator.load()
(in my case it executes in this order MenuBuilder.load(), Translator.load(), MenuBuilder.draw() so it doesn't do what I want)
onload.js
import MenuBuilder from "./menu-builder.js";
import Translator from "./translator.js";
var menuBuilder = new MenuBuilder();
var translator = new Translator();
menuBuilder.load();
translator.load();
menu-builder.js
"use strict"
class MenuBuilder {
constructor() {
this._nav = document.getElementsByTagName("nav")[0];
this._url = window.location.href;
}
load() {
console.log("MenuBuilder.load() start");
fetch(`/json/menu.json`)
.then((res) => res.json())
.then((jsonMenu) => {
this.draw(jsonMenu);
})
/*.catch(() => {
console.error(`Could not load ${this._lang}.json.`);
});*/
console.log("MenuBuilder.load() end");
}
draw(jsonMenu) {
console.log("MenuBuilder.draw(jsonMenu) start");
var htmlMenu = `<div id="siteTitleDiv"><p id="siteTitle" data-i18n="general.title"></p><p id="siteTitleShadow" data-i18n="general.title-shadow"></p><p id="siteSubtitle"data-i18n="general.subtitle"></p></div><ul>`;
for(var i = 0; i < jsonMenu.length; i++) {
var menuItem = jsonMenu[i];
var regexp = /http:\/\/cypher-f\.com\/(([a-z\-]*\/)?([a-z\-]*\/))?/g;
var fullPage = "something format_abc";
var match = regexp.exec(this._url);
var level_1 = match[1];
var level_2 = match[3];
var parent = match[2];
var full_suffix = match[0];
if ((parent == null) || (menuItem.parent === parent)) {
var material_icon = menuItem["material-icon"];
var href = menuItem["href"];
var i18n = menuItem["data-i18n"];
htmlMenu += `<li><i class="material-icons">${material_icon}</i></li>`;
}
}
htmlMenu += `</ul>`;
this._nav.innerHTML = htmlMenu;
console.log("MenuBuilder: nav.innerHTML");
console.log(this._nav.innerHTML);
console.log("MenuBuilder: document.elements");
console.log(document.querySelectorAll("[data-i18n]"));
console.log("MenuBuilder.draw(jsonMenu) end");
}
}
export default MenuBuilder;
translator.js
"use strict"
class Translator {
constructor() {
this._lang = this.getLanguage();
this._elements = document.querySelectorAll("[data-i18n]");
}
getLanguage() {
var lang = navigator.languages ? navigator.languages[0] : navigator.language;
return lang.substr(0, 2);
}
load(lang = null) {
console.log("Translator.load() start");
console.log("this._elements");
console.log(this._elements);
if (lang) {
this._lang = lang;
}
else {
var re = new RegExp("lang=([^;]+)");
var value = re.exec(document.cookie);
var cookieLang = (value != null) ? unescape(value[1]) : null;
if (cookieLang) {
this._lang = cookieLang;
}
}
fetch(`/i18n/${this._lang}.json`)
.then((res) => res.json())
.then((translation) => {
this.translate(translation);
})
.then(this.toggleLangTag())
.then(document.cookie = `lang=${this._lang};path=/`)
/*.catch(() => {
console.error(`Could not load ${this._lang}.json.`);
});*/
console.log("Translator.load() end");
}
translate(translation) {
console.log("Translator.load(translation) start");
this._elements.forEach((element) => {
var keys = element.dataset.i18n.split(".");
var text = keys.reduce((obj, i) => obj[i], translation);
if (text) {
element.innerHTML = text;
}
else {
element.innerHTML = `key ${keys} not found for ${this._lang}!`
}
});
console.log("Translator.load(translation) end");
}
toggleLangTag() {
if (document.documentElement.lang !== this._lang) {
document.documentElement.lang = this._lang;
}
}
switchLanguage(translator) {
var availableLang = ["en", "fr"];
var currentLangIndex = availableLang.indexOf(translator._lang);
var nextLang = availableLang[(currentLangIndex + 1)%availableLang.length];
translator.load(nextLang);
}
}
export default Translator;
I'm sorry I know this is kind of a newbie question but I haven't programmed in three years.
You're working with Promises here, so you want to stick with that paradigm. Return the promise that is returned from the fetch call, then "chain" off of that promise to call the translator.
load() {
console.log("MenuBuilder.load() start");
// The return here gives control of the promise to the caller...
return fetch(`/json/menu.json`)
.then((res) => res.json())
.then((jsonMenu) => {
this.draw(jsonMenu);
})
/*.catch(() => {
console.error(`Could not load ${this._lang}.json.`);
});*/
console.log("MenuBuilder.load() end");
}
So back in onload.js you can use the promise returned from menuBuilder.load() to call translator.load() after menuBuilder.load() is done.
import MenuBuilder from "./menu-builder.js";
import Translator from "./translator.js";
var menuBuilder = new MenuBuilder();
var translator = new Translator();
menuBuilder.load().then(() => translator.load());

How to stop executing Javascript function containing infinite loop after some time

Suppose I have following piece of code that contains an infinite loop:
function infiniteLoop() {
while(true) {
//do something, eg.
document.getElementById("someID").innerHTML = "Blah";
}
}
If we execute this code in an online compiler, browser will crash. I want to prevent that from happening. So I tried following code following this answer:
function willNotCrash() {
myVar = setInterval(infiniteLoop, 5000);
setTimeout(function(){
clearInterval(myVar);
}, 4000);
}
This code doesn't make the browser to crash, because I am stopping the execution before infiniteLoop() gets called by clearInterval(myVar).
My question is how do I stop executing such functions if they don't response within some period of time (eg. after 5 seconds or before the browser is crashed).
For example, if we copy paste following java code in https://www.compilejava.net/
public class HelloWorld {
public static void main(String[] args) {
while(true) {
System.out.println("Blah");
}
}
}
we get a nice output saying,
Script was taking longer than 5 seconds to execute so it was killed.
Here is my current code: http://js.do/code/106546
This is a bit tricky but perfectly doable. You need to tokenize the script and then rebuild it but insert a counter increment in every loop and function call. If the counter goes above some threshold, then bomb out. I did it here: https://littleminigames.com/
You can see the source at https://bitbucket.org/cskilbeck/littleminigames/src
The interesting bits are in wrapper.js (https://bitbucket.org/cskilbeck/littleminigames/src/ac29d0d0787abe93c75b88520050a6792c04d34d/public_html/static/js/wrapper.js?at=master&fileviewer=file-view-default)
Google escodegen, estraverse and esprima
I relied heavily on this: https://github.com/CodeCosmos/codecosmos/blob/master/www/js/sandbox.js
wrapper.js, as requested:
// Don't obfuscate this file! We depend on the toString() of functions!
// this was all nicked from https://github.com/CodeCosmos/codecosmos/blob/master/www/js/sandbox.js
(function(mainApp) {
'use strict';
var esprima = window.esprima,
estraverse = window.estraverse,
escodegen = window.escodegen,
errors = [],
eng,
Syntax = estraverse.Syntax;
// This implements the jankiest possible "source map", where we keep an array
// of [generatedLine, knownSourceLine]. Seems to essentially work.
function SourceNode(line, col, _sourceMap, generated) {
this.line = line;
this.col = col;
this.generated = generated;
}
SourceNode.prototype.toStringWithSourceMap = function toStringWithSourceMap() {
var code = [];
var mapLines = {};
var map = [];
// assumes that wrapCode adds two lines
var line = 3;
var lastMapLine = null;
function walk(node) {
if (typeof(node) === "string") {
if (node) {
code.push(node);
var matches = node.match(/\n/g);
if (matches !== null) {
line += matches.length;
}
}
} else if (node instanceof SourceNode) {
if (node.line !== null) {
if (!mapLines[line]) {
map.push([line, node.line]);
mapLines[line] = node.line;
}
}
walk(node.generated);
} else {
node.forEach(walk);
}
}
walk(this);
return {
code: code.join(''),
map: map
};
};
SourceNode.prototype.toString = function toString() {
return this.toStringWithSourceMap().code;
};
// This is used by escodegen
window.sourceMap = {
SourceNode: SourceNode
};
// TODO (chs): add in all the things that need to be masked
function runWrapper($userCode, __sys) {
var clear = __sys.clear,
setpixel = __sys.setpixel,
rectangle = __sys.rectangle,
box = __sys.box,
line = __sys.line,
getpixel = __sys.getpixel,
getpixeli = __sys.getpixeli,
keypress = __sys.keypress,
keyrelease = __sys.keyrelease,
keyheld = __sys.keyheld,
reset = __sys.reset;
__sys.userFunction = __sys.catchErrors($userCode);
}
function extractCode(fn) {
var code = fn.toString();
return code.substring(code.indexOf('{') + 1, code.lastIndexOf('}'));
}
function makeOneLine(code) {
return code.replace(/(\/\/[^\n]+|\n\s|\r\n\s*)/g, '');
}
var runTemplate = makeOneLine(extractCode(runWrapper));
function wrapCode(code, template, functionName, postCode) {
// avoid interpretation of the replacement string by using a fun.
// otherwise mo' $ mo problems.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
return ("'use strict';" + template.replace(/\$userCode/, function() {
return 'function ' + functionName + '() {\n' + code + postCode + '\n}';
}));
}
var injectStatement = esprima.parse("if (++__sys.ctr >= __sys.maxctr) throw new Error('Script halted - infinite loop?');").body[0];
var injectElseStatement = esprima.parse("if (++__sys.ctr >= __sys.maxctr) throw new Error('Script halted - infinite loop?'); else ;").body[0];
function CallExpression(callee, args) {
this.callee = callee;
this.arguments = args;
}
CallExpression.prototype.type = Syntax.CallExpression;
function Identifier(name) {
this.name = name;
}
Identifier.prototype.type = Syntax.Identifier;
function BlockStatement(body) {
this.body = body;
}
BlockStatement.prototype.type = Syntax.BlockStatement;
function ReturnStatement(argument) {
this.argument = argument;
}
ReturnStatement.prototype.type = Syntax.ReturnStatement;
function FunctionExpression(id, params, body) {
this.id = id;
this.params = params;
this.body = body;
this.defaults = [];
this.expression = false;
this.generator = false;
this.rest = null;
}
FunctionExpression.prototype.type = Syntax.FunctionExpression;
function wrapId(node, defaultName) {
if (node.loc) {
var id = (node.id || {
name: null,
loc: null
});
var loc = id.loc || node.loc;
var name = id.name || defaultName;
return new Identifier(name + '$' + loc.start.line);
} else {
return node.id;
}
}
function instrumentAST(ast) {
var identifierStack = [];
function pushIdentifier(s) {
identifierStack[identifierStack.length - 1].push(s);
}
function popIdentifierStack() {
identifierStack.pop();
}
function pushIdentifierStack() {
identifierStack.push([]);
}
function peekLastIdentifier() {
var lastStackIdx = identifierStack.length - 1;
if (lastStackIdx >= 0) {
var stack = identifierStack[lastStackIdx];
if (stack.length) {
return stack[stack.length - 1];
}
}
return '';
}
pushIdentifierStack();
return estraverse.replace(ast, {
enter: function enterAST(node) {
switch (node.type) {
case Syntax.VariableDeclarator:
if (node.id.type === Syntax.Identifier) {
pushIdentifier(node.id.name);
}
break;
case Syntax.MemberExpression:
if (node.object.type === Syntax.Identifier) {
var id = node.object.name;
if (node.property.type === Syntax.Identifier) {
id += '__dot__' + node.property.name; // huh? why mangle these?
// console.log(id);
}
pushIdentifier(id);
} else if (node.property.type === Syntax.Identifier) {
pushIdentifier(node.property.name);
}
break;
case Syntax.FunctionDeclaration:
pushIdentifierStack();
break;
case Syntax.FunctionExpression:
pushIdentifierStack();
break;
default:
break;
}
return node;
},
leave: function leaveAST(node) {
switch (node.type) {
case Syntax.DoWhileStatement:
break;
case Syntax.ForStatement:
break;
case Syntax.FunctionDeclaration:
break;
case Syntax.FunctionExpression:
break;
case Syntax.WhileStatement:
break;
default:
return estraverse.SKIP;
}
// modify the BlockStatement in-place to inject the instruction counter
if(node.body.body === undefined) {
// they have used a non-block statement as the body of a function or loop construct
// not allowed for function declarations - should never get here
if(node.type === Syntax.FunctionDeclaration) {
errors.push({
message: "Missing {",
line: node.loc.start.line,
column: node.loc.start.column
});
}
else {
// otherwise insert the test
var newBody = angular.copy(injectElseStatement);
newBody.alternate = node.body;
node.body = newBody;
}
return estraverse.SKIP;
}
node.body.body.unshift(injectStatement);
if (node.type === Syntax.FunctionExpression) {
popIdentifierStack();
// __catchErrors(node)
node.id = wrapId(node, peekLastIdentifier());
return new CallExpression(
new Identifier("__sys.catchErrors"), [node]);
}
if (node.type === Syntax.FunctionDeclaration) {
popIdentifierStack();
// modify the BlockStatement in-place to be
// return __catchErrors(function id() { body });
var funBody = node.body;
node.body = new BlockStatement([
new ReturnStatement(
new CallExpression(
new CallExpression(
new Identifier("__sys.catchErrors"), [new FunctionExpression(
wrapId(node, peekLastIdentifier()), [],
funBody)]), []))
]);
}
return node;
}
});
}
// mainApp.sandbox('var a = 1; function update(frame) { clear(0); }').code
// give it the source code as a string
mainApp.sandbox = function(code) {
var rc = {};
this.errors = [];
try {
this.ast = instrumentAST(esprima.parse(code, { range: true, loc: true }));
this.map = escodegen.generate(this.ast, { sourceMap: true, sourceMapWithCode: true });
this.code = wrapCode(this.map.code, runTemplate, '', ';\n__sys.updateFunction = (typeof update === "function") ? update : null;');
}
catch(e) {
this.errors.push({
message: e.description,
line: e.lineNumber,
column: e.column
});
}
if(this.code) {
this.code = "eng.clientFunction = function(__sys) {" + this.code + "};";
}
};
mainApp.sandbox.prototype.searchMap = function(needle) {
// binary search
var lo = 0;
var hi = this.map.map.length;
var mid, here;
while (true) {
mid = lo + ((hi - lo) >> 1);
here = this.map.map[mid];
if (mid === lo || here[0] === needle) {
return here[1];
} else if (here[0] > needle) {
hi = mid;
} else {
lo = mid;
}
}
};
})(mainApp);
Typically all JavaScript runs in one thread, so it is impossible to run any JavaScript that could stop your loop while your loop is running. Using HTML5 web workers, you can run the infinite loop in a separate thread, and then you can terminate it:
var myWorker = new Worker( '/infinite.js ');
setTimeout( function ( ) {
myWorker.terminate( );
}, 5000 );
However your web worker won't have access to the DOM, so the contents of your infinite loop would need to be different that what you have in your question.
I found exactly what I was looking for in Bergi's comment,
Alternatively, place a if (Date.now() > dateAtStartOfExecution+5000) return; in every loop body.
So now my code looks like:
function infiniteLoop() {
dateAtStartOfExecution = Date.now();
while(true) {
//do something
document.getElementById("someID").innerHTML = "Blah";
if (Date.now() > dateAtStartOfExecution+5000) {
alert("Taking too much time. Killing.");
return;
}
}
}
If I run this code after 5 seconds I will get an alert and the execution will stop. Try this:
http://js.do/code/106565

Communication between Stores in Reactjs

I develop an application which based on Reactjs and Flux. There is a problem of communication between Stores: ProjectsStore and TasksStore.
In the method getAllForCurrentProject of TasksStore, I call ProjectsStore.getCurrentId(). I get an Uncaught TypeError: undefined is not a function as a result. The typeof ProjectsStore is object in getAllForCurrentProject. When I call ProjectsStore.getCurrentId() from any component it works fine.
What is the reason for this behavior?
In the example MessageStore asks ThreadStore with the same pattern:
getAllForCurrentThread: function() {
return this.getAllForThread(ThreadStore.getCurrentID());
}
My stores:
ProjectsStore.js:
'use strict';
var Dispatcher = require('../dispatcher/Dispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var _ = require('underscore');
var Api = require('../services/Api');
var ProjectsConstants = require('../constants/ProjectsConstants');
var TasksStore = require('../stores/TasksStore');
var changeEvent = 'projectsChanged';
var current = 0;
var items = [];
function requestItems() {
return Api.Projects.getAll();
}
function setItems(data) {
items = data;
}
var ProjectsStore = assign({}, EventEmitter.prototype, {
emitChange: function () {
this.emit(changeEvent);
},
getAll: function () {
return items;
},
getCurrentId: function() {
return current;
},
getCurrent: function() {
var item = _.where(items, { id: this.getCurrentId() });
return (typeof item[0] == 'object' ? item[0] : null);
},
getChildrenOf: function(id, isInclude) {
var result = (typeof isInclude == 'boolean' && isInclude === true ? [id] : []),
children = _.chain(items).where({ parent: id }).pluck('id').value();
result.concat(children);
return result;
}
});
ProjectsStore.dispatchToken = Dispatcher.register(function (payload) {
var action = payload.action;
switch (action.type) {
case ProjectsConstants.projectsSetCurrent:
current = action.data;
break;
case ProjectsConstants.projectsGetAll:
requestItems();
break;
case ProjectsConstants.projectsGetAllSuccess:
setItems(action.data);
break;
default:
return true;
}
ProjectsStore.emitChange();
return true;
});
module.exports = ProjectsStore;
TasksStore.js:
'use strict';
var Dispatcher = require('../dispatcher/Dispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var _ = require('underscore');
var Api = require('../services/Api');
var TasksConstants = require('../constants/TasksConstants');
var ProjectsStore = require('../stores/ProjectsStore');
var changeEvent = 'tasksChanged';
var items = [];
function requestItems() {
return Api.Tasks.getAll();
}
function setItems(data) {
items = data;
}
var TasksStore = assign({}, EventEmitter.prototype, {
emitChange: function () {
this.emit(changeEvent);
},
getAll: function () {
return items;
},
getAllForProject: function(id) {
var projects = ProjectsStore.getChildrenOf(id, true);
return _.chain(items).where({ parent: projects });
},
getAllForCurrentProject: function() {
console.log('Type:', typeof ProjectsStore); // <-- object
console.log('Inspect:', ProjectsStore); // <-- {}
// Why ProjectsStore here is {} and
// Uncaught TypeError: undefined is not a function?
var id = ProjectsStore.getCurrentId();
// When I calling ProjectsStore.getCurrentId(); from any component it works fine.
return this.getAllForProject(id);
}
});
TasksStore.dispatchToken = Dispatcher.register(function (payload) {
var action = payload.action;
switch (action.type) {
case TasksConstants.tasksGetAll:
requestItems();
break;
case TasksConstants.tasksGetAllSuccess:
setItems(action.data);
break;
default:
return true;
}
TasksStore.emitChange();
return true;
});
module.exports = TasksStore;
It's look like you have Circular dependencies - TasksStore and ProjectsStore requiring each other.
ProjectsStore don't need to know TasksStore, remove the line:
var TasksStore = require('../stores/TasksStore');
or, if you use it, design your store to allow dependency injection, so your to classes won't dependent on each other

Alter value in object

Writing Javascript, I have an object/class with the following attributes:
this.option1Active = null;
this.option2Active = null;
this.option3Active = null;
this.option4Active = null;
I would like to set one of those attributes to true based on the parameter genre
function selectGenre (genre) {
if (genre === 'option1') {
this.option1Active = true;
}
else if (genre === 'option2') {
this.option2Active = true;
}
else if (genre === 'option3') {
this.option3Active = true;
}
else if (genre === 'option4') {
this.option4Active = true;
}
}
Though writing if statements is not a sustainable solution.
I'd like to do something like this:
function selectGenre (genre) {
var options = {
'option1': this.option1Active,
'option2': this.option2Active,
'option3': this.option3Active,
'option4': this.option4Active
};
options[genre] = true;
}
But that only set options[index] to true, not e.g. this.option1Active.
Is there a way to change the reference a key of an object points to?
If not, other ways of refactoring the if statements is greatly appreciated.
You can use a string for the property name to set on this.
var genreOptions = {
'option1': 'option1Active',
'option2': 'option2Active',
'option3': 'option3Active',
'option4': 'option4Active'
};
function selectGenre (genre) {
this[genreOptions[genre]] = true;
}
It seems you can just append "Active" to genre to get the property itself:
function selectGenre (genre)
{
var prop = genre + 'Active';
if (typeof this[prop] != 'undefined') {
this[prop] = true;
}
}
Though, it would be easier if you could use an array as your property instead, i.e. this.optionActive[3] vs. this.option3Active.
Is this what you want ?
var obj = {};
obj.option1Active = null;
obj.option2Active = null;
obj.option3Active = null;
obj.option4Active = null;
var options = {
option1: 'option1Active',
option2: 'option2Active',
option3: 'option3Active',
option4: 'option4Active'
};
function selectGenre(genre) {
obj[options[genre]] = true;
}
console.log(obj);
selectGenre('option2');
console.log(obj);

Javascript Composite pattern, can not use overwritten methods correctly

I have a javascript compositer pattern which i implemented (see code below).
In my main class i instantiate either the MenuItem or the Menu. I have to call the method update() on the component and they should return the corresponding code.
However it doesnt return the correct amount of totalitems. it alwasy returns the default value 0 which is defined in MenuComponent.
I think it has something to do with the this keyword but i can not find the exact solution.
MenuItem:
//MENU ITEM
//----------
var MenuItem = function(id) {
MenuComponent.apply(this, [id, name]);
};
MenuItem.prototype = Object.create(MenuComponent.prototype);
MenuItem.prototype.constructor = MenuItem;
MenuItem.prototype.update = function() {
//works
console.log(this.ingredients)
//Doesnt work, this should display same as this.ingredients
console.log(this.calculateIngredients())
console.log("--------------")
};
Menu:
//MENU
//--------
var Menu = function(id, name) {
MenuComponent.apply(this, [id, name]);
this.menuitems = [];
};
Menu.prototype = Object.create(MenuComponent.prototype);
Menu.prototype.constructor = Menu;
Menu.prototype.add = function(menuitem) {
this.menuitems.push(menuitem);
};
Menu.prototype.remove = function(menuitem) {
for(var s, i = 0; s = this.getMenuItem(i); i++) {
if(s == menuitem) {
this.menuitems.splice(i, 1);
return true;
}
if(s.remove(menuitem)) {
return true;
}
}
return false;
};
Menu.prototype.getMenuItem = function(i) {
return this.menuitems[i];
};
Menu.prototype.calculateIngredients = function() {
this.ingredients = 0;
for(var key in this.menuitems) {
this.ingredients += this.menuitems[key].calculateIngredients();
}
return this.ingredients;
};
MenuComponent
//MenuComponent
//-------------
var MenuComponent = function(id, name) {
if(this.constructor === MenuComponent) {
throw new Error("Can't instantiate abstract class");
}
this.id = id;
this.name = name;
this.ingredients = 0;
};
MenuComponent.prototype.calculateIngredients = function() {
return this.ingredients;
};
MenuComponent.prototype.update = function() {
console.log(this.ingredients)
console.log("-----------------")
};
example
// HANDLER
var menuitem1 = new MenuItem(1)
, menuitem2 = new MenuItem(2)
, menuitem3 = new MenuItem(3)
, menuitem4 = new MenuItem(4)
, menuitem5 = new MenuItem(5)
, menuitem6 = new MenuItem(6)
, menuitem7 = new MenuItem(7)
, menu = new Menu(1);
menu.add(menuitem1);
menu.add(menuitem2);
menu.add(menuitem3);
menu.add(menuitem4);
menuitem1.ingredients = 1
menuitem2.ingredients = 5
menuitem3.ingredients = 7;
menuitem4.ingredients = 2
// lets say i want to update the ingredient count of the following
menuitem1.update();
menuitem2.update();
menu.update();
//the update goes wrong, it doesnt display the correct amount, it alwasy displays 0 on the amounts where i commented
JSFiddle
Instead of
MenuComponent.prototype.update = function() {
console.log(this.ingredients) // 0
};
You want to call
MenuComponent.prototype.update = function() {
console.log(this.calculateIngredients()) // 15
};
whole code on jsfiddle: http://jsfiddle.net/krzysztof_safjanowski/gjTb4/

Categories

Resources