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
Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.
lol @ 43k minified and compressed just to handle dates sensibly though

Adbot
ADBOT LOVES YOU

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

geeves posted:

Joda Time was a godsend pre-Java 8, so it's nice to see that JsJoda exists. Wish I had known about it sooner. Moment is decent, but its API is just weird. A more Java-like implementation is most welcome. And may be something to which I can actually contribute.

The best part is the immutability. Moment's mutable design is a great foot gun.

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

Vulture Culture posted:

lol @ 43k minified and compressed just to handle dates sensibly though

yeah dealing with datetime correctly sucks rear end.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Its so great that the JS standard library is so unfeatureful, isn't it?

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
Zero porcelain = maximal closeness to the metal! :awesomelon:

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I wanted to say I've had the pleasure of using `js-joda` for dates stuff in a recent project and it's so nice. Terrible name but so nice.

Dominoes
Sep 20, 2007

necrotic posted:

The best part is the immutability. Moment's mutable design is a great foot gun.
I don't view immutability as a requirement... Just don't make basic manipulation mutate by default! It took me a while to figure out why adding in moment was causing strange bugs. I see the lack of separate date/time/delta types as the biggest issue, along with an awkward API.

Fish Ladder Theory
Jun 7, 2005

May I recommend https://date-fns.org/

it fuckin good

edit: just saw this quote:

Dominoes posted:

Yep, twas me... And that library looks exactly like what I was trying to build... to the point where it means I should abandon the project, despite the basics being done. Date-fns was a false-messiah, but this may be the real deal.



what did i miss?

necrotic
Aug 2, 2005
I owe my brother big time for this!
My post right before his quotes his "announcement", and date-fns has been part of the conversation on dates since before that quoted post.

edit: sorry, two posts before has the quote.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm confused about managing peer dependencies in npm(/yarn) package environments.

I'm using ReactXP for a project - ReactXP is a wrapper on React and React-Native that aims to allow write-once components that transpile to run natively on the web, mobile, and (soon) windows. From ReactXP's package.json:

JavaScript code:
"version": "0.42.0-rc.12",
"peerDependencies": {
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-native": "^0.42.0",
    "react-native-windows": "^0.33.0"
}
ReactXP's 'Getting Started' documentation recommends pulling down a sample app and working from there. Fair enough. From Hello-World's package.json:

JavaScript code:
"dependencies": {
    "reactxp": "0.42.0-rc.9",
    "react": "^15.4.1",
    "react-dom": "^15.4.1",
    "react-native": "^0.42.0",
    "react-native-windows": "^0.33.0",
    "reactxp-imagesvg": "^0.2.1",
    "reactxp-video": "^0.1.3"
}
My own project started with this Hello-World at something like reactxp 0.42.0-rc.5. What's the expected workflow for me when I want to update my version of reactxp? Do I yarn update reactxp and then have a look at reactxp's package.json file in order to pull down the correct versions of its peer dependencies? Can I configure yarn or npm to pull down the correct peer dependencies and make the necessary updates to my own package.json file?

icantfindaname
Jul 1, 2008


Okay I started working on the Casper project again, and I'm stuck. I found this Chrome plugin to automatically generate scripts but it's not working

https://github.com/ebrehault/resurrectio

On this page

http://worknet.wisconsin.gov/worknet/daindustry.aspx

Option number 6 does not appear until option 5 is selected, and this seems to break the script generation. It has an option to generate the script with XY coordinates instead of HTML tags, which works, but doesn't seem to be able to scroll down the menus and so can't select anything more than the first few that are shown at first. I've tried to combine them to use XY clicks for boxes 5 and 6 and HTML tags for the others but that doesn't work either.

Here's what it generates for what I want it to do

code:
/*==============================================================================*/
/* Casper generated Mon Jun 26 2017 11:32:30 GMT-0500 (Central Daylight Time) */
/*==============================================================================*/

