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
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.
Another promises question. Whats the best way to run promises in parallel but then do something once all have resolved.

For instance, I know how to chain promises:
code:
PromiseA().then(PromiseB).then(PromiseC).done(something).fail(err);
But this runs in series, completing promiseA and then beginning the promise for B. How do I run PromiseA and PromiseB at the same time but only do something once they are both complete?

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

Another promises question. Whats the best way to run promises in parallel but then do something once all have resolved.

For instance, I know how to chain promises:
code:
PromiseA().then(PromiseB).then(PromiseC).done(something).fail(err);
But this runs in series, completing promiseA and then beginning the promise for B. How do I run PromiseA and PromiseB at the same time but only do something once they are both complete?

Promise.all

Takes an array of promises and resolves when ALL of those resolve.

JavaScript code:
Promise.all( [PromiseA, PromiseB] ).then(
   // A and B did their thing!
).catch(
  // A or B messed up!
);

pepito sanchez
Apr 3, 2004
I'm not mexican

piratepilates posted:


From what I gather about the whole picture (and I'm sure Subjunctive has a lot to say about all of it), the hands on implementation would be to use React for views, communicating with Flux to drive all of the other components and state, Relay to talk to your backends, Immutable.js for data structures and nice immutability, and Flow for type checking all of it.

This is why I gave up on backbone. I don't mind complexity. I do mind something that doesn't deliver a complete solution to a given problem. for backbone companies have either written their own libraries on top of it or use marionette -- a heavy library where you only truly require less than half of the modules to make backbone do what you want. i only started on angular because it did offer something like a complete solution, even if i did have to use a few external libraries like ui-router to make production quality anything other than bad.

likely React/Relay/Flux all culminates into something that can be called a "framework" but right now it's looking like a bundle of things in its immaturity. it's do-able of course. obviously it's been done and being done, but the entire point for me is reducing headaches and having to reinvent the wheel. this is when any library or framework or language is bad compared to a better option.

all of your points are well taken and it's true that MVC has become something of a loose thing, where ultimately in the front-end it's really a matter of convenience and readability. angular itself is really just a MVVM framework, not really MVC like you'll see in .NET or Spring, or probably Django.

granted Relay is a newer and immature thing, but I'm very interested to see where it goes from here. having to depend on the backend developer having the same code you do isn't so awesome unless you're the person doing all the work.

I'm happy to see type definitions for React and Flux in TypeScript, but i'm looking at flow and flow's website for the first time now. is there any special reason you use flow over TS?

piratepilates
Mar 28, 2004

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



pepito sanchez posted:

This is why I gave up on backbone. I don't mind complexity. I do mind something that doesn't deliver a complete solution to a given problem. for backbone companies have either written their own libraries on top of it or use marionette -- a heavy library where you only truly require less than half of the modules to make backbone do what you want. i only started on angular because it did offer something like a complete solution, even if i did have to use a few external libraries like ui-router to make production quality anything other than bad.

likely React/Relay/Flux all culminates into something that can be called a "framework" but right now it's looking like a bundle of things in its immaturity. it's do-able of course. obviously it's been done and being done, but the entire point for me is reducing headaches and having to reinvent the wheel. this is when any library or framework or language is bad compared to a better option.

all of your points are well taken and it's true that MVC has become something of a loose thing, where ultimately in the front-end it's really a matter of convenience and readability. angular itself is really just a MVVM framework, not really MVC like you'll see in .NET or Spring, or probably Django.

granted Relay is a newer and immature thing, but I'm very interested to see where it goes from here. having to depend on the backend developer having the same code you do isn't so awesome unless you're the person doing all the work.

I'm happy to see type definitions for React and Flux in TypeScript, but i'm looking at flow and flow's website for the first time now. is there any special reason you use flow over TS?

I don't, I use typescript.

Facebook uses flow because they made it. The main difference is that flow is targeting a deeper level of type inference from what I can tell, where all typing is evident through analysis on objects and their modification. Typescript takes s a more structured approach and is a superset of JavaScript where types are determined somewhat through inference, and somewhat through specific structures (their own class system, enums, etc.).

At this point the differences don't matter, they both have almost the same features and are being developed so quickly that you won't really feel bad about choosing one instead of the other in a year.

Edit:I will say, one nice thing to say about the maturity of the Facebook stack is that it is being embraced in production by (one of) the most widely used websites today. I believe the big ticket item for angular these days is still the YouTube app on the PS3.

piratepilates fucked around with this message at 18:43 on Aug 24, 2015

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

piratepilates posted:

Edit:I will say, one nice thing to say about the maturity of the Facebook stack is that it is being embraced in production by (one of) the most widely used websites today. I believe the big ticket item for angular these days is still the YouTube app on the PS3.
Angular was written by the DoubleClick team within Google and the entire DoubleClick frontend platform runs on AngularJS. It's been the largest production AngularJS project for a long, long time.

bartkusa
Sep 25, 2005

Air, Fire, Earth, Hope

piratepilates posted:

From what I gather about the whole picture (and I'm sure Subjunctive has a lot to say about all of it), the hands on implementation would be to use React for views, communicating with Flux to drive all of the other components and state, Relay to talk to your backends, Immutable.js for data structures and nice immutability, and Flow for type checking all of it.

I think Relay competes with Flux. Flux is top-down. Relay is bottom-up.

Relay lets data requests devolve to the component level, instead of being centralized in stores. If a deeply-nested component needs something from the DB, it's kind of awful to force its parents' and the store to know what it needs and pass it down. Every file ends up getting touched by every feature.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
I said a bunch of words about Angular vs React and stuff cause I wanted to practice speaking the idea.

https://www.youtube.com/watch?v=CJuaB65k_vM

A bunch of libraries that work well together is not a framework, so you shouldn't look at React + Flux with some sort of expectation of a framework. That's totes okay though, because if you structure your application with good libraries you can actually end up with a better architecture that doesn't rely on heavy coupling. The less coupling you can get away with without sacrificing productivity (usually coupling is accepted because it makes it quicker to develop, with an ORM, data model, etc etc), the better position you'll be in to adopt new tech. Usually that's harder if you adopt a framework, you upgrade at the pace it does (so if you pick a framework, pick the right horse or you'll regret it).

pepito sanchez
Apr 3, 2004
I'm not mexican

Maluco Marinero posted:

I said a bunch of words about Angular vs React and stuff cause I wanted to practice speaking the idea.

https://www.youtube.com/watch?v=CJuaB65k_vM

A bunch of libraries that work well together is not a framework, so you shouldn't look at React + Flux with some sort of expectation of a framework. That's totes okay though, because if you structure your application with good libraries you can actually end up with a better architecture that doesn't rely on heavy coupling. The less coupling you can get away with without sacrificing productivity (usually coupling is accepted because it makes it quicker to develop, with an ORM, data model, etc etc), the better position you'll be in to adopt new tech. Usually that's harder if you adopt a framework, you upgrade at the pace it does (so if you pick a framework, pick the right horse or you'll regret it).

