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
geeves
Sep 16, 2004

dancavallaro posted:

What is an example of a use case where it makes sense to use == over ===?

The only time I ever had trouble with not being able to use === is if I had to check for "undefined" for some reason. For some reason it always failed (not sure if it still does)

One of my former coworkers pissed me off by constantly doing this:

code:

if (typeof arg1 == 'string') {
    if (arg1 == 'something') {
        dothis();
    }

}

instead of:

if ("something" === arg1) {
    dothis();
}

Adbot
ADBOT LOVES YOU

geeves
Sep 16, 2004

Golbez posted:

My question was more along the lines of, why would geeves' coworker even need to do a 'typeof' in this case? The only possible type that can ever == "something" is a string. It's not like == "1", where a string or int could work.

I'm slowly moving towards using ===s, though since most of my work is in PHP, and form submissions are always strings, that can sometimes be a little counterintuitive.

That's the point. My coworker didn't have to check for typeof because it was already handled in a method that would always return a String or an Integer or Boolean, etc. Even though JavaScript doesn't support real strong typed members, it's just something I've become picky about from my experience in Java and brought into my JS coding and it's also greatly reduced the type I've had to spend debugging.

geeves
Sep 16, 2004

I don't know if this is a jQuery thing or not, but has anyone every successfully made a variable inside an anonymous function readable outside of it?

We did this at my old job so we would avoid collisions amongst us writing lots of JS. But I didn't come up with how it was done and I've been unsuccessful in trying to recreate it from memory. It was something maniacal involving the window object.

code:
($, window, function() {
   
   // I think it was window.document
   var foo = window.document = foo;

   foo = {
       bar : function(sa) {

      }
   };


})($, window); //I think it was this again from memory 

// then foo is available outside of it which was great to add to <a>, <li> etc.

foo.bar("string");



Any ideas?

geeves
Sep 16, 2004

Xenogenesis posted:

Just assign that variable to some arbitrary property on "window". The window object is also the top level scope, so any properties you define on it are global variables. Simple example:

code:
(function () {
  var someISH = {
    prop: "value",
    hi: function () { alert(":3");}
  };

  window.someISH = someISH;
})();

someISH.hi();
Just so you know whats going on here...

code:
($, window, function () {
The "$, window, " is useless: this is because comma is being used as the expression operator. The comma is splitting whats in the parens into three expressions, but the value of a statement is the last expression evaluated. So the $ and window are just random variables chilling there for no reason; the function (and later, its invocation) is the only thing really happening there.

code:
var foo = window.document = foo
This just sets window.document to undefined. Proooobaly not what you want.

code:
})($, window)
The actual function invocation. The parens are used around the function because for whatever reason Javascript doesn't let you immediately invoke a declared function unless the "function" keyword is preceded by some token. The token doesn't really matter; you could do +function () {}(), ~function () {}(), any unary operator, but most people wrap the function in parens.

Also, no need to pass $ and window to the function, as your function does nothing with its arguments.

For writing a library. Reusable code isn't *usable* unless... you have some way to use it. Most of the time you're only "exporting" one variable anyway, so you don't have to worry about conflicts too much. It's basically namespace emulation.

That was it, thanks.

It has been a couple of months since I've seen the code and I didn't write the part that started with ($, window, function) ... so I don't know why that was in there and I had too many other things to work on that I never got around to doing a code review before I left my old job.

geeves
Sep 16, 2004

Lumpy posted:

Javascript will add semi-colons for you. And that's a Bad Thing.

Example:

code:
function poop (arg) {
  var blah = arg;
  return
  {
     someThing: blah,
     otherThng: 13
  }
}

var gleep = poop(2);
What is gleep ? If you said UNDEFINED you are right! Javascript slapped a semi-colon after the return and the rest of the stuff is ignored.

On the other hand, I'm not sure why anyone would define their object in the actual return value instead of prior to it.

geeves
Sep 16, 2004

Lumpy posted:

I do it constantly, and it's one of the "big three" patterns in JavaScript, the Module Pattern.