var x = require('casper').selectXPath;
casper.options.viewportSize = {width: 1920, height: 974};
casper.on('page.error', function(msg, trace) {
   this.echo('Error: ' + msg, 'ERROR');
   for(var i=0; i<trace.length; i++) {
       var step = trace[i];
       this.echo('   ' + step.file + ' (line ' + step.line + ')', 'ERROR');
   }
});
casper.test.begin('Resurrectio test', function(test) {
   casper.start('http://worknet.wisconsin.gov/worknet/daindustry.aspx');
   casper.waitForSelector("#lstNaicsLevel option:nth-child(2)",
       function success() {
           test.assertExists("#lstNaicsLevel option:nth-child(2)");
           this.click("#lstNaicsLevel option:nth-child(2)");
       },
       function fail() {
           test.assertExists("#lstNaicsLevel option:nth-child(2)");
   });
   casper.waitForSelector("#lstIndustry option:nth-child(3)",
       function success() {
           test.assertExists("#lstIndustry option:nth-child(3)");
           this.click("#lstIndustry option:nth-child(3)");
       },
       function fail() {
           test.assertExists("#lstIndustry option:nth-child(3)");
   }); 
   casper.waitForSelector("#lstYear option:nth-child(1)",
       function success() {
           test.assertExists("#lstYear option:nth-child(1)");
           this.click("#lstYear option:nth-child(1)");
       },
       function fail() {
           test.assertExists("#lstYear option:nth-child(1)");
   });
   casper.waitForSelector("#lstPeriod option:nth-child(1)",
       function success() {
           test.assertExists("#lstPeriod option:nth-child(1)");
           this.click("#lstPeriod option:nth-child(1)");
       },
       function fail() {
           test.assertExists("#lstPeriod option:nth-child(1)");
   });
   casper.waitForSelector("#lstOwnership option:nth-child(1)",
       function success() {
           test.assertExists("#lstOwnership option:nth-child(1)");
           this.click("#lstOwnership option:nth-child(1)");
       },
       function fail() {
           test.assertExists("#lstOwnership option:nth-child(1)");
   });
   casper.waitForSelector("#lstReportValues option:nth-child(7)",
       function success() {
           test.assertExists("#lstReportValues option:nth-child(7)");
           this.click("#lstReportValues option:nth-child(7)");
       },
       function fail() {
           test.assertExists("#lstReportValues option:nth-child(7)");
   });
   casper.waitForSelector("form[name=Form1] input[name='btnResults']",
       function success() {
           test.assertExists("form[name=Form1] input[name='btnResults']");
           this.click("form[name=Form1] input[name='btnResults']");
       },
       function fail() {
           test.assertExists("form[name=Form1] input[name='btnResults']");
   });
   /* submit form */
   casper.waitForSelector("body",
       function success() {
           test.assertExists("body");
           this.click("body");
       },
       function fail() {
           test.assertExists("body");
   });
   casper.wait(1000);
   casper.then(function() {
       this.captureSelector("screenshot1.png", "html");
   });

   casper.run(function() {test.done();});
});
It chokes on this line

code:
>casperjs test test.js
Test file: test.js
# Resurrectio test
PASS Find an element matching: #lstNaicsLevel option:nth-child(2)
FAIL Find an element matching: #lstIndustry option:nth-child(3)
#    type: assertExists
#    file: test.js
#    subject: false
#    selector: "#lstIndustry option:nth-child(3)"
PASS Resurrectio test
FAIL 2 tests executed in 6.175s, 1 passed, 1 failed, 0 dubious, 0 skipped.

Details for the 1 failed test:

In test.js
  Resurrectio test
    assertExists: Find an element matching: #lstIndustry option:nth-child(3)

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



I can't get that working well enough to fail a test, but I suspect part of problem is that the way the code generator is trying to click on the selection options won't work.

Try changing the this.click lines where it tries to click on an nth-child to
JavaScript code:
    this.fill('form[name=Form1]', {'lstArea', [0,1,2,3,4,5,6,7,8,9,10]});
Where the array contains all of the indexes you want selected (starting from 0, not 1!).

To start with all the options in 5 selected,
JavaScript code:
casper.start('http://worknet.wisconsin.gov/worknet/daindustry.aspx', {
    method: 'post',
    data: {
        lstNaicsLevel: [0,2,3,4,9]
    }
});
should work and hopefully that gets you past dealing with 6 not being there.

icantfindaname
Jul 1, 2008


Okay, I got it to work, you can just post all the fields but the 6th one, then wait 1000 ticks, and post that field and it works

icantfindaname
Jul 1, 2008


Okay I'm back, I've got the first menu to work, now I'm trying to navigate through the results page, and it's breaking for some reason. This code breaks when trying to hit the reset button on the result page, and the next page button doesn't work for some reason. It's weird though, because I rigged up a test of those buttons specifically that works fine