it's a good point that it does definitely depend on the context of the situation and what the project demands. the rest of this post is mainly opinion. i chose angular for a reason. starting on front-end development and steering away from pure js and jQuery i had to choose something that worked friendly with a backend i had to adapt to, and provided a solution for "views" in single-page "app" style. before this it was all relying a lot on the backend rendering PHP partials, which is perfectly acceptable until you're in a company where that side of development is being overworked. a RESTful api with thin middleware wasn't an option but a necessity. backbone seemed like an easy and cool and lightweight solution at first. then you pile on marionette because you realize you need it. then i found out it was complicated and overweight, and what turned me away was how much code i never actually used was being loaded onto a page just to make something functional. libraries and libraries and monkey patches upon a skeleton of a framework. i hate sounding like it's a promotion but angular made it really easy in a complete package. the only external libraries i use are ui-router and lodash unless there's a specific need for ease in something else, like with google maps, and they're just helper libraries, not requirements or dependencies in the grand scheme.

so that's what keeps me away from immature libraries, or related bundles of them seeming to form a kind of framework. the point is avoiding a headache before it starts. i think the only downsides to angular are the learning curve and the backwards incompatibility of angular2, whenever that comes out. but i think everyone's going to have to make the transition and migration to es6 eventually. that's why i've been learning how to use typescript.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
All of what you said isn't the fault of the libraries though, and they aren't immature for what they promise to provide. As I said, if you don't know how to pull all that stuff together in a way that keeps things easy to develop, don't do it. If your approach is to pile on new libraries then you will of course end up with a frankenstein system.

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:

Promise.all

Takes an array of promises and resolves when ALL of those resolve.

