Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
A LOVELY LAD
Feb 8, 2006

Hey man, wanna hear a secret?



College Slice
Hey here comes a really feeble and probabaly hard to understand JS question but I can't figure out what I need to type to find similar problems.


I'm using an object to store data to be used to generate new objects dynamically. (backstory: I'm using pixiJS and cant stringify the pixijs objects)



dataModel.object = {name: "object", otherVariable=0}

newObject = {}
newObject.name = dataModel.object.name


How could I change otherVariable on dataModel.object by referencing newObject?

I tried adding a value to dataModel.object ( DM: dataModel.object ) so I could then go

newObject.DM = dataModel.object.DM

newobject.DM.othervariable += 1


but DM gets undefined, probably to prevent crashes. I know I could do it using eval but I'd rather not.

Cheers


EDIT: I think I got around this by just transferring all the data to newObject, deleting dataModel.object and then recreating dataModel.object as and when required (for stringify/saving)

A LOVELY LAD fucked around with this message at 22:23 on Sep 11, 2015

Adbot
ADBOT LOVES YOU

qntm
Jun 17, 2009

A LOVELY LAD posted:

Hey here comes a really feeble and probabaly hard to understand JS question but I can't figure out what I need to type to find similar problems.


I'm using an object to store data to be used to generate new objects dynamically. (backstory: I'm using pixiJS and cant stringify the pixijs objects)



dataModel.object = {name: "object", otherVariable=0}

newObject = {}
newObject.name = dataModel.object.name


How could I change otherVariable on dataModel.object by referencing newObject?

I tried adding a value to dataModel.object ( DM: dataModel.object ) so I could then go

newObject.DM = dataModel.object.DM

newobject.DM.othervariable += 1


but DM gets undefined, probably to prevent crashes. I know I could do it using eval but I'd rather not.

Cheers


EDIT: I think I got around this by just transferring all the data to newObject, deleting dataModel.object and then recreating dataModel.object as and when required (for stringify/saving)

If by this you mean you wrote something like

JavaScript code:
dataModel.object = {name: "object", otherVariable: 0, DM: dataModel.object};
then this is almost exactly the same as writing something like

JavaScript code:
var DM = dataModel.object; // undefined
dataModel.object = {name: "object", otherVariable: 0, DM: DM};
which is why dataModel.object.DM returns undefined. To get the result you wanted, you would have to do something like this:

JavaScript code:
dataModel.object = {name: "object", otherVariable: 0};
dataModel.object.DM = dataModel.object;

A LOVELY LAD
Feb 8, 2006

Hey man, wanna hear a secret?



College Slice

qntm posted:


which is why dataModel.object.DM returns undefined. To get the result you wanted, you would have to do something like this:

JavaScript code:
dataModel.object = {name: "object", otherVariable: 0};
dataModel.object.DM = dataModel.object;


I did try it that way originally but then I can't dynamically store/set up the DM bit when stringifying the object, I would have to make an array of these DM references or something similar I think.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
Got another stupid question. What are strings in javascript encoded as? Are they by default UTF-8?

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord
It depends on the engine but generally it's UTF-16.

three
Aug 9, 2007

i fantasize about ndamukong suh licking my doodoo hole
Is it best to use XMLHttpRequest or JSONP? Book I'm reading (Head First HTML5) kinda leans towards JSONP but is not explicit.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

three posted:

Is it best to use XMLHttpRequest or JSONP? Book I'm reading (Head First HTML5) kinda leans towards JSONP but is not explicit.

I don't see why anyone would prefer JSONP over XHR if the job can be done with XHR. JSONP requires trusting the server and executing arbitrary javascript code.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Knifegrab posted:

Got another stupid question. What are strings in javascript encoded as? Are they by default UTF-8?

JavaScript as standardized expects UCS2-with-surrogates in source files (it seemed like a good idea in 1997). Engines use a variety of encodings internally, with most engines having at least two depending on the contents of the string.

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.
I need some help with callbacks as I don't really understand them. I have this code which gets a string from a url, and then sends an alert with the text. I don't want the alert to show until the string is returned (long running database procedure), but I also don't want to block the UI.

code:
var area = document.getElementsByName('cmbxArea_Value')[0].value;
var date = document.getElementById('dtefDate').value;
var url = '/ReportCompiler.ashx?area=' + area + '&date=' + date;
var request = new XMLHttpRequest();
request.open('GET', url, true);
var resp = 'Error loading report';
request.onload = function() {
	if (request.status >= 200 && request.status < 400) {
		resp = request.responseText;
	}
};
request.send();
alert(resp);

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Put the alert(resp); in the callback itself.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Uziel posted:

I need some help with callbacks as I don't really understand them. I have this code which gets a string from a url, and then sends an alert with the text. I don't want the alert to show until the string is returned (long running database procedure), but I also don't want to block the UI.