code:
var x = require('casper').selectXPath;
var fs = require('fs');

var years = [2016, 2015, 2014, 2013, 2012, 2011];
var quarters = [0201, 0202, 0203, 0204];
var csv_record = '';
var query;
var limit = 28;

casper.options.viewportSize = {width: 1920, height: 974};
casper.on('page.error', function(msg, trace) {
   this.echo('Error: ' + msg, 'ERROR');
   for(var i=0; i<trace.length; i++) {
       var step = trace[i];
       this.echo('   ' + step.file + ' (line ' + step.line + ')', 'ERROR');
   }
});

casper.test.begin('Resurrectio test', function(test) {
	var csv_record = '';
	
	casper.start('http://worknet.wisconsin.gov/worknet/daindustry.aspx');
		
	for (i = 0; i < years.length; i++) {
		for (j = 0; j < quarters.length; j++) {
			
			csv_record = '';

			casper.then(function() {
				this.fill('form#Form1', {
					'lstArea':			'5504ALL',
					'lstYear':			'2016',
					'lstPerType':		'02',
					'lstPeriod':		'0201',
					'lstNaicsLevel':	'9',
//					'lstIndustry':		'1319131    ',
					'lstOwnership':		'60',
					'lstReportValues':	'Total Wages $'
				});

			});
			
			casper.wait(1000);
			
			casper.then(function() {

				this.fill('form#Form1', {
					'lstIndustry':		'1319131    ',
				});

				this.click("input[name='btnResults']");
			});
			
//	form[name=Form1]

			casper.then(function() {
				for (m = 0; m < 3; m++) {
					this.waitForSelector("input[name='btnRestart']");
					
					this.echo("ping\n");
					
					this.capture(m.toString() + 'screenshot.png');

					if (m == 2) { limit = 25; } else { limit = 28; }

					for (n = 3; n < limit; n++) {
						query = 'span[id*="ctl' + n.toString() + '_Label14"]';

						csv_record = csv_record + this.fetchText(query) + ',';
					}

					if (m == 2) {
						this.click("input[name='btnRestart']"); //This line breaks it, don't know why
					} else { 
						this.click("input[name='btnPageNext']"); //This line does not do anything, don't know why
					}

				}
			
				fs.write('totalwages.csv', csv_record + '\n', 'a+');
			});
		}
	}

	casper.run(function() {test.done();});
});
code:
ping

ping

ping

FAIL Errors encountered while filling form: Unable to find field element in form: FieldNotFound: setField: Invalid field ; on
ly HTMLElement is supported; Unable to find field element in form: FieldNotFound: setField: Invalid field ; only HTMLElement
is supported; Unable to find field element in form: FieldNotFound: setField: Invalid field ; only HTMLElement is supported; U
nable to find field element in form: FieldNotFound: setField: Invalid field ; only HTMLElement is supported; Unable to find f
ield element in form: FieldNotFound: setField: Invalid field ; only HTMLElement is supported; Unable to find field element in
 form: FieldNotFound: setField: Invalid field ; only HTMLElement is supported; Unable to find field element in form: FieldNot
Found: setField: Invalid field ; only HTMLElement is supported
#    type: uncaughtError
#    file: test.js:873
#    error: Errors encountered while filling form: Unable to find field element in form: FieldNotFound: setField: Invalid fie
ld ; only HTMLElement is supported; Unable to find field element in form: FieldNotFound: setField: Invalid field ; only HTMLE
lement is supported; Unable to find field element in form: FieldNotFound: setField: Invalid field ; only HTMLElement is suppo
rted; Unable to find field element in form: FieldNotFound: setField: Invalid field ; only HTMLElement is supported; Unable to
 find field element in form: FieldNotFound: setField: Invalid field ; only HTMLElement is supported; Unable to find field ele