JavaScript code:
Promise.all( [PromiseA, PromiseB] ).then(
   // A and B did their thing!
).catch(
  // A or B messed up!
);

Thanks, you guys all rock.

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL
React on its own is quite enough to build most SPAs that need to be built. I still have not really found a use for Flux or Flux-alikes despite having 6 React-driven apps in production currently. It seems like a fair number of people coming from Angular want to know "what do I use for Ajax? What do I use for routing? What do I use for my model and controller" and besides routing where the answer is react-router, the answer is "look at NPM or just write javascript". NPM has battle tested libraries for pretty much anything you need to do, so why would you be shopping around for an all in one solution?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Chenghiz posted:

React on its own is quite enough to build most SPAs that need to be built. I still have not really found a use for Flux or Flux-alikes despite having 6 React-driven apps in production currently. It seems like a fair number of people coming from Angular want to know "what do I use for Ajax? What do I use for routing? What do I use for my model and controller" and besides routing where the answer is react-router, the answer is "look at NPM or just write javascript". NPM has battle tested libraries for pretty much anything you need to do, so why would you be shopping around for an all in one solution?

Because then you only have to bookmark one site for all your documentation!

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

Lumpy posted:

Because then you only have to bookmark one site for all your documentation!
stackoverflow.com!

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

pepito sanchez posted:


so that's what keeps me away from immature libraries, or related bundles of them seeming to form a kind of framework. the point is avoiding a headache before it starts. i think the only downsides to angular are the learning curve and the backwards incompatibility of angular2, whenever that comes out. but i think everyone's going to have to make the transition and migration to es6 eventually. that's why i've been learning how to use typescript.

There isn't any 'backwards incompatibility' with Angular 2.0. It's really a different framework, that happens to share some common themes. Angular 2.0 is promising some great things, but it can only do that by completely re-writing everything and abandoning many core concepts in 1.x. If you don't like that it's different, you can keep using 1.x until the end of time, it won't stop working.

TIP
Mar 21, 2006

Your move, creep.



I am in the process of planning out a javascript-based app and I was hoping you guys could push me in the right direction.

My app needs to interact with the Google Drive and Realtime APIs and work on computer and also work as an Android app (preferably wrapped up with Cordova/Crosswalk as I have had good experiences with that).

Where I'm stuck right now is in trying to get the credentials for Google's APIs. I need OAuth 2.0 client ID from the Google Developer's Console but it requires that I enter "Authorized JavaScript origins" or "Authorized redirect URIs". It says if you're initiating authorization from a browser to use "Authorized JavaScript origins", which seems to be the URL you're hosting from. What do I put if I'm just running it off my computer? Do I need to run a local server and use a URI instead? And if so, how will that translate to me wrapping this up as an Android app later?

Any help is hugely appreciated.

TIP fucked around with this message at 06:49 on Aug 31, 2015

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.
Anyone have any node.js ssh tunnelling experience, I am tearing out my hair trying to get something to work.

Say I have this ssh command: "ssh -p1313 -C -g https://www.url.com -L4200:127.0.0.1:33442"

Right its forwarding some ports.

I am trying to get a ssh tunnel connection generated so I can do some http.requests in node.js. However I cannot get it to work. I've tried:

code:
var conn = new Connection();
	conn.on('ready', function() {
	  console.log('Client :: ready');
	  conn.forwardOut("127.0.0.1", 33442, "127.0.0.1", 4200, function(err, stream) {
	    if (err) deferred.reject('STDERR: ' + err);
	    stream.on('close', function() {
	      console.log('Stream :: close');
	      conn.end();
	    }).on('data', function(data) {
	      console.log('STDOUT: ' + data);
		  console.log(data);
	    }).stderr.on('data', function(data) {
	      	console.log('STDERR: ' + data);
	    });	
	});
	}).connect({
	  host: 'www.url.com',
	  port: 1313,
	  username: 'user',
	  privateKey: require('fs').readFileSync('/some/key/file/here', {encoding: "utf8"})
  }).on('error', function(err) {
	  console.log(err);
  });

and

