ExtJS 4 - Cannot read property 'substring' of undefined - javascript

I am new to Ext JS 4 and I am currently developing a pretty complex Ext JS MVC application that follows the architecture explained in this (basic) tutorial.
http://docs.sencha.com/extjs/4.0.7/#%21/guide/application_architecture.
Almost all the times I add a new view with the related model, controller and store, as first step I have to fix some mispelled alias or id. It comes to be very tricky since ext does not help me as I would expect, and there is a lot of these ids to look for.
Using Firebug, the error message given to me is:
Uncaught TypeError: Cannot read property 'substring' of undefined localhost:8080/Web/extjs4/ext-debug.js:5246
Is there a way to quickly undestand where the mispelling is?
This is the code portion where the exception is thrown
parseNamespace: function(namespace) {
var cache = this.namespaceParseCache,
parts,
rewrites,
root,
name,
rewrite, from, to, i, ln;
if (this.enableNamespaceParseCache) {
if (cache.hasOwnProperty(namespace)) {
return cache[namespace];
}
}
parts = [];
rewrites = this.namespaceRewrites;
root = global;
name = namespace;
for (i = 0, ln = rewrites.length; i < ln; i++) {
rewrite = rewrites[i];
from = rewrite.from;
to = rewrite.to;
// 5246
if (name === from || name.substring(0, from.length) === from) {
name = name.substring(from.length);
if (typeof to != 'string') {
root = to;
} else {
parts = parts.concat(to.split('.'));
}
break;
}
}
parts.push(root);
parts = parts.concat(name.split('.'));
if (this.enableNamespaceParseCache) {
cache[namespace] = parts;
}
return parts;
},
Thanks in advance.

I sanity check my code with console.log( Ext.getClassName(someObj) ); -- sometimes JSLint can help you find unused variables -- Good Luck!

Related

Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft. (Boardgame.io)

i know there is a quite similar question here in stackoverflow but i cant figure out what is the error in my code. To sum up, im pretty new to React and Javascript (i also know nothing about redux) and I am doing a project in Boardgame.io. This platform has its own template to define the state and the rules of the game (turn/phases etc).
The template is something like this:
export const Catan = {
setup: (ctx) => createInitialState(),
turn: {
moveLimit: 5, //realmente no tiene limite
},
moves: {
diceRoll: (G) => {
let roll = diceRoll();
G.diceValue = roll;
},
buildRoad, },
Im doing a function that defines one of the posibles moves that one player can do (buildRoad):
function buildRoad (G, ctx, id){
let playerID = 'player_' + ctx.currentPlayer;
let cPlayer = G[playerID];
if(cPlayer.resources.lumber < 1 || cPlayer.resources.brick <1){
alert("Not enough rss");
return INVALID_MOVE;
}
if(G.roadCells[id].value !== -1){
alert("Already owned road");
return INVALID_MOVE;
}
if(checkRoadBuild(G, cPlayer, id) === false){
alert("Cant build without conection");
return INVALID_MOVE;
}
// 1 lumber adn 1 brick
G.roadCells[id] = ctx.currentPlayer;
cPlayer.resources.brick--;
cPlayer.resources.lumber--;
return 1;
}
This function uses the object that defines the state G and other object with similar information ctx. What I do here with cPlayer is to call one of the objects players that i define inside G:
player_0: {
name : 'player_0',
color : 'red',
points : 0,
longestRoad : false,
largestArmy : false,
devCards : [],
resources : {
brick: 3,
lumber: 2,
ore: 0,
grain: 0,
wool: 0
},
ownedTiles : new Array(19 + 1).join('0').split('').map(parseFloat),
settlements : [],
cities : [],
},
In the last if, i call another check function and there is (i guess) where the error comes from, or at least i think that:
function checkRoadBuild(G, cPlayer, id){
//search in settlements and cities
for(let i=0; i<cPlayer.settlements.length; i++){
if(cPlayer.settlements[i] === G.roadCells[id].to || cPlayer.settlements[i] === G.roadCells[id].from)
return true;
}
for(let i=0; i<cPlayer.cities.length; i++){
if(cPlayer.cities[i] === G.roadCells[id].to || cPlayer.cities[i] === G.roadCells[id].from)
return true;
}
//look for connected roads - TODO
return true;
}
This function its not finished yet, thats why it always return true, but the problem comes when i try to make the move buildRoad. The console shows this error:
index.js:1 ERROR: Error: [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.
at t (errors.ts:49)
at P (finalize.ts:27)
at e.i.produce (immerClass.ts:111)
at turn-order-ec34409c.js:169
at turn-order-ec34409c.js:547
at Object.processMove (reducer-fcd5a508.js:738)
at reducer-fcd5a508.js:903
at dispatch (redux.js:213)
at client-1ffa26ed.js:256
at client-1ffa26ed.js:300
at Object.dispatch (client-1ffa26ed.js:310)
at InteractiveFunction.dispatchers.<computed> (client-1ffa26ed.js:200)
at InteractiveFunction.Submit (Debug-753f485a.js:3852)
at Debug-753f485a.js:289
at Array.forEach (<anonymous>)
at Debug-753f485a.js:288
at Submit (Debug-753f485a.js:3646)
at HTMLSpanElement.OnKeyDown (Debug-753f485a.js:3657)
I ve been looking what could be my error in the code but i dont see anything strange. I have been reading about this error but i dont know much about immer and reducer (i think the error comes from that). I would thanks any help. I can send more info if need it.
I have already figured out it, it was a return that wasnt supposed to be there.

javascript functions wait for data availability or variable not capable of handling huge data

forgive the trivial question but I am more used to C++ and Python code than javascript.
I have the following code from the THREE JS PLY loader:
var geometry;
var scope = this;
if (data instanceof ArrayBuffer) {
geometry = isASCII(data) ? parseASCII(bin2str(data)) : parseBinary(data);
} else {
geometry = parseASCII(data);
}
parse: function (data) {
function isASCII(data) {
var header = parseHeader(bin2str(data));
return header.format === 'ascii';
}
function bin2str(buf) {
var array_buffer = new Uint8Array(buf);
var str = '';
for (var i = 0; i < buf.byteLength; i++) {
str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
}
return str;
}
It works fine if I load a small ply file but browser crashes on very large one. I believe there are two "possible" issues:
1) on a large file the string str returned by the function bin2str(buf) might not be able to handle the parsing process
2) in the function isASCII(data) the line
parseHeader(bin2str(data));
crashes the browser as the bin2str(data) cannot return a proper value in time as the process is very memory consuming
I am using the conditional as i am not totally sure of what the problem is. Any suggestion and/or possible solution?
Thank you,
Dino
In the end the solution I have adopted was to decimate my file using the free software MeshLab.
Hope this helps.
Dino

What are the possible ways to fix problems when the server change from http to https?

I am having an issue with a calculation operation I am working on since the server changes from http to https.
I haven't change anything in the file of the functionality giving the issues, and actually I don't know what is going on because the console is not returning any errors.
In the Production Environment everything works properly because the protocol is http, but in the Staging ENV, that part of the app goes down and is not returning anything due to the change to a secured server.
if(window.location.href.indexOf("standalone") != -1) {
var pid = 'HL:Tool:HLmisc:Calc;MortgageCalculator';
var standalone = 'standalone=y&';
}else{
var pid = 'MHE:Tool:HLPE;Tool_AffordabilitySnapshot';
var standalone = 'standalone=&';
} if(window.location.href.indexOf("standalone") != -1) {
var pid = 'HL:Tool:HLmisc:Calc;MortgageCalculator';
var standalone = 'standalone=y&';
}else{
var pid = 'MHE:Tool:HLPE;Tool_AffordabilitySnapshot';
var standalone = 'standalone=&';
}
$(".submitBtn").click(function(e){
//alert(this.id);
var valRes = AFFSNAP.form.validate();
if(this.id === 'incomeSubmit' && valRes) {
//alert('build income array');
var income = new Array();
income['pid'] = pid+'Tool_AffordabilitySnapshot';
income['nm'] = this.name;
income['hr'] = location.protocol+'//'+location.hostname+location.pathname+'?'+standalone+'step=expenses&agi='+$('#agi').val()+'&mni='+$('#mni').val();
AFFSNAP.throwManualCMClickEvt(income);
}
if(this.id === 'expensesSubmit' && valRes) {
var expenses = new Array();
expenses['pid'] = pid+'Tool_AFS_Expenses';
expenses['nm'] = this.name;
expenses['hr'] = '//'+location.hostname+location.pathname+'?'+standalone+'step=debt&utilities='+$('#utilities').val()+'&communications='+$('#communications').val()+'&entertainment='+$('#entertainment').val()+'&dependents='+$('#dependents').val()+'&travel='+$('#travel').val()+'&savings='+$('#savings').val();
AFFSNAP.throwManualCMClickEvt(expenses);
}
if(this.id === 'calculateSubmit' && valRes){
var calculate = new Array();
calculate['pid'] = pid+'Tool_AFS_Debt';
calculate['nm'] = this.name;
calculate['hr'] = '//'+location.hostname+location.pathname+'?step=results&creditCards='+$('#creditCards').val()+'&loans='+$('#loans').val();
AFFSNAP.throwManualCMClickEvt(calculate);
AFFSNAP.throwCMOnLoadEvt2();
}
return valRes;
});
that is the function where it takes some of the input values and do the calculation I need.
Any suggestions?
EDIT
If you downvote, at least provide a reason so I can improve my answer. You are abusing of that functionality.
If you're referencing links within the same site, It's best to just reference paths relative to the root and omit the protocol & hostname. Your links would look like this:
test
The other way to handle it is to just remove the protocol altogether. This will allow it to be inherited from the current protocol. So your links would look like:
test
Whether your protocol is http or https, it will be automatically pre-pended to the href.

TypeError: Error #1009: Cannot access a property or method of a null object reference. at Slide1_fla::MainTimeline/frame1() AS3

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Slide1_fla::MainTimeline/frame1()
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Slide2_fla::MainTimeline/frame1()
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Side3_fla::MainTimeline/frame1()
I have tried all of the sources and still couldn't find any answer to fix this problem.
I am running Adobe Flash CS6 AS3
Whenever I run the script, I get this output and the file doesn't run properly. In the published file, the swf file isn't show completely, meaning the external .swf files are not fitted in the contentContainer.
My code is this:
var _swfLoader:Loader;
var _swfRequest:URLRequest;
var _swfPathArr:Array = new Array("Slide1.swf", "Slide2.swf", "Slide3.swf");
var _swfClipsArr:Array = new Array();
var _swfTempClip:MovieClip;
var _loadedSWFs:int;
var contact_btn:SimpleButton;
var news_btn:SimpleButton;
var portfolio_btn:SimpleButton;
startLoading(_swfPathArr);
function startLoading(pathArr:Array):void {
_swfLoader = new Loader();
_swfRequest = new URLRequest();
loadSWF(pathArr[0]);
}
function loadSWF(path:String):void {
setupListeners(_swfLoader.contentLoaderInfo);
_swfRequest.url = path;
_swfLoader.load(_swfRequest);
}
function setupListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, onSwfComplete);
dispatcher.addEventListener(ProgressEvent.PROGRESS, currentSwfProgress);
}
function currentSwfProgress(event:ProgressEvent):void {
var _perc:int = (event.bytesLoaded / event.bytesTotal) * 5;
// swfPreloader.percentTF.text = _perc + "10%";
}
function onSwfComplete(event:Event):void {
event.target.removeEventListener(Event.COMPLETE, onSwfComplete);
event.target.removeEventListener(ProgressEvent.PROGRESS, currentSwfProgress);
_swfTempClip = event.target.content;
_swfTempClip.customID = _loadedSWFs;
_swfClipsArr.push(_swfTempClip);
if(_loadedSWFs <_swfPathArr.length - 1) {
_loadedSWFs++;
loadSWF(_swfPathArr[_loadedSWFs]);
} else {
_swfLoader.unloadAndStop();
_swfLoader = null;
onCompletePreloading();
}
}
function onCompletePreloading():void {
contentContainer.addChild(_swfClipsArr[0]);
news_btn.enabled = true;
contact_btn.enabled = true;
portfolio_btn.enabled = true;
news_btn.addEventListener(MouseEvent.CLICK, setContent);
portfolio_btn.addEventListener(MouseEvent.CLICK, setContent);
contact_btn.addEventListener(MouseEvent.CLICK, setContent);
}
function setContent(event:MouseEvent):void {
var _swfToAdd:MovieClip;
switch(event.target.name) {
case "news_btn":
_swfToAdd = _swfClipsArr[0];
break;
case "portfolio_btn":
_swfToAdd = _swfClipsArr[1];
break;
case "contact_btn":
_swfToAdd = _swfClipsArr[2];
break;
}
contentContainer.removeChildAt(contentContainer.numChildren-1);
contentContainer.addChild(_swfToAdd);
trace(_swfToAdd.customID);
}
I used to face this problem when the loaded SWF contain "TLF Text".
So the fix? Make "ALL" your textfield in the loaded SWF "Classic Text" and hopefully your problem would be solved.
PS. An easy way to clean all TLF text from a FLA file is to change document script from ActionScript 3.0 to 2.0. Since TLF Text is only support in 3.0, they will immediately change back to Classic Text, and then change your script back to 3.0 again. :)

How to access callback on grunt task set up in initConfig

I've got an issue that I can't seem to resolve. I have tried a couple different ways, but nothing is working yet.
I am using grunt-messageformat to create my i18n localized copy. I have 2 folders with languages in them and I'd like to have grunt automatically generate the correct output for each folder (language).
The task that got me closest is this:
grunt.registerTask("ReadFolders", "Read the language folders in app/data/i18n/", function () {
// Returns an array of the paths to the language folders.
// ['app/data/i18n/en', 'app/data/i18n/key', ...]
var languageFolders = grunt.file.expand("app/data/i18n/*");
var path;
var languageName;
var i;
for (i = 0; i < languageFolders.length; i++) {
path = languageFolders[i];
languageName = path.substring(path.lastIndexOf("/") + 1, path.length);
grunt.config.set("mFormat.locale", languageName);
grunt.config.set("mFormat.inputdir", "app/data/i18n/" + languageName);
grunt.config.set("mFormat.output", "app-dist/test/js/locales/" + languageName + "/i18n.js");
grunt.task.run("messageformat:all");
}
});
This also uses the following code for my messageformat task, which is set up in initConfig:
messageformat: {
all: {
locale: "<%= mFormat.locale %>",
inputdir: "<%= mFormat.inputdir%>",
output: "<%= mFormat.output%>"
}
}
The problem is that my loop in 'readFolders' runs through twice before the messageFormat task runs, which means the task runs twice, but both times it uses the last values for the mFormat variables.
I don't see any examples of how to access a callback of a task that is set up using initConfig.
Any thoughts? Or other ideas?
Thanks
Well I didn't find a way to do what I had originally asked... But I found a good workaround that fulfills my needs. Instead of running the task for each folder, I instead rewrite the messageformat config dynamically for each language.
grunt.registerTask("ReadFolders", "Read the language folders in app/data/i18n/", function () {
// Returns an array of the paths to the language folders.
// ['app/data/i18n/en', 'app/data/i18n/key', ...]
var languageFolders = grunt.file.expand("app/data/i18n/*");
var path;
var languageName;
var locale;
var messageFormat = {};
var i = 0;
for (i = 0; i < languageFolders.length; i++) {
path = languageFolders[i];
languageName = path.substring(path.lastIndexOf("/") + 1, path.length);
locale = languageName;
if (languageName === "key") {locale = "en"; }
messageFormat[languageName] = {
locale: locale,
inputdir: "app/data/i18n/" + languageName,
output: "app-dist/test/js/locales/" + languageName + "/i18n.js"
};
}
grunt.config.set("messageformat", messageFormat);
grunt.task.run("messageformat");
});
After quite an exhaustive search, I think this is the only possible (and quite frankly, in my case, the better) solution.
Still happy to hear about any other ideas if anyone's got any.

Categories