ment in form: FieldNotFound: setField: Invalid field ; only HTMLElement is supported; Unable to find field element in form: F
ieldNotFound: setField: Invalid field ; only HTMLElement is supported
#           fillForm@phantomjs://platform/casper.js:873:62
#           fillNames@phantomjs://platform/casper.js:936:25
#           phantomjs://code/test.js:30:14
#           runStep@phantomjs://platform/casper.js:1685:31
#           checkStep@phantomjs://platform/casper.js:414:28
#    stack: not provided
FAIL Errors encountered while filling form: Unable to find field element in form: FieldNotFound: setField: Invalid field ; on
ly HTMLElement is supported
#    type: uncaughtError
#    file: test.js:873
#    error: Errors encountered while filling form: Unable to find field element in form: FieldNotFound: setField: Invalid fie
ld ; only HTMLElement is supported
#           fillForm@phantomjs://platform/casper.js:873:62
#           fillNames@phantomjs://platform/casper.js:936:25
#           phantomjs://code/test.js:47:14
#           runStep@phantomjs://platform/casper.js:1685:31
#           checkStep@phantomjs://platform/casper.js:414:28
#    stack: not provided
This code works fine though

code:
var x = require('casper').selectXPath;

var years = ['2016', '2015', '2014', '2013', '2012', '2011'];
var quarters = ['0201', '0202', '0203', '0204'];

casper.options.viewportSize = {width: 1920, height: 974};
casper.on('page.error', function(msg, trace) {
   this.echo('Error: ' + msg, 'ERROR');
   for(var i=0; i<trace.length; i++) {
       var step = trace[i];
       this.echo('   ' + step.file + ' (line ' + step.line + ')', 'ERROR');
   }
});

casper.test.begin('Resurrectio test', function(test) {
	casper.start('http://worknet.wisconsin.gov/worknet/daindustry.aspx');

	casper.then(function() {
		this.fill('form#Form1', {
			'lstArea':			'5504ALL',
			'lstYear':			'2016',
			'lstPerType':		'02',
			'lstPeriod':		'0201',
			'lstNaicsLevel':	'9',
			'lstOwnership':		'60',
			'lstReportValues':	'Total Wages $'
		});

	});

	casper.wait(1000);

	casper.then(function() {

		this.fill('form#Form1', {
			'lstIndustry':		'1319131    ',
		});

		this.capture('one.png');

		this.click("input[name='btnResults']");
	});
	
//	form[name=Form1]

	casper.wait(1000);	//Might be needed
	
	casper.then(function() {
		this.capture('two.png');
		
		this.click("input[name='btnPageNext']");
	});
	
	casper.wait(1000);
/*
	casper.then(function() {
		this.fill('form#Form1', {
			'lstArea':			'5504ALL',
			'lstYear':			'2011',
			'lstPerType':		'02',
			'lstPeriod':		'0204',
			'lstNaicsLevel':	'9',
			'lstOwnership':		'60',
			'lstReportValues':	'Total Wages $'
		});
	});
	
	casper.wait(1000);
*/
	casper.then(function() {

//		this.fill('form#Form1', {
//			'lstIndustry':		'1319131    ',
//		});
		
		this.capture('three.png');

		this.click("input[name='btnRestart']");
	});

	casper.wait(1000);	//Might be needed
	
	casper.run(function() {
		this.capture('four.png');
		
		test.done();
	});
});

mystes
May 31, 2006

Pollyanna posted:

Also, I have weird luck and I apply to lots of places on AngelList. This one was a throwaway where my note to them was "Do you do cats?".
Maybe they thought you meant the Scala library Cats and liked incomprehensible code?

reversefungi
Nov 27, 2003

Master of the high hat!
Anyone here watched a TypeScript course on Udemy (or something similar) that they'd recommend? I've gone through some of the official stuff which is really good, but I find going through some series of video lectures/examples help me buckle down and go more deeply into a topic.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I've had a great experience with TypeScript, but I haven't had any trouble figuring it out from the documentation provided on the official website. Since it's a superset of ES2015+, the massive bulk of TypeScript is just existing valid JavaScript code. It adds a few features but mostly not.

In fact it replaces some things you used to need like Babel.

icantfindaname
Jul 1, 2008


Okay I'm back again, sorry for asking so many questions on this one topic. Now I'm just trying to click the download button on that page and save the file in CasperJS, but I'm not sure how to do it, because the file generated has no fixed URL and is generated by a script. I tried to implement the suggestion from this website, but it gives me an error saying theFormRequest.action is null

https://stackoverflow.com/questions/16144252/downloading-a-file-that-comes-as-an-attachment-in-a-post-request-response-in-pha

code:
casper.test.begin('Resurrectio test', function(test) {
			casper.start('http://worknet.wisconsin.gov/worknet/daindustry.aspx');

			casper.then(function() {
				this.fill('form#Form1', {
					'lstArea':			'5504ALL',
					'lstYear':			['2016', '2015', '2014', '2013', '2012', '2011'],
					'lstPerType':		'02',
					'lstPeriod':		['0201', '0202', '0203', '0204'],
					'lstNaicsLevel':	'9',
					'lstOwnership':		'60',
					'lstReportValues':	'Total Wages $'
				});

			});
			
			casper.wait(1000);
			
			casper.then(function() {

				this.fill('form#Form1', {
					'lstIndustry':		'1319131    ',
				});

				this.click("input[name='btnResults']");
			});
			
			casper.wait(1000);

			casper.then(function() {
				var formRequest = this.page.evaluate(function() {
					var request = {};
					var formDom = document.forms["Form1"];
					formDom.onsubmit = function() {
						var data = {};
						for(var i = 0; i < formDom.elements.length; i++) {
							data[formDom.elements[i].name] = formDom.elements[i].value;
						}
						request.action = formDom.action;
						request.data = data;
						return false; //Stop form submission
					}
					
					this.click("input[name='btnDownload']");
					
					return request;
				});
				
				this.download(formRequest.action, "industry.csv", "POST", formRequest.data);
			});

	casper.run(function() {this.capture('jesus.png'); test.done();});
});

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
I have a question that I'm not really sure what the best practice is for this topic

I want to give a customer the ability to fill out a form and enter what country they're from on a cart page so that when they get to the checkout page the country field will be pre-populated with that country they entered.

Should i throw the entry in the url? Should i save it in a cookie? Is there a better way of doing it?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Grump posted:

I have a question that I'm not really sure what the best practice is for this topic

I want to give a customer the ability to fill out a form and enter what country they're from on a cart page so that when they get to the checkout page the country field will be pre-populated with that country they entered.

Should i throw the entry in the url? Should i save it in a cookie? Is there a better way of doing it?

I manage stuff like that with session data, which is tracked with a cookie in my framework of choice. (Django) - you can see an example of what that ends up looking like from a user perspective at https://archierose.com.au - I do a few more things to keep calcing shipping costs at the same time, which you can see if watch the xhr in the network tab.

Vesi
Jan 12, 2005

pikachu looking at?
same way as the rest of the cart data would be best practice so they have the same lifetime

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
Yeah i'm pretty limited to only writing to the front-end.

Is it possible to save data to session storage with JS?

geeves
Sep 16, 2004

Grump posted:

Yeah i'm pretty limited to only writing to the front-end.

Is it possible to save data to session storage with JS?

Yes. But it's not available to the server until you send it.

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

geeves posted:

Yes. But it's not available to the server until you send it.

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Of course that might be enough if the JavaScript accessing the session storage is then just altering the form that's in the checkout page.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
I'll give it a shot and report back

huhu
Feb 24, 2006
Anyone have a good article/video that talks about how to best make selections with jQuery? I'm looking for something more comprehensive than a tips and tricks article which is all I'm seeing on Google.

Honest Thief
Jan 11, 2009

huhu posted:

Anyone have a good article/video that talks about how to best make selections with jQuery? I'm looking for something more comprehensive than a tips and tricks article which is all I'm seeing on Google.

What you mean by best selections? Like CSS queries?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



icantfindaname posted:

Okay I'm back again, sorry for asking so many questions on this one topic. Now I'm just trying to click the download button on that page and save the file in CasperJS, but I'm not sure how to do it, because the file generated has no fixed URL and is generated by a script. I tried to implement the suggestion from this website, but it gives me an error saying theFormRequest.action is null

https://stackoverflow.com/questions/16144252/downloading-a-file-that-comes-as-an-attachment-in-a-post-request-response-in-pha

code:
casper.test.begin('Resurrectio test', function(test) {
			casper.start('http://worknet.wisconsin.gov/worknet/daindustry.aspx');

			casper.then(function() {
				this.fill('form#Form1', {
					'lstArea':			'5504ALL',
					'lstYear':			['2016', '2015', '2014', '2013', '2012', '2011'],
					'lstPerType':		'02',
					'lstPeriod':		['0201', '0202', '0203', '0204'],
					'lstNaicsLevel':	'9',
					'lstOwnership':		'60',
					'lstReportValues':	'Total Wages $'
				});

			});
			
			casper.wait(1000);
			
			casper.then(function() {

				this.fill('form#Form1', {
					'lstIndustry':		'1319131    ',
				});

				this.click("input[name='btnResults']");
			});
			
			casper.wait(1000);

			casper.then(function() {
				var formRequest = this.page.evaluate(function() {
					var request = {};
					var formDom = document.forms["Form1"];
					formDom.onsubmit = function() {
						var data = {};
						for(var i = 0; i < formDom.elements.length; i++) {
							data[formDom.elements[i].name] = formDom.elements[i].value;
						}
						request.action = formDom.action;
						request.data = data;
						return false; //Stop form submission
					}
					
					this.click("input[name='btnDownload']");
					
					return request;
				});
				
				this.download(formRequest.action, "industry.csv", "POST", formRequest.data);
			});

	casper.run(function() {this.capture('jesus.png'); test.done();});
});

this.click won't work inside of an evaluated function because it's running in the page's context rather than Phantom's. Try this
JavaScript code:
var formRequest = this.page.evaluate(function() {
    var formDom = document.forms["Form1"];
    return {
        action: formDom.action,
        data: new FormData(formDom)
    };
});

huhu
Feb 24, 2006

Honest Thief posted:

What you mean by best selections? Like CSS queries?

What is the most efficient way to navigate the DOM with jQuery. For example, I know

Good:
code:
$table = $("#myTable");
$table.doX();
$table.doY();
Bad:
code:
$("#myTable").doX();
$("#myTable").doY();
But beyond that I'm wondering what else I should know... if anything.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



huhu posted:

What is the most efficient way to navigate the DOM with jQuery. For example, I know

Good:
code:
$table = $("#myTable");
$table.doX();
$table.doY();
Bad:
code:
$("#myTable").doX();
$("#myTable").doY();
But beyond that I'm wondering what else I should know... if anything.