code:
var conn = new Connection();
	conn.on('ready', function() {
	  console.log('Client :: ready');

	conn.exec('nc 127.0.0.1 33442', function(err, stream){

	   if(err) throw err;
	   console.log('ForwardOut Ready!');

	   var c2 = new Connection();

	   c2.connect({
		 sock: stream,
		 username: 'user',
		 privateKey: require('fs').readFileSync('/some/file/here', {encoding: "utf8"})
	   });

	   c2.on('ready', function(){
		 console.log('Connected!');
	   });

	   c2.on('error', function(err) {
		 console.log('Connection2 :: error :: ' + err);
	   });
	   stream.emit('connect'); // needed to simulate a TCP socket
   });


	}).connect({
	  host: 'www.url.com',
	  port: 1313,
	  username: 'user',
	  privateKey: require('fs').readFileSync('/file/here', {encoding: "utf8"})
  }).on('error', function(err) {
	  deferred.reject(err);
  });

and nothing seems to work, I'm ripping my hair out over here.

edit: For the record I am trying to use the SSH 2 package.

Knifegrab fucked around with this message at 15:28 on Sep 3, 2015

9-Volt Assault
Jan 27, 2007

Beter twee tetten in de hand dan tien op de vlucht.
D3.js question:

If i do:
code:
    <script type="text/javascript">
  var dataset;
  d3.csv("spanish-silver.csv", function(error, data) {
    if (error) {
      console.log(error);
    } else
      {console.log(data);
        dataset = data;
      };

});



d3.select("body").selectAll("p")
    .data(dataset)
    .enter()
    .append("p")
    .text("hail satan!");

</script>

i get an empty page and an error message stating "Uncaught TypeError: Cannot read property 'length' of undefined", however the csv gets loaded based on the console output.

If i wrap the second part in a function and call that function it works, printing a bunch of hail satan paragraphs:

code:
    <script type="text/javascript">
	var dataset;
	d3.csv("spanish-silver.csv", function(data) {
      dataset = data;
      satan(dataset);
 	});



	var satan = function(dataset) {d3.select("body").selectAll("p")
		.data(dataset)
		.enter()
		.append("p")
		.text("hail satan");};

</script>
Why is the second example working, but the first not? Im quite clueless about javascript so i should probably learn more about it. :shobon:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Charlie Mopps posted:

D3.js question:

If i do:
code:
    <script type="text/javascript">
  var dataset;
  d3.csv("spanish-silver.csv", function(error, data) {
    if (error) {
      console.log(error);
    } else
      {console.log(data);
        dataset = data;
      };

});



d3.select("body").selectAll("p")
    .data(dataset)
    .enter()
    .append("p")
    .text("hail satan!");

</script>

i get an empty page and an error message stating "Uncaught TypeError: Cannot read property 'length' of undefined", however the csv gets loaded based on the console output.

If i wrap the second part in a function and call that function it works, printing a bunch of hail satan paragraphs:

code:
    <script type="text/javascript">
	var dataset;
	d3.csv("spanish-silver.csv", function(data) {
      dataset = data;
      satan(dataset);
 	});



	var satan = function(dataset) {d3.select("body").selectAll("p")
		.data(dataset)
		.enter()
		.append("p")
		.text("hail satan");};

</script>
Why is the second example working, but the first not? Im quite clueless about javascript so i should probably learn more about it. :shobon:


In your first example here's what happens:

1. var dataset is created, and has value of undefined.
2. d3 is told to load a CSV file and run a callback when it's done
3. d3 is told to select stuff and do somethign with dataset, which is still undefined
4. CSV finishes loading, the callback runs and dataset now has a value

In your second example here's what happens:


1. var dataset is created, and has value of undefined.
2. d3 is told to load a CSV file and run a callback when it's done
3. CSV finishes loading, the callback runs and dataset now has a value
4. satan is run, and d3 is told to select stuff and do something with dataset

Lumpy fucked around with this message at 15:02 on Sep 3, 2015

Video Nasty
Jun 17, 2003

Okay, stupid, long question time. I have a large amount of link elements that point to a receipt page. Between each anchor tag is an order reference number, typically ten digits separated by a period.

Here's an example:
code:
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=682413&OrderId=93406.99350&UserID=76251&Action=VIEW">93406.99350</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=495104&OrderId=12345.75684&UserID=76251&Action=VIEW">12345.75684</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=566987&OrderId=54321.15987&UserID=76251&Action=VIEW">54321.15987</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=155651&OrderId=32323.78998&UserID=76251&Action=VIEW">32323.78998</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=457078&OrderId=12132.45654&UserID=76251&Action=VIEW">12132.45654</a>
These links are all inside table cells, within procedurally generated tables and divs from the underlying aspx code that I'm not allowed to modify.

I wanted to come up with a means to replace the inner text with just the last five digits of the order reference number. Unfortunately, I am only able to use an earlier jQuery build being brought in via CDN, because it ties in to some other javascript functionality that I'm not meant to refactor just yet. Anyway, the purpose of this is to truncate the order reference number, which is returned by the database in that format. I cannot modify the database call, because it also constructs the link for the actual value inserted into the URL; so it breaks functionality of the URL if I truncate the number before it's rendered to the page.

I eventually came up with the following, which basically deconstructs each link by index reference and rebuilds it with different inner text:
code:
<script>
// jQuery.noConflict variable= $j 

var link = $j('td.DataRow a[href*="&OrderId="]');

$j(document).ready(function() {  

  $j(link).each( function() {
     var hyperlink = $j(this).attr('href'), 
     re= new RegExp(/(\d{4,5}\.)(\d{5})/), 
     order= $j(this).text();
     var linkText = $j(this).html("<a href="+ hyperlink +">" + order.replace(re , '$2' ) + " </a> ");

     return linkText;
    });
}); 
</script>
- but when I have something like 1,000 of these URLS to recurse through and modify the DOM on a given page, it destroys page load timing. I feel like there could be a much more efficient way to tackle this and it's been escaping me for days now. :(

edit: fiddle!

Video Nasty fucked around with this message at 04:48 on Sep 4, 2015

piratepilates
Mar 28, 2004

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



Nash Regex posted:

Okay, stupid, long question time. I have a large amount of link elements that point to a receipt page. Between each anchor tag is an order reference number, typically ten digits separated by a period.

Here's an example:

These links are all inside table cells, within procedurally generated tables and divs from the underlying aspx code that I'm not allowed to modify.

I wanted to come up with a means to replace the inner text with just the last five digits of the order reference number. Unfortunately, I am only able to use an earlier jQuery build being brought in via CDN, because it ties in to some other javascript functionality that I'm not meant to refactor just yet. Anyway, the purpose of this is to truncate the order reference number, which is returned by the database in that format. I cannot modify the database call, because it also constructs the link for the actual value inserted into the URL; so it breaks functionality of the URL if I truncate the number before it's rendered to the page.

I eventually came up with the following, which basically deconstructs each link by index reference and rebuilds it with different inner text:


- but when I have something like 1,000 of these URLS to recurse through and modify the DOM on a given page, it destroys page load timing. I feel like there could be a much more efficient way to tackle this and it's been escaping me for days now. :(

edit: fiddle!

Maybe change the inner text manually instead of setting the html? I'd imagine setting the html for each link could have a lot of overhead in rebuilding an element when all you're doing is changing the inner text.

edit: kind of a wild guess but maybe just don't use jQuery for any of that. It's simple enough code to do nowadays in plain JS as long as you're targeting like IE8+, and jQuery can apparently introduce a lot of overhead in certain situations due to extra work it's taking or compatibilities it has to ensure

piratepilates fucked around with this message at 04:56 on Sep 4, 2015

Video Nasty
Jun 17, 2003

piratepilates posted:

Maybe change the inner text manually instead of setting the html? I'd imagine setting the html for each link could have a lot of overhead in rebuilding an element when all you're doing is changing the inner text.

edit: kind of a wild guess but maybe just don't use jQuery for any of that. It's simple enough code to do nowadays in plain JS as long as you're targeting like IE8+, and jQuery can apparently introduce a lot of overhead in certain situations due to extra work it's taking or compatibilities it has to ensure

That's a fair point. To that end, jQuery is getting included either way so I figured it would have been better to utilize, but you're right about the extraneous overhead that comes along with it.

TIP
Mar 21, 2006

Your move, creep.



Nash Regex posted:

- but when I have something like 1,000 of these URLS to recurse through and modify the DOM on a given page, it destroys page load timing. I feel like there could be a much more efficient way to tackle this and it's been escaping me for days now. :(

edit: fiddle!

Working with the DOM is super slow and you're reading and writing to the DOM for every single link. My suggestion would be to grab all the data at once, manipulate it in JavaScript, and then make one update to the DOM with the new values.

geeves
Sep 16, 2004

Tip posted:

Working with the DOM is super slow and you're reading and writing to the DOM for every single link. My suggestion would be to grab all the data at once, manipulate it in JavaScript, and then make one update to the DOM with the new values.

Before the advent of jQuery when adding through the DOM was necessary and innerHTML not feasible because of scoping issues, this was definitely the recommended way to build a large amount of HTML (and really just in general)

German Joey
Dec 18, 2004
Quick question for y'all. its been about a year since I looked into this. is Sails.js / Waterline still the best way to interact with an SQL database in the node.js world? Or is there anything new I should know about?

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

Nash Regex posted:

Okay, stupid, long question time. I have a large amount of link elements that point to a receipt page. Between each anchor tag is an order reference number, typically ten digits separated by a period.

Here's an example:
code:
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=682413&OrderId=93406.99350&UserID=76251&Action=VIEW">93406.99350</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=495104&OrderId=12345.75684&UserID=76251&Action=VIEW">12345.75684</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=566987&OrderId=54321.15987&UserID=76251&Action=VIEW">54321.15987</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=155651&OrderId=32323.78998&UserID=76251&Action=VIEW">32323.78998</a>
<a target="_Blank" href="http://www.website.com/store/OrderReceipt.aspx?PortalID=457078&OrderId=12132.45654&UserID=76251&Action=VIEW">12132.45654</a>
These links are all inside table cells, within procedurally generated tables and divs from the underlying aspx code that I'm not allowed to modify.

I wanted to come up with a means to replace the inner text with just the last five digits of the order reference number. Unfortunately, I am only able to use an earlier jQuery build being brought in via CDN, because it ties in to some other javascript functionality that I'm not meant to refactor just yet. Anyway, the purpose of this is to truncate the order reference number, which is returned by the database in that format. I cannot modify the database call, because it also constructs the link for the actual value inserted into the URL; so it breaks functionality of the URL if I truncate the number before it's rendered to the page.

I eventually came up with the following, which basically deconstructs each link by index reference and rebuilds it with different inner text:
code:
<script>
// jQuery.noConflict variable= $j 

var link = $j('td.DataRow a[href*="&OrderId="]');

$j(document).ready(function() {  

  $j(link).each( function() {
     var hyperlink = $j(this).attr('href'), 
     re= new RegExp(/(\d{4,5}\.)(\d{5})/), 
     order= $j(this).text();
     var linkText = $j(this).html("<a href="+ hyperlink +">" + order.replace(re , '$2' ) + " </a> ");

     return linkText;
    });
}); 
</script>
- but when I have something like 1,000 of these URLS to recurse through and modify the DOM on a given page, it destroys page load timing. I feel like there could be a much more efficient way to tackle this and it's been escaping me for days now. :(

edit: fiddle!

Oh my god I had no idea that javascript had native regular expressions

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

This doesn't seem to be that much faster (45 ms vs the original's 55ms), but it's simpler at least

JavaScript code:
$j = jQuery.noConflict(); 

$j(document).ready(function() {  

   $j('a[href*="&OrderId="]').each( function() {
      var $this = $j(this);
      var re = /\d{4,5}\./;
     
      $this.text($this.text().replace(re, ''));
    });
}); 
I left out the unnecessary call to RegExp constructor, the "link" variable, and instead of replacing the whole element, I just replace the link text.

Also, you're not supposed to return anything from the .each() callback unless you want to break the loop (then return false).

edit: If you want to do the text replacement in steps, use
JavaScript code:
var linkText = $this.text();
var newText = linkText.replace(re, '');
$this.text(newText);