code:
var area = document.getElementsByName('cmbxArea_Value')[0].value;
var date = document.getElementById('dtefDate').value;
var url = '/ReportCompiler.ashx?area=' + area + '&date=' + date;
var request = new XMLHttpRequest();
request.open('GET', url, true);
var resp = 'Error loading report';
request.onload = function() {
	if (request.status >= 200 && request.status < 400) {
		resp = request.responseText;
	}
};
request.send();
alert(resp);

This is the order in which your code runs:

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.
Thanks! That was easier than I thought:
code:
 request.onreadystatechange = ClientSideUpdate;
function ClientSideUpdate() {
                                                                    var result;
                                                                    if (request.readyState == 4) {
                                                                        result = request.responseText;
                                                                        Ext.Msg.notify('Report Generation', result);
                                                                    }
                                                                 }

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
So I've always just had one big main clientside javascript file per page. Now that I am doing something more complex I feel like my single page approach is getting far too unwieldy.

Obviously on the serverside with node and requires its easy to build complex systems with multiple files, but I really am scratching my head figuring out the best approach here for client side. Anyone have any ideas?

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

So I've always just had one big main clientside javascript file per page. Now that I am doing something more complex I feel like my single page approach is getting far too unwieldy.

Obviously on the serverside with node and requires its easy to build complex systems with multiple files, but I really am scratching my head figuring out the best approach here for client side. Anyone have any ideas?

Write everything in different files and use ES6 style imports, then use webpack to pack them together in one file to be linked from the HTML.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Do you want to edit in multiple source files, or serve different script to different pages based on what they need? Webpack works well for the former, don't bother with the latter.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Subjunctive posted:

Do you want to edit in multiple source files, or serve different script to different pages based on what they need? Webpack works well for the former, don't bother with the latter.

I just want to edit multiple source files, for management reasons I feel it would be a lot easier to have mutliple tabs open than to scroll up and down a gigantic file. I only have one true "webpage" so I don't have to worry about the latter.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Knifegrab posted:

I just want to edit multiple source files, for management reasons I feel it would be a lot easier to have mutliple tabs open than to scroll up and down a gigantic file. I only have one true "webpage" so I don't have to worry about the latter.

Well, if that is ALL you are looking for, VSCode & Atom editors allow side by side editing within the same file.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Skandranon posted:

Well, if that is ALL you are looking for, VSCode & Atom editors allow side by side editing within the same file.

I use atom, though I appreciate the suggestion as Atom does indeed rule. However I would still like to split my work across multiple files if possible.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

I use atom, though I appreciate the suggestion as Atom does indeed rule. However I would still like to split my work across multiple files if possible.

Webpack.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

piratepilates posted:

Write everything in different files and use ES6 style imports, then use webpack to pack them together in one file to be linked from the HTML.

I just looked up es6 style imports and its not yet supported by firefox so I think I had better hold off on using that for now.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Knifegrab posted:

I just looked up es6 style imports and its not yet supported by firefox so I think I had better hold off on using that for now.

One thing you can do with typescript is compile multiple ts files into one big js file, and just serve that as a single script.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

I just looked up es6 style imports and its not yet supported by firefox so I think I had better hold off on using that for now.

No no, use ES6 style imports and use Webpack to join it together in one file, include the file in the HTML. Develop in multiple files, serve in one.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

piratepilates posted:

No no, use ES6 style imports and use Webpack to join it together in one file, include the file in the HTML. Develop in multiple files, serve in one.

This is good advice and will serve people well. (Though you reach a point where having the script out-of-line can be better.)

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

piratepilates posted:

No no, use ES6 style imports and use Webpack to join it together in one file, include the file in the HTML. Develop in multiple files, serve in one.

I guess I'm confused, I looked up firefox's es6 support and it explicitly says it does not support module import/export yet. What am I missing (bear in mind I am dense).

Edit, wait, does webpack just turn all of the javascript into a single file? Reading its tutorial has left me more confused than not.

Knifegrab fucked around with this message at 04:45 on Sep 16, 2015

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

I guess I'm confused, I looked up firefox's es6 support and it explicitly says it does not support module import/export yet. What am I missing (bear in mind I am dense).

Webpack reads the ES6 imports and creates a new file that has all of the files that were imported in one, you serve up only the new (one single) file, while developing in the other files. All browsers see are the one file, all you see is one built file and many source files.

Your other option is to use some kind of weird runtime mess like AMD but this is 2015 please don't do that.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

piratepilates posted:

Webpack reads the ES6 imports and creates a new file that has all of the files that were imported in one, you serve up only the new (one single) file, while developing in the other files. All browsers see are the one file, all you see is one built file and many source files.

Your other option is to use some kind of weird runtime mess like AMD but this is 2015 please don't do that.

So if I do this in myLib.js

code:

function myFunc () {

...

}

module.export.myFunc = myFunc;

Then in other file I do

code:
var myLib = require('myLib.js');

myLib.myFunc();
This would work assuming I then compile this with webpack?

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

So if I do this in myLib.js

code:

function myFunc () {

...

}

module.export.myFunc = myFunc;

Then in other file I do

code:
var myLib = require('myLib.js');