IDs < classes < anything else you can do with a CSS selector < anything jQ selectors can do beyond the CSS spec (because that's done in JS)

Where < means 'is faster than'

icantfindaname
Jul 1, 2008


Munkeymon posted:

this.click won't work inside of an evaluated function because it's running in the page's context rather than Phantom's. Try this

That runs, but just gives me the HTML page in industry.csv

Is there a way to trigger the download button click inside the download function, as an argument to the POST option?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



icantfindaname posted:

Is there a way to trigger the download button click inside the download function, as an argument to the POST option?

I'm not sure what you mean by that, but I think you just need to add btnDownload.x and btnDownload.y to the form data like so

JavaScript code:
formRequest.data.append("btnDownload.x", 10);
formRequest.data.append("btnDownload.y", 10);
this.download //etc
Because that seems to be the difference between getting the HTML and CSV results when I gently caress with the POST parameters.

Really not sure how Phantom's support for attachment content-disposition is still so loving bad :\

E: I should probably explain that I figured that out by clicking the download button and looking at the request in Chrome's dev tools, then comparing the POST parameters in that request to the ones sent when the results load. Difference was the btnDownload ones. Confirmed by pasting the ones that trigger CSV results into Postman and deleting btnDownload

Munkeymon fucked around with this message at 14:51 on Jul 10, 2017

huhu
Feb 24, 2006
code:
var list = ["a", "b"];
for (var item in list) {
    var postData = {
	item: item
    };

console.log(postData[item]);

    genAjaxPost(postData,
        "/dest/place",
        "",
        function (data) {
            console.log(postData[item]);
        })
};
The result of console.log() is:

code:
"a"
"b"
"b"
"b"
There are definitely some syntax errors in this JS. Why is the for loop running twice to get the two items "a" and "b" but the Ajax post only gets "b" twice?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



huhu posted:

code:
var list = ["a", "b"];
for (var item in list) {
    var postData = {
	item: item
    };

console.log(postData[item]);

    genAjaxPost(postData,
        "/dest/place",
        "",
        function (data) {
            console.log(postData[item]);
        })
};
The result of console.log() is:

code:
"a"
"b"
"b"
"b"
There are definitely some syntax errors in this JS. Why is the for loop running twice to get the two items "a" and "b" but the Ajax post only gets "b" twice?

Just as a hint, the console.log in your callback isn't logging what you probably think it's logging.

ROFLburger
Jan 12, 2006

huhu posted:

code:
var list = ["a", "b"];
for (var item in list) {
    var postData = {
	item: item
    };

console.log(postData[item]);

    genAjaxPost(postData,
        "/dest/place",
        "",
        function (data) {
            console.log(postData[item]);
        })
};
The result of console.log() is:

code:
"a"
"b"
"b"
"b"
There are definitely some syntax errors in this JS. Why is the for loop running twice to get the two items "a" and "b" but the Ajax post only gets "b" twice?

Looks like by the time your ajax callback is invoked, the loop has completed and the value of postdata is going to be {item: "b"}

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

huhu posted:

code:
var f = function(item) {
	var postData = {
		item: item
	};
	console.log(postData[item]);

	genAjaxPost(postData, "/dest/place", "",
        function (data) {
            console.log(postData[item]);
        })
}

var list = ["a", "b"];
for (var item in list) {
	f(item);
};



Try this

Honest Thief
Jan 11, 2009
Maybe this is just me bitching and being annoying but it seems every other article about some new js tool barely covers the basic use cases. Case in point, I'm trying to figure out the syntax it accepts for custom routing, only the given example on the repo doesn't work, and none of the article I can find seem to consider the possibility of wanting to have custom routes.
edit:Ok, fine, it uses path-to-regexp, but some headsup would be nice

Honest Thief fucked around with this message at 17:14 on Jul 10, 2017

ROFLburger
Jan 12, 2006

That's been my experience too, and it certainly seems like it's more common with JS libraries than anything else I've worked with

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
So lately I've been trying to craft a utility library in TypeScript, but I'm stumped on how I can use import statements in my TypeScript but still have everything output as a single Javascript file.

Let me clarify: I currently have something working if I keep everything within a single .ts file. tsc outputs a single .js file with a global object available on window and I can invoke its various methods no problem:
JavaScript code:
// dist/index.js
var KaleLib = (function () {
    function KaleLib() {
    }
    KaleLib.prototype.send = function (event) {
        console.log("Sending " + event.type + " event for " + event.userId + " that viewed " + event.itemId + " on " + event.timestamp.getTime());
    };
    return KaleLib;
}());
window.KaleLib = new KaleLib();
code:
<!-- some-webpage.html -->
<script src="dist/index.js"></script>
<script>
  KaleLib.send({
    type: 'pageview',
    userId: 'IAmKale',
    itemId: '1234',
    timestamp: new Date(),
  });
</script>
This all works exactly as expected.

The issue is that when I try to break up my code into multiple .ts files and then import them into index.ts. When I go this route tsc outputs everything as CommonJS modules (as configured in my tsconfig.json) which requires me to add in something to load the modules, and polyfills, and other extraneous code. I'm trying to keep the library as small as possible so this is less than ideal.

So here's my question: How can I break up and organize my code into multiple files, but get tsc to output a single JavaScript file in basic ES5?

Adbot
ADBOT LOVES YOU

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

IAmKale posted:

So lately I've been trying to craft a utility library in TypeScript, but I'm stumped on how I can use import statements in my TypeScript but still have everything output as a single Javascript file.

Let me clarify: I currently have something working if I keep everything within a single .ts file. tsc outputs a single .js file with a global object available on window and I can invoke its various methods no problem:
JavaScript code:
// dist/index.js
var KaleLib = (function () {
    function KaleLib() {
    }
    KaleLib.prototype.send = function (event) {
        console.log("Sending " + event.type + " event for " + event.userId + " that viewed " + event.itemId + " on " + event.timestamp.getTime());
    };
    return KaleLib;
}());
window.KaleLib = new KaleLib();
code:
<!-- some-webpage.html -->
<script src="dist/index.js"></script>
<script>
  KaleLib.send({
    type: 'pageview',
    userId: 'IAmKale',
    itemId: '1234',
    timestamp: new Date(),
  });
</script>
This all works exactly as expected.

The issue is that when I try to break up my code into multiple .ts files and then import them into index.ts. When I go this route tsc outputs everything as CommonJS modules (as configured in my tsconfig.json) which requires me to add in something to load the modules, and polyfills, and other extraneous code. I'm trying to keep the library as small as possible so this is less than ideal.

So here's my question: How can I break up and organize my code into multiple files, but get tsc to output a single JavaScript file in basic ES5?

You can use TypeScript internal namespaces to manage the code across multiple files, and then do a simple concatenation of all the files. I usually use gulp-typescript and gulp-concat to do this, but you might be able to get tsc to do it by itself. PM me for a specific example if you need one.

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