Wheany fucked around with this message at 12:14 on Sep 5, 2015

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Also, the "native" version only takes about 10 ms. (I still use $j(document).ready(), because I don't want to deal with that bullshit);

JavaScript code:
$j = jQuery.noConflict(); 

$j(document).ready(function() {  
    Array.prototype.forEach.call(document.querySelectorAll('a[href*="&OrderId="]'), function(elem) {
        elem.textContent = elem.textContent.replace(/\d{4,5}\./, '');
    });
}); 
That should on everything newer than IE 9

Video Nasty
Jun 17, 2003

Wheany, you own! I wasn't positive that I needed a return from the Each loop, but assumed I still needed to actually output something after reconstructing my element. I have gotten lazy over the years relying on jQuery for most of my heavy javascripting and it's amazing how many rudimentary things I've forgotten as a result. Thanks again dudes.

Electrophotonic
Mar 14, 2010

They're gonna stop
Saturday night
So you better have fun now
I PREDICT


Are there any tools yet for generating GraphQL schemas? The plain JS schema definitions are incredibly verbose and are a pain to write for anything dealing with more data types than, say, a Star Wars ship database by faction (scum & villainy not included).

E: well there are certainly a bunch of attempts but also breaking changes.

Electrophotonic fucked around with this message at 19:53 on Sep 5, 2015

fantastic in plastic
Jun 15, 2007

The Socialist Workers Party's newspaper proved to be a tough sell to downtown businessmen.

German Joey posted:

Quick question for y'all. its been about a year since I looked into this. is Sails.js / Waterline still the best way to interact with an SQL database in the node.js world? Or is there anything new I should know about?

I've used Sequelize and it wasn't too painful. I haven't used Sails/Waterline, though, so I don't know how it compares to them.

piratepilates
Mar 28, 2004

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



German Joey posted:

Quick question for y'all. its been about a year since I looked into this. is Sails.js / Waterline still the best way to interact with an SQL database in the node.js world? Or is there anything new I should know about?

Well I just read this article about Sails.js, helpfully titled "Don’t Use Sails (or Waterline)"

Maybe try Sequelize.

There's something very funny about datastore libraries in Javascript not having stuff like transactions or batch insertions that seem kind of important to have.

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL

piratepilates posted:

There's something very funny about datastore libraries in Javascript not having stuff like transactions or batch insertions that seem kind of important to have.

It's especially weird considering that most of the sql libraries available for node.js have transaction functionality.

TIP
Mar 21, 2006

Your move, creep.



Tip posted:

Where I'm stuck right now is in trying to get the credentials for Google's APIs. I need OAuth 2.0 client ID from the Google Developer's Console but it requires that I enter "Authorized JavaScript origins" or "Authorized redirect URIs". It says if you're initiating authorization from a browser to use "Authorized JavaScript origins", which seems to be the URL you're hosting from. What do I put if I'm just running it off my computer?

Turns out there is an option marked "other" that doesn't require the authorized javascript origins or authorized redirect URIs.

German Joey
Dec 18, 2004

piratepilates posted:

Well I just read this article about Sails.js, helpfully titled "Don’t Use Sails (or Waterline)"

Maybe try Sequelize.

There's something very funny about datastore libraries in Javascript not having stuff like transactions or batch insertions that seem kind of important to have.

Yeah, I just saw that too, and its finally the tipping point for me where I just gave up on node.js completely and go back to Django, or maybe Flask or Mojolicious, I haven't 100% decided yet. But absolutely that blogpost was the moment that I just said "gently caress it, I'm out, I can't deal with this node.js poo poo anymore." I'd rather spend a couple weeks rewriting my entire project then waste one more day fighting with a broken library. Maybe Sequelize is good now (I remember looking at that one specifically a few years ago and it being inadequate, although that was probably an early version because this looks OK), but the trend is pointing to probably not. I'm so sick of every loving javascript library being terrible!!! ARRGHH! Time after time after time, every new thing I look at has some flashy splash page but lovely, outdated, and inconsistent documentation. Every framework has ten trillion pointless preprocessors being stapled to it that otherwise reinvent the same drat wheel. If you need layers upon layers upon layers of build tools for your server-side javascript, then what the gently caress is the point of using javascript on the server side to begin with? Isn't the whole point that both client/server are in the same language, a language that everyone in the entire drat world happens to know and have access to - a language that any ten year old can start playing around with by pressing ctrl-shift-j in their browser? That's why I got into node.js to begin with!

And why is there so many broken rear end libraries/tools in the javascript ecosystem that do the exact same thing and NONE of them work right? It is a pandemic in the Javascript world that completely unlike any other language community I've seen. Even Perl's CPAN, which has shitloads of silly (e.g. the entire Acme:: namespace) and half-baked modules is nowhere near as bad as Javascript's situation because the vast majority of modules there are well-documented, automatically tested, reviewed... and centralized so you can see everything relevant at once. In contrast, new alternatives for the most minor goddamn poo poo are all over the web, especially client libraries. I find that raw jQuery is consistently the only thing I feel I can put my faith in. When I try searching for a new javascript library, I've realized that my initial expectation of *anything* I find is that it will not work or be what I need until proven otherwise. The general trend is to try to make easy poo poo even easier (why? why so much effort on something people can already do just fine?) while very few care about trying to make hard poo poo possible.

Sails/Waterline was the one framework I'd seen that even seemed like it was trying to move in the right direction, and then that turns out to be riddled with mind-bogglingly inane poo poo like this? "mystery 50ms sleep calls in put/post requests" "The .count function used to work by pulling the entire table into memory and checking the length of the resulting array." "table joins randomly deleting tables" "i don't even know what to say about this" I just need code that's supposed to work to just actually work, goddammit!

German Joey fucked around with this message at 11:24 on Sep 8, 2015

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

German Joey posted:

Yeah, I just saw that too, and its finally the tipping point for me where I just gave up on node.js completely and go back to Django, or maybe Flask or Mojolicious, I haven't 100% decided yet. But absolutely that blogpost was the moment that I just said "gently caress it, I'm out, I can't deal with this poo poo anymore." Maybe Sequelize is good now (I remember looking at that one specifically a few years ago and it being inadequate), but the trend is pointing to probably not. I'm so sick of every loving javascript library being terrible. Time after time after time, every new thing I look has some flashy splash page but lovely, outdated, and inconsistent documentation. Every framework has ten trillion pointless preprocessors being stapled to it but otherwise reinvents the same wheel. If you need layers upon layers upon layers of build tools for your server-side javascript, then what the gently caress is the point of using javascript on the server side to begin with? And why is there so many broken rear end libraries/tools in the javascript ecosystem that do the exact same thing and NONE of them work right? That includes client poo poo too; raw jQuery is consistently the only thing I feel I can put my faith in. The general trend is to try to make easy poo poo even easier while nobody cares about trying to make hard poo poo possible. Sails/Waterline was the one framework I'd seen that even seemed like it was trying to move in the right direction, and then that turns out to be riddled with mind-bogglingly inane poo poo like this? "mystery 50ms sleep calls in put/post requests" "The .count function used to work by pulling the entire table into memory and checking the length of the resulting array." "table joins randomly deleting tables" "i don't even know what to say about this" I just need code that's supposed to work to just actually work, goddammit!



You are absolutely right.

And after working a few years with Javascript god drat did it feel good to code Java again. Like, everything doesn't have to be poo poo? What is this?

German Joey
Dec 18, 2004

Wheany posted:



You are absolutely right.

And after working a few years with Javascript god drat did it feel good to code Java again. Like, everything doesn't have to be poo poo? What is this?

Last night I started reading some Flask documentation/tutorials, and I was like, "Wow, goddamn, this is really great." But then I went to look at Django again, (I'd used it heavily 3-4 years ago), specifically a websockets library called Swampdragon, and it was really well documented too! Full API documentation, multiple full walkthroughs/examples for setting up a new app (and they actually worked). Amazing! And then I read some article comparing Flask/Django/Pyramid and one minor negative it brought up against both Flask and Django was that their documentation was "ok, but not the best."

...

I had forgotten that this is what the rest of the dev world actually expects as a bare minimum. :gonk:

piratepilates
Mar 28, 2004

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



I find the worst is when a JS library has an API reference but doesn't actually go in to detail on what a function is expecting as a type, what it returns as a type, it's error behaviour, or what it really does. Here's an identifier, go play with it in the REPL until you know what it does!

Doesn't hold true for everything (ArcGIS Javascript Map viewer is what I've been working with lately and it's actually pretty decent in terms of the above and samples) but drat is it annoying to find the one 'suggested' library for the thing you want to do and it turns out to have the worst documentation.

edit: Or just go look through all the pull requests! Look through all the source and pull requests, why wouldn't you, this is normal!

Edit: can't forget my favourite return type listing -- Promise. So what does this return? "A promise" ...great so what value is coming back in that promise for me to use? "Good luck!"

piratepilates fucked around with this message at 14:59 on Sep 8, 2015

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

German Joey posted:

a language that any ten year old can start playing around with by pressing ctrl-shift-j in their browser? That's why I got into node.js to begin with!

I think I found some of your problem. Having such a low barrier to entry allows a lot of crap in.

qntm
Jun 17, 2009

German Joey posted:

"mystery 50ms sleep calls in put/post requests"

Awesome!

Adbot
ADBOT LOVES YOU

pepito sanchez
Apr 3, 2004
I'm not mexican

quote:


// It is deliberately not configurable for now, since it's not really

holy poo poo

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