code:
APP.Thing = (function () {
  var privateVar = 'whee',
         privateMethod = function () {
             //stuff;
         };
   return {
      publicVar: "pants",
      publicMethod: function () {
        alert(privateVar);
      }
  }
}());

I admit I don't like the way it looks. Perhaps because I would never do that in Java. Especially if the returned object was more complex than just 3 lines. Is it interpreted differently than

code:
APP.Thing = (function () {
  var privateVar = 'whee',
         privateMethod = function () {
             //stuff;
         };
  var obj = {
      publicVar: "pants",
      publicMethod: function () {
        alert(privateVar);
  }
   return obj;
  }
}());
? Again, maybe this is more personal preference. But back to your original point - I kinda wish JavaScript would strictly enforce the semi-colon.

geeves
Sep 16, 2004

All Hat posted:

JSLint complains about updateLinks() being called before it's declared. poo poo works, but I wonder if this is a sign of bad coding practices.

I've never gotten this one, but if it's there this is one of those nit-picky things with which I don't agree in JSLint. Functions and declared variables are always hoisted to the top of their scope by the interpreter so they're ready to be used by everything in its scope.

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

geeves
Sep 16, 2004

Lumpy posted:

Except Hoisting does not include the definition of the function (or assignment if it's an expression) if it's declared as a variable:

code:
function poop() {
  alert(f()); // error
  var f = function(){
    return true;
  }
  alert(f()); // would alert true if it got here.
}
If you are engaging in the bad practice of declaring global functions, then yes, the name and declaration will be hoisted, but since you shouldn't be doing that, JSLint is actually providing a helpful warning.

Good catch - I thought that article covered it, it must have been another one or maybe in The Good Parts?.

geeves
Sep 16, 2004

epswing posted:

Use parseInt!

code:
var zipNum = parseInt(zipcode);
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt
Careful with parseInt on zipcodes!

It's better to check for field length and/or use a regex with zip codes because using parseInt could lead to unintended consequenses for codes that start with zero. http://www.w3schools.com/jsref/jsref_parseInt.asp

so instead, something like:

code:
var patt10 = /\d\d\d\d\d-\d\d\d\d/i;
var patt5 = /\d\d\d\d\d/i;
if (10 === zipcode.value.length && zipcode.value.match(patt10)) {
  // valid 5 + 4 zipcode.
} else if (5 === zipcode.value.length && zipcode.value.match(patt5)) {
  // valid 5 digit zipcode.
}
VVVV Much more elegant, regex aren't my strong suit

geeves fucked around with this message at 20:32 on Mar 23, 2011

geeves
Sep 16, 2004

Master_Odin posted:

How would I submit a form inside an iframe? The form is set-up correctly that outside the iframe, it submits fine and what have you. However, when trying to do:
code:
document.getElementById('evilFrame').contentWindow.document.getElementById('evil').submit();
I've tried some variations, but kept just getting that this equals null and so .submit() fails.

The ids are right with the first being the frame and the second being the form.

Try something like this with jQuery:

code:
$("#iFrame").contents().find("#someForm").submit();
Before the .submit() is how to access elements in an iFrame (just note you're subject to the same origin policy.

http://forum.jquery.com/topic/jquery-how-to-access-iframe-window

geeves
Sep 16, 2004

Lumpy posted:

You should put your own semicolons in, but not for any real concern about performance. Putting semicolons in explicitly makes it clear "what you meant" to others (and to yourself in 3 months when you revisit your code) and also avoids some functional "gotchas" where letting the interpreter put them in for you might not give you what you expect / want.

Non-use of semi-colons or not using braces is only of my coding pet peeves with c-style languages. I've tried to contribute to some opensource (mostly jQuery plugins that I use) when I can, especially ones with promise that fall victim to poor coding standards. Only to have the changes rejected and comments deleted when I raise concerns.

geeves
Sep 16, 2004

Mindisgone posted:

I can just call that in the middle of the code? What sort of info will I get?

You can drop anything (strings, objects, arrays, html, etc) into console.log(Obj) and it will display in Firebug or your Javascript Console.

geeves
Sep 16, 2004

Blinkz0rz posted:

I'm getting a bit deeper into JavaScript and I was wondering if anyone had any suggestions for reading about anonymous functions, object literal usage, and general patterns for advanced programming?

Here's an online book about Design Patters in JavaScript that I've used as reference

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

geeves
Sep 16, 2004

Dr. Poz posted:

I just ran into the fact that when instantiating a Date in JavaScript, the constructor parameter for Month is zero-based, meaning that a 1 means February. Is there a clean way to globally override this without making developers remember to use a derived type? I'm using TypeScript for this particular project if that makes a difference.

I've done this in the past as necessary. Drop this into a global JS file.

http://jsfiddle.net/VrU2a/

code:
Date.prototype.getRealMonth = function () {
    return this.getMonth() + 1;
};

geeves
Sep 16, 2004

I have a stupid angular question. I'm trying to get program ID from ng-init, but it's undefined because reasons. I can dump the scope object and the value is defined in the object, with the correct value, however trying to access it doesn't work.

code:
<ng-include src="'/partials/admin/admin-customize-states.html'" ng-init="editable=false;programId=${programId};" ></ng-include>
My controller:

code:
.controller('adminCustomizeStates', ['$scope', 'main', 'admin', function ($scope, main, admin) {
    console.log($scope); // programId exists and the value is what I expect it to be!
    console.log("program 1: " + $scope.programId); // but I'm undefined here because gently caress you.
    admin.getCustomStates($scope.programId, function (data) {
Now, I can get around this by wrapping everything in $scope.$watch("programId", function(){....} but I wonder why I should have to use this work around. For another module I have identical code for the first several lines as above that doesn't give me undefined params.

geeves
Sep 16, 2004

Jabor posted:

Be careful with logging $scope and interpreting the result - the behaviour of the debugger can be more confusing than enlightening. Specifically, the log will show you the value of the $scope object when you clicked the arrow to expand it, not what the value was when the log statement ran.

Chances are the id is being set sometime after this code runs.

I'm just irked with the inconsistency more. I've run into things like this with JS many times in the past. I just went through everything and changed methods to make sure everything runs after the page loads. Everything is fine and back to normal.

geeves
Sep 16, 2004

Knifegrab posted:

I just can't wrap my head around promises. Does anyone have a fool proof tutorial/explanation?

I've been reading through these books - https://github.com/getify/You-Dont-Know-JS

Here's the book & chapter that discusses Promises:

https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/ch3.md

Edit: Hopefully that helps. I'm probably in the same boat as you. I won't see more benefits until I see more real world examples.

geeves fucked around with this message at 20:40 on Jul 23, 2015

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)

geeves
Sep 16, 2004

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 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!

Next time I'm in an interview, if I'm asked about node.js this will be my answer :hfive:

geeves
Sep 16, 2004

Noam Chomsky posted:

Which is?

(I'm genuinely asking.)

Free-form content. One of the best examples (regardless of if you think it's good) is Adobe CQ. It runs on a Java Content Repository JSR-283 is the current implementation off the top of my head (I may be wrong). While the content is structured by type (String, Integer, Date...), it's not bound by a DB structure and is stored in a nodal way so it is very conducive (and CQ has this built in) to simply exporting objects straight to JSON or XML or even HTML.

geeves
Sep 16, 2004

Subjunctive posted:

let doesn't really improve things for garbage collection very much (a bit in cases where you create a lot of garbage in one loop without reusing variables or something?), but binding-per-execution is useful for avoiding traps like the common:

code:
for (var i = 1; i <= 5; i++) {
  items[i].onclick = function (ev) {
    console.log("Item " + i + " is clicked.");
  };
}


I use this as one of my interview questions and ask them, "What's wrong, if anything at all?"

2 out of maybe 14 or 15 candidates this past summer (for a senior-level / managerial position) got the answer right. One asked why I didn't just use jQuery :downs:

geeves
Sep 16, 2004

Tao Jones posted:

Angular question:

My app has a collection, foo, which generates a variety of pages (/foo/1, /foo/2, /foo/3, etc). Foo has a "type" property that can be bar, baz, whatever.

If a user is on a foo page and then navigates to a qaz page, I want qaz to know what "type" the user was looking at before they navigated. But if the user goes from foo to some non-qaz page and then on to qaz, I don't want qaz to know.

My naive idea is to make some kind of fooSharedDataService with a lastFooSeen variable, have fooController set lastFooSeen when it activates, have qazController check the lastFooSeen, and have the other controllers set lastFooSeen to null. But what I really want (because mandating that every controller ever must interact with fooSharedDataService seems dumb) is some kind of global state thing which I don't know if Angular provides.

Is there an Angular tool that can handle a global state thing like this, or alternately is there a better way to solve the problem?

Is it something you can track in $rootScope? It may or may not be the perfect place for it, but it's a start. In the old days of JS i would track this via cookies or browser cookies/session depending on the need. It might not be pretty but it worked.

geeves
Sep 16, 2004

Skandranon posted:

Using $rootScope is almost always a bad idea.

You have the right idea, create a breadCrumbsService to track this. A service is a singleton, so in effect, it IS a single, globally accessible variable. Anyone that is concerned with knowing about where a user has last been, can inject the service.

To elaborate, it's not silly, and not ALL controllers. You may have components in your app which don't care, and thus, don't need it. There is no reason you can't just create var x on the global scope, but it's not the Angular way of doing it.

Also, by creating a service, you can put methods in the service which will manage the logic on how the variables get changed, so every controller just needs to call Service.SetActivePage when they get switched to, and the Service can manage the backlog.

Where do you store the collection of pages? That should probably be in a Service too, and you can probably merge these things into the same service, since you are tracking the page history.

I hate the idea of rootScope, like I said, it's not pretty. But it can be useful in the worst situations. It's the first thing that came to mind, but I should have suggested a factory. It's more natural to Java devs like me. If you're goal is you still have to track state somehow, root or or a factory object would be a good choice.

I'm letting the fact that I hate the implementation of angular that a couple of devs did for my company's app. I wasn't involved in the decision (or dev) and I really wish I was. Because I would have veto'd it (or at least the way that they did it).

I'm not against angular at all. I like it actually. But the web devs that we had wrapped our entire app AND javascript within controllers causing major pain and conflicts with new controllers, etc. that we've had to write. That and we still have a heavy reliance on jQuery which just adds to the mess.

Those two devs are gone now (they were good, just not wise in the way they implemented angular) and I've moved all the rootscope methods to a factory where they should have been. But we have 1 module they defined and everything conficts if I want to use more than one controller on a page. :argh: I want to hire them back so I can fire them because gently caress they put us in a bad position that I can't easily fix / refactor.

geeves
Sep 16, 2004

Skandranon posted:

For the last month I've been working on refactoring a similarly poorly implemented Angular app. They used controllers like services, spawning up 10 of the same controller when they thought they were accessing the same one. However, it all magically worked because they ALSO created a hast table based global variable service that everything got put in, so the controllers ended up accessing the same variables from there, though I suspect this was more a coincidence.

How can you not use more than 1 controller per page? Do you mean you can't nest any other controllers in it?

I don't understand it yet because I'm still figuring things out.... but they made every page its own controller.

so:

<body data-ng-controller="${actionName}"> (we're based in struts) wraps everything else. The controllers interfere with each other causing a major JS error (what I don't have a complete understanding of), yet. The embedded controller doesn't "fire" or "init" at all and I have no idea why. If I use directives,it works,, but it doesn't answer why the controllers don't. And perhaps that's one of the shortcomings of the 1.x branch that may be better addressed in 2.x

geeves
Sep 16, 2004

Skandranon posted:

I'd break everything down into smaller parts until the 'super controller' had no actual code left in it.

This is really want I want to do. It's just not the easiest to sell in corporate environment because "everything works". My opinion (and agreed upon) is that the current implementation is completely wrong.


Everything they did was in an init or return block that was just a clusterfuck.

geeves
Sep 16, 2004

Bruegels Fuckbooks posted:

My company used to use Lotus Notes, and then the announcement went out that we were going to use gmail. It was great - we could use it on our phones, just use it on any web browser. It worked pretty well for 4 years.

Then they decided Gmail was too open.

Solution:

1. Instead of logging into gmail, you log into some external provider.
2. User needs client side certificate and activex control to log in, and can no longer go directly to gmail, but has to go through some weird website, which requires typing in the concatenation of your company id and employee id plus your password to log in.
3. You need to install a bunch of weird bullshit to get gmail on a phone to work but that's OK because you need authorization from someone director level or higher to get it on your phone.

It loving sucks. I can't figure out how to have Fiddler open and check my email at the same time, or get Gmail to work with loving google chrome.

That is loving insane. Was two-factor not an option with Gmail? For a company to be ISO-something-security compliant, you just need two factor and password changes every 3? months I believe. I've worked in places that required security clearances and even then there is nothing as insane as that.

Edit: Sounds like your company got a bunch of FUD as a sales pitch to buy just another layer of "protection" which is just another places where employee information is held by yet another company.

geeves
Sep 16, 2004

Lumpy posted:

So I was looking at some code and came across a bunch of stuff like this:

JavaScript code:
function poop () {
   
    if (someCondition) {
        blah();
        anotherThing();
     } else
        ;

    if (otherCondition) {
        ;
    } else
        oneLiner();

}
I'm at a loss as to why one would do that. I'm curious if anyone else has seen that and the reasoning behind it.

Let me guess, this is an NPM project...

geeves
Sep 16, 2004

vardyparty posted:

Semicolons or no semicolons?

Not using them looks cleaner and nicer like ruby or python code.

I had someone say this to me in an interview. Also about not using { } with if / else statements. He wasn't hired.

Strong Sauce posted:

Adding semicolons won't help someone in this case. Learning how ASI is implemented will.

code:
function a() {
  return
  { 
    b: 3;
  };
}

Yeah you're example is kind of tricky because to someone new to programming might not realize that an object is just an array of a map (key/value pair) so a comma would be used in that case (if there were more k/v pairs after).

quote:

The answer should be choose whatever works best for you.

If you're writing code just for you - do whatever you want. I personally think it's lazy and in poor practice not to use them. I've always been strict with semi-colons; I'm from a Java background, so it's just more natural to me.

In a team environment they should be enforced so there's less possible misinterpretation. At my company your code will not pass peer review. The time it can take to submit, reject, resubmit fixed code takes up more time than just using a semi-colon.

geeves
Sep 16, 2004

Portland Sucks posted:

I tried throwing

code:
<head>
    <script>
        function ajaxRequest() {
        	event.preventDefault();
	        $.ajax({
                    type: 'post',
                    url: 'insert.php',
                    data: $("#payment").serialize(),

                    success: function () {
                        return true;
                    }
                });
            };
    </script>
    <meta charset="UTF-8">
    <title>Buy this drat knife.</title>
</head>
but it just prevents my submit button from working at all?

What about something like:

code:
<head>
    <script>
        function ajaxRequest() {
        	var form = $("#payment");
	        $.ajax({
                    type: 'post',
                    url: 'insert.php',
                    data: form.serialize(),

                    success: function () {
                        form.submit();
                    }
                });
            };
    </script>
    <meta charset="UTF-8">
    <title>Buy this drat knife.</title>
</head>
Change <input type="submit"> to <button type="button" onclick="ajaxRequest()">Paypal!</button>

geeves
Sep 16, 2004

Portland Sucks posted:

Sorry to be a pest, but I'm back with this same problem that remains unresolved and is rapidly become a pain in the rear end. Any other JS/Ajax gods around here that can lend a hand?

My version worked. Try it yourself. You should get a few Alert dialogs then you'll be redirected to Paypal. http://plnkr.co/edit/Cpfsy5tn3gdhajTorcON

geeves
Sep 16, 2004

Wheany posted:

Is there an easy way of detecting when external images on SA fail to load?

I use https on the forums and I want to make a greasemonkey script that replaces images that failed to load (over http) with links that I can open in a new tab.

My first easy method, as always, is to use brure force and polling. Just check the images every few seconds and after some arbitrary timeout decide that it failed to load. But that's fragile as gently caress.

Not tested and probably could be a better solution, but something like:

code:
(function (window, document) {
    function getImages(images) {
        for (var j = 0; j < images.length; j++) {
            var img = new Image();
            img.onerror = imageError(img);
            img.src = images[j].src;
        }
    }

    function imageError(image) {
        console.error(image.src + " NOT FOUND");
    }


    function testImages() {
        var posts = document.getElementsByClassName("postbody");

        for (var i = 0; i < posts.length; i++) {
            var images = posts[i].getElementsByTagName("img");
            getImages(images);
        }
    }

    document.addEventListener("load", testImages, false);
}(window, document));
I already have an SA greasemonkey script that I use, so I'll test this more later dropping it into that and delving into the archives where there are lots of broken images.

geeves
Sep 16, 2004

Blinkz0rz posted:

Yeah, I should amend my comment to be:

"Be verbose, be explicit, be safe. Stop trying to do clever things. Clever things only make you feel smart. Everyone else hates you for them."

A company I worked for fired a couple of CMU JavaScript Bros for not adhering to our style guide. They had other issues too, but we were sick of denying their pull requests and having them break the build because it wouldn't pass JSLint, etc. They had other issues as well, mostly their attitude (and they were certain they were creating the new snapchat), but still it just carried over and dealing with them during code reviews, etc. became a nightmare because of it.

geeves
Sep 16, 2004

Because you have multiple return points which, IMHO, is bad code.

Add:

return advGuessMyNumber(input - M...

return advGuessMyNumber(Math.floor

You're better off with something like

https://jsfiddle.net/9h7dqgzk/2/

geeves fucked around with this message at 04:04 on Nov 12, 2016

geeves
Sep 16, 2004

ddiddles posted:

One of the best courses I took (well, still taking) was Anthony Alicea's JS Udemy course, he takes the time to explain how the JS engine works, which sheds a lot of light on how the actual syntax works.

https://www.udemy.com/understand-javascript/learn/v4/

It's $20 right now, and well worth it in my opinion.

Also, teamtreehouse.com has a pretty extensive JavaScript course as well.

The first 3.5 hours on on youtube (Alicea's actual youtube account it seems) if you want to take more of peek to see if it's worth the $20.

https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

geeves
Sep 16, 2004

The Fool posted:

I made a terrible thing last night.
code:
var express = require('express');
var exec = require('child_process').exec;

var app = express();

var port = 3000;

app.get('/:command/*?', function (req, res) {
  var command = "powershell.exe " + req.params.command;
  var args = req.params[0].replace(/\//i, ' ');
  command += " " + args;

  exec(command, function(error, stdout, stderr) {
    var result = "<h4>" + command + "</h4>";
    if (error) {
      result += error;
    } else {
      result += stdout;
    }
    res.send("<pre>" + result + "</pre>");
  });
});

app.listen(port, function () {
  console.log('Listening on port: ' + port);
});
For the sake of argument, what are some things that can be done to make this bit of code not a giant black hole of security risks?

Obvious ones to me:
Don't allow arbitrary execution of commands, only specific ones.
Make sure the node process is running as a service account with only the desired permissions.
Require authentication.

What else is there?

Roadie posted:

Nothing. Anything that lets people run arbitrary command-line code will gently caress you.

What do you actually want to do with this?

Exactly.

#1 in java script: The Bad Parts or "DON'T loving DO THIS" - exec() (I realize this may be different in node, than in the browser - but until I know better/....)

If you are running a .exe (or .sh) make sure it's something airtight that you have also written yourself and you know exactly what you will be executing.

If you have to write sketchy code like this perhaps you should be handing off to another service / queuing system that can handle it properly.

Not to enable you (I don't know what powershell.exe does) at the very least, you should be checking if req.params.command are in fact valid and what you want to allow (for example, if it does CRUD and you only want Read, make sure the params are Read params - otherwise 403 / 500 that response). Treat everything like you would SQL injection and don't pass them blindly.

But as Roadie said, "No".

geeves
Sep 16, 2004

necrotic posted:

https://www.npmjs.com/package/money-math

But don't do money related math in JS unless it's like some dumb estimate.

yeah. Just don't. when I had to do money-like numbers, I just sent it to the server instead. Much safer and not much longer.

geeves
Sep 16, 2004

Bruegels Fuckbooks posted:

I was thinking about replying like this but then I remembered that node.js is a thing, so it's conceivable that node.js could be used by like banking sites or some poo poo.

The next solo Superman movie will be a remake of 3 and have Kevin hart as the villain working with Lex. He won't be collecting simple half pennies from banks. Who knows what he'll exploit with node.js.

I highly doubt any financial institution is using node.js for any calculation.

geeves
Sep 16, 2004

Sab669 posted:

(Posting from my phone at work, sorry for poor formatting.)

TL:DRI'm looking for a JavaScript library to help iterate over HTML elements. Any suggestions?

I had to do something very similar to this in C# last week. I used HTML Agility Pack for this and it was fairly easy to use once I got the hang of it. For that project, I was iterating over a table and pulling out the InnerText; fairly simple. This time around it's a bit more complicated.


I've got a table within a div, within a table, within yet another table. So we're 3 tables deep. Thankfully (surprisingly) the div containing the table I care about has an ID so it's easy to find.

This final table has N rows and 4 columns. The number of rows is generated dynamically at run time to include a number of input controls to act as search parameters for the user.

I'm trying to basically combine the plain text in the "odd numbered" <TD> elements, then get the value of the control within the "even numbered" <TD> elements.

Now that I've typed it out it doesn't sound too hard but I can't figure out how to do it with just plain JS. I tried using document.GetElementById("myDivID"), then use getElementsByTagName to get the table, but this doesn't give me its child nodes (unsurprisingly). I tried passing "input" to that as well, but I'm getting far more controls in that collection than I can see on the page, which might be due to the third-party controls we use.

JavaScript is a little weird with tables and childNodes. Technically each table has a <tbody> and <thead> I believe, even if you do not declare them. Best to go after them explicitly: (Edit: also there are technically 9 childNodes of <tr> in this example, not 4)

https://jsfiddle.net/createanaccount/z56yesz0/

geeves fucked around with this message at 14:47 on Feb 7, 2017

geeves
Sep 16, 2004

There Will Be Penalty posted:

Use table_element.querySelector("> tbody > tr > td:nth-child(even)")

(I think that would be the correct selector, I know it would work with jQuery.)

This is much better. I keep forgetting that querySelector exists half the time.

Adbot
ADBOT LOVES YOU

geeves
Sep 16, 2004

Dominoes posted:

The JS economy feels confusing if you don't use Node, since most guides assume you're using it.

Is there a well-written guide on how to get started with Node / Bower? More so on the Bower end as we don't use node.js.

Or is there something other than Bower? Or is this a Grunt / webpack thing to combine all of our JS dependencies? There's 50 tools out there and looking at the JS community it's maddening coming from a community that basically has 3 solid, well developed tools for building an application (Gradle, Maven and Ant).

The dev who introduced us to all of this a couple of years ago just did a really piss poor job of it because all he really wanted was grunt watch. He basically would install packages via bower then just copy them into our repository instead of actually using its process. We're well behind the times and I've been knee deep in moderizing our Java build process and I want to continue this on the front end side of things.

You're correct about every React / Redux just making assumptions and not at least writing, first you need to install X - follow these instructions on this site or something.

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