myLib.myFunc();
This would work assuming I then compile this with webpack?

Yes.

Here is the whole compiled file for that if you're curious:

code:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}


/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	var myLib = __webpack_require__(1);

	myLib.myFunc();

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	/* WEBPACK VAR INJECTION */(function(module) {function myFunc () {

	console.log('...');

	}

	module.export.myFunc = myFunc;
	/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)(module)))

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = function(module) {
		if(!module.webpackPolyfill) {
			module.deprecate = function() {};
			module.paths = [];
			// module.parent = undefined by default
			module.children = [];
			module.webpackPolyfill = 1;
		}
		return module;
	}


/***/ }
/******/ ]);

piratepilates fucked around with this message at 04:53 on Sep 16, 2015

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

piratepilates posted:

Webpack reads the ES6 imports and creates a new file that has all of the files that were imported in one, you serve up only the new (one single) file, while developing in the other files. All browsers see are the one file, all you see is one built file and many source files.

Your other option is to use some kind of weird runtime mess like AMD but this is 2015 please don't do that.

You can use Browserify to do the same thing, but either way, you have to set up a bundler to interpret the require/import statements.

Also, TypeScript will allow you to use the ES6 import syntax, and will change them to var x = require("sdfdsf"); if targeting ES5.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

piratepilates posted:

Yes.

Here is the whole compiled file for that if you're curious:

code:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}


/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	var myLib = __webpack_require__(1);

	myLib.myFunc();

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	/* WEBPACK VAR INJECTION */(function(module) {function myFunc () {

	console.log('...');

	}

	module.export.myFunc = myFunc;
	/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)(module)))

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = function(module) {
		if(!module.webpackPolyfill) {
			module.deprecate = function() {};
			module.paths = [];
			// module.parent = undefined by default
			module.children = [];
			module.webpackPolyfill = 1;
		}
		return module;
	}


/***/ }
/******/ ]);

Can I do nested requires? I mean to say, can I have my main file require fileA, and then can I have fileA require fileB? Would that work or is it only capable of doing it one level deep?

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

Can I do nested requires? I mean to say, can I have my main file require fileA, and then can I have fileA require fileB? Would that work or is it only capable of doing it one level deep?

Yes, it also probably deals with cyclic requires and the like.

It's also very easy to test out, just install it through npm and do 'webpack <mainfile> <outputfile>'.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

piratepilates posted:

Yes, it also probably deals with cyclic requires and the like.

It's also very easy to test out, just install it through npm and do 'webpack <mainfile> <outputfile>'.

Yeah a minute after asking ths dumb question I had it working. Thanks a ton this is going to make my life much much better!

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

Yeah a minute after asking ths dumb question I had it working. Thanks a ton this is going to make my life much much better!

Now if you get bored you can also go hog wild and start using require's for everything -- CSS, HTML, images, anything you can get a loader for you can write a require for and have Webpack fill it out.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

piratepilates posted:

Now if you get bored you can also go hog wild and start using require's for everything -- CSS, HTML, images, anything you can get a loader for you can write a require for and have Webpack fill it out.

I'll look into it, I'm ridiculously ecstatic to have bite sized files right now, as its my preferred organization method (I'm anal about code organization and structuring and modularization).

edit: THANKS! <3

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Skandranon posted:

You can use Browserify to do the same thing

Get used to this when developing Javascript.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
i just use multiple .js files and <script> tags because i hate build processes lmao

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Suspicious Dish posted:

i just use multiple .js files and <script> tags because i hate build processes lmao

If you enable HTTP2 or SPDY on your server and your visitors are using modern browsers then this isn't even bad, it should (theoretically) work as well or better than concatenating files.

I still like Webpack for the non-JS requires and all the nice loaders still.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

piratepilates posted:

If you enable HTTP2 or SPDY on your server and your visitors are using modern browsers then this isn't even bad, it should (theoretically) work as well or better than concatenating files.

I still like Webpack for the non-JS requires and all the nice loaders still.

I like webpack for those things (ES6, import, etc.) but the best thing is hot reloading. :swoon:

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Lumpy posted:

I like webpack for those things (ES6, import, etc.) but the best thing is hot reloading. :swoon:

Can you expand on hot reloading, and pretend I am a complete moron (I am).

necrotic
Aug 2, 2005
I owe my brother big time for this!

Knifegrab posted:

Can you expand on hot reloading, and pretend I am a complete moron (I am).

Hot reloading will watch for changes to your JS files and automatically inject the new script into your browser page on the fly. No reload is necessary and you see changes immediately. It's pretty spectacular, but took me some effort to get it working the first couple of times.

Adbot
ADBOT LOVES YOU

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

necrotic posted:

Hot reloading will watch for changes to your JS files and automatically inject the new script into your browser page on the fly. No reload is necessary and you see changes immediately. It's pretty spectacular, but took me some effort to get it working the first couple of times.

Ahhh gotcha, well for now I don't mind hitting up and then enter everytime I wanna test my new code, and I'm afraid of messing even THAT up!

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply