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
go play outside Skyler
Nov 7, 2005


LifeLynx posted:

code:
<span className="item-name" onClick={() => { ClickHandler() } }>{object.name}</span>

function ClickHandler() {
	this.style.color = 'red'
}
This gives me a "TypeError: Cannot read property 'style' of null" error. What can I put in the ClickHandler function that will tell it "Hey you know the element that was clicked on that triggered this function? Change it to red."?

Also since I'm doing this in React, for some reason putting that anonymous function in the onClick of the span tag makes the whole thing re-render as soon as it loads. I noticed that if I just have a function in there, it will load as soon as the page first renders. Seems odd.

Arrow notation functions in JS keep the this context. As such, this will be defined as whatever it was in the render function, which probably isn't what you want.

Directly pass the ClickHandler function (without parentheses) and you'll be fine

code:
<span className="item-name" onClick={ ClickHandler }>{object.name}</span>

function ClickHandler() {
	this.style.color = 'red'
}

Adbot
ADBOT LOVES YOU

go play outside Skyler
Nov 7, 2005


Another way to do it would be with a parameter-object but I guess in your case you couldn't prevent someone from calling your function with both a GUID and an ID.

go play outside Skyler
Nov 7, 2005


D34THROW posted:

Hopefully the right place to ask this:

I did some digging into an online cut optimizer out of curiosity, and I pulled this bit of code out of it. Is it JSON or something I haven't learned about Javascript yet?

code:
var CutList = (function() {
	function maxSize() {
		var arr = s.stock_array;
		var high = 0;
		for(var i = 0, len = arr.length; i < len; i++){
			high = (high < arr[i].size) ? arr[i].size : high;
		}
		return high;
	}
	var s, cl = {
		settings: {
			cut_array:      [],
			stock_array:    [],
			cut_list:       [],
			stock_list:     [],
			kerf:           1.5,
			stock:          8000,
			cut_ul:		$('#cut-list'),
			stock_ul:	$('#stock-list'),
			cut_length:	$('#cut-form input[name*="length"]'),
			cut_quantity:	$('#cut-form input[name*="quantity"]'),
			stock_length:	$('#stock-form input[name*="length"]'),
			stock_quantity:	$('#stock-form input[name*="quantity"]'),
			name_input:	$('#settings-form input[name*="cutlist-name"]'),
			stock_input:	$('#settings-form input[name*="stock-length"]'),
			kerf_input:	$('#settings-form input[name*="kerf"]')
		},
		init: function() {
			s = this.settings;
			this.bindUI();
			this.renderUI();
		},

It's plain old javascript with some jQuery in it.

These
code:
$('#settings-form input[name*="kerf"]')
Are called selectors. It means 'Give me a DOM element which matched: an HTML input with a name containing "kerf" inside an HTML element with an ID of "settings-form"'. These selectors are roughly the same as the ones used in CSS.

jQuery creates a function called $ in the global scope to make it easier to type.

e: nowadays, people are using jQuery less and less, and you can pretty much replace this function with document.querySelectorAll("..."). However, do note that the jQuery $ function returns a jQuery object so you can chain calls. document.querySelectorAll does not.

cutList is probably a self-calling anonymous function. Hard to say without the last few lines of it. Usually self-calling anonymous functions are used to not pollute the global scope with functions that don't need to be used elsewhere. The syntax is like this

code:
(function () {
function thisFunctionWillNotBeAvailableInTheGlobalScope(){
// stuff
}
})()

go play outside Skyler fucked around with this message at 19:17 on Mar 23, 2020

go play outside Skyler
Nov 7, 2005


D34THROW posted:

I didn't realize this rabbit hole went so deep :v: I'm barely scratching the surface here, it took me an hour yesterday to figure out why Firefox was throwing an error on .valueOf().



code:
settings: {
			cut_array:      [],
			...
			kerf_input:	$('#settings-form input[name*="kerf"]')
		},
Direction change: I come from a VBA-as-a-hobby background, so I'm interpreting settings:{...} here as a collection, where cut_array...kerf_input are key/value pairs - Javascript objects, based on what W3Schools says, and JSON basically bakes these into a file so it can be more easily worked with. I'd say a class object, but there's no methods to a JS object.

This is indeed an associative array, also called just an "object". In JavaScript, you can declare new, complex tree objects using a JSON-like notation (it's not exactly the same but close enough for what you care about right now).

An object in JavaScript can have functions, other objects. It's an associative array of whatever you want.

Not exactly sure about my terminology here, maybe someone can chime in. I've been doing JS for so long that I'm basically not thinking about these things anymore.

e: something I make EVERYONE who works in my team read is java script: The Good Parts. The book is relatively short and you can get it as an e-book for a fistful of dollars. Definitely read it if you want to avoid common pitfalls and write good code. Nowadays it's a bit dated in the solutions it offers, what with the new EcmaScript standards, but the gist of it is still very good.

go play outside Skyler fucked around with this message at 19:46 on Mar 23, 2020

go play outside Skyler
Nov 7, 2005


That's weird. My only explanation here would be that you have some additional Express middleware that's causing this issue somewhere. From what I've seen on SO, try listing all your routes and check which middleware could be running and try taking them out one-by-one until it works. Here's apparently how you can list the routes (which should include middleware)

code:
// express 3.x
app.routes

// express 4.x
// Applications - built with express()
app._router.stack

// Routers - built with express.Router()
router.stack
Haven't tested this but it feels like the most probable issue.

go play outside Skyler
Nov 7, 2005


Better to make it an npm package with 5 dependencies

go play outside Skyler
Nov 7, 2005


OtspIII posted:

I'm very close to being done adding accounts to my website, but the one remaining step is pretty intimidating--making sure that I'm sending passwords securely from the client to the server. Right now in my dev environment I'm just sending username/password in the body of my POSTs, but that seems like something that should extremely never go live. I've found a few ways of handling things, but am having trouble understanding the context of a lot of what I'm finding. Can I get a sanity check on what's good practice from everyone?

For context: React frontend, Express backend, passport-local for authentication, hosted on AWS. User accounts, email verification, password change, and password reset are all effectively in and working (if there are any other features that really need to be in before launch, I'd appreciate the heads up).

The main thing I'm going to be doing is getting my HTTPS set up. I already have a SSL certificate, but have struggled a bit getting it set up and working in the past--the AWS part is making it hard to visualize exactly where or how it should be done. The research I've done seems to be implying that I need a Load Balancer set up to install it on? I honestly can't tell if that's true or if it's just the one way I was able to find information on. I feel like I'm making things more complex than they need to be, but it also sounds like a Load Balancer might be a good thing to have in general, given that they sound like they help with things like DDoS attacks and I've already had some friction with 4chan. But does a LB even do anything for a relatively small single-server website like mine? I'm honestly still pretty lost in the woods when it comes to server architecture stuff

The other thing I've found that seems more compatible with HTTP transmissions is embedding login data within the authorization header rather than the body, but I have had zero luck getting this to be compatible with passport-local, to the point where I'm wondering if I'm somehow missing the point of how one or the other of them are even meant to be used. Am I missing something?

As a side note, I've been getting a ton of angry messages in the console about how I have password info not held within a form for all this. I've been hand-rolling my server calls, since that honestly seems easier in React than normal form use, but am I missing out on some behind-the-scenes security precautions or something by not using them?

My current plan is to try to set up both my SSL certificate and also get the Auth Header stuff working--does that seem like sufficient safety for password transmission? Or would even just one be enough?

Unless I'm completely out of the loop, you should be fine with just SSL and I honestly don't see why you would need a load balancer for a single server setup. I know some sites hash the password field before sending it out but that has always seemed overkill to me.

For SSL, just use Let's Encrypt. It can fetch a certificate for you automatically and renews them every 3 months. And did I mention it's free and supported by all major browsers without any security warning?

If you really think you need DDoS protection, go with something like Cloudflare. It's super easy to set up though you should check if their free tier is enough for you.

I don't think there's any security implications with using a password field outside a form, except maybe some obscure exploit I'm not aware about, but it's always good practice to wrap all your fields in forms. This enables default behavior that most people are used to (like enter key to submit, better tabbing between fields, better autocomplete, etc). Probably also better for accessibility.

You can always just override the onSubmit event of your form, call e.preventDefault() and return false to make sure the browser doesn't navigate away from the page and that you keep the context.

go play outside Skyler
Nov 7, 2005


SirPablo posted:

I'm having issues with CORS, mainly I don't understand it well. Is there really no way to just pull the content of a php script that loads in the browser window fine within a page's JS? Imagine that website.com/data.php returned the text "12345", is the no way to really capture that within a js function?

Unless website.com explicitly allows it, then no, not anymore. If you own website.com, just add the Access-Control-Allow-Origin: * header to the response and you'll be fine.

Another solution, if you really need to scrape something on a server you don't have control of, is to use a proxy server which does the requests for you.

CORS is there to protect people from attacks like logging you in to Facebook from another website. Because your browser has your session information for all websites you visit, the w3c decided to limit the attack surface by blocking all cross-domain requests. This is actually a good thing.

If you're just testing out something for yourself, you can also just disable web security in chrome by starting it with the --disable-web-security command line argument.

go play outside Skyler
Nov 7, 2005


MrMoo posted:

Like a heathen I just symlink node_modules across projects to cut on disk space, :lol:

that sounds like a terrible idea

go play outside Skyler
Nov 7, 2005


Just going to state the obvious in case it's been missed. If you're actually displaying tabular data, like a list or something, then you should just use plain old tables.

go play outside Skyler
Nov 7, 2005


Do you really need a plug-in for that? Never heard of vimejs, but if you roll your own player, you can completely hide controls, and just draw your own scrubber based on start and end time. Calculations to know the percentage of playback based on video.currentTime is trivial.

go play outside Skyler
Nov 7, 2005


fsif posted:

Gotcha. Yeah, obviously you know your project better than I do so take what I say with whatever appropriate amount of salt.

BUT I'd just caution that the solution of "rolling your own" scrubber might not be that easy. There's no native way to do it with Vime as far as I can tell. If your team is comfortable ditching Vime and want to use a low-level <video> tag to program it, there are still a lot of responsive and accessibility hurdles you'll want to make sure to clear. Also don't know if your chunking solution is in some ways dependent on Vime.

Should also note that in my (not particularly robust, but still existent!) experience with trying to pause a longer video at a certain spot to bring about an artificial end, the native JavaScript events weren't that precise. The clip would stop within a 1+ second range.

So you know, totally unsolicited and underinformed opinion here, but in the abstract a project like this could end up being one where you end up spending more developers and technical debt than you do just running the servers, heh.

Not to derail, but I think what you experienced might be due to keyframes. Not sure you can just seek to any random position in the video like that, it might snap to h264 keyframes.

Come to think about it, I'd also suggest generating the clips on the server-side!

go play outside Skyler
Nov 7, 2005


Comedy option: deliver video video an mjpeg stream

go play outside Skyler
Nov 7, 2005


roomforthetuna posted:

Passing a callback down gives you a way to have the child call the parent, it doesn't give you a way to have the parent call the child.

To get the ability to call a function on a child you can pass a callback down that contains a callback that the child immediately calls to register a callback with the parent so the parent can call something on the child if the parent keeps a copy of that thing. Obviously that's a fine and appropriate approach that isn't incredibly annoying at all.

Why would you need to call a function on a child? Change its property, get it to redraw, let react handle DOM updates. If your components are complicated enough that you need to call methods on them, they are too complex and you should probably break them down.

The only reason I see for calling a method on a child component is to mess with the DOM and that's not something you should be doing in react.

go play outside Skyler
Nov 7, 2005


I have never encountered a case where a child component's rendering size affected parent components in a way that couldn't be solved with good CSS rules.

I could tell you to "lol learn CSS" but a more constructive suggestion I would have, would be to create a withLayoutUpdate() High-Order-Component, that adds a new "didDraw" callback property to every component using this. When your child component is finished rendering, call this callback and have your parent components listen on that event and redraw accordingly, I guess.

Not sure of the specifics of how to implement that, but it seems like a way to do it. I understand this feels like a limitation to React and if I was in your case I'd be feeling like I'm just trying to find ways around React's architecture as well. But to me this is a small drawback in a sea of advantages the "framework" has, including but not limited to writing super simple layout code.

Mind you, this is coming from a guy who spent years writing UI's in WinForms, jQuery, Cocoa (interface builder et. al) and WPF. I've seen it all, and I still cringe every time I look at the amount of loving boilerplate and complexity needed to do simple poo poo with WPF when I compare it to React. I still very much enjoy how React is extremely down-to-earth and simple to understand.

go play outside Skyler
Nov 7, 2005


I'm not sure an empty tag is valid syntax. If you need a container element that does nothing, use a <React.Container>

go play outside Skyler
Nov 7, 2005



Wow, I think that's new. Guess that's what happens when you don't touch web dev for a year 🤷‍♂️

go play outside Skyler
Nov 7, 2005


fuf posted:

why does everyone write functions like this now:

code:
const handleChange = (e) => {
    updateValue(e.target.value)
 }
instead of like this:
code:
function HandleChange(e){
  updateValue(e.target.value)
}
?

if you put HandleChange in a callback context, "this" will refer to the callback context with version 2. With version 1, "this" will be implicitly captured and refer to whatever it was when the function was defined.

go play outside Skyler
Nov 7, 2005


Might not be a popular opinion but as someone who's done a lot of everything web, a lot of embedded, a lot of Java, Kotlin and Swift, I'll say this: in 2022 it doesn't really matter if you barely know how HTML and CSS work anymore. Nowadays there's so much poo poo going on between the code you write and what's delivered to the browser, you'll be using a build system that handles all that stuff for you.

Unless you're supposed to be the one initiating the project and building it from scratch, I'd just start learning React, Vue or Angular + TypeScript and worry about the details later. React in my opinion is the best, least opinionated framework, but the most important is to learn whatever your company plans to be using.

Because you're not going to be the one starting the project from scratch, are you? ...???

go play outside Skyler
Nov 7, 2005


CarrKnight posted:

Right, thanks for comments.

To be fair, I am not going to build any very complicated web-app; rather what I really need to produce is a "one-page" app where users play a bit with some sliders for inputs, the "javascript application" I need to write crunch those numbers into some output and then plots some neat graphs.
It's basically a "run stat analysis in browser" kind of app with no connection to either data-bases or any other server. The need for JS (or typescript or whatever) is just because we want a user to run analysis without having to download an excel spreadsheet or, god forbid, a desktop program.

Given this use-case, do you guys still think the right approach is to start with React?

100%, but start with something that does all the boilerplate for you like create-react-app. Enjoy the ease of development of doing npm start during development and learn about how to build a release version of your app with web pack and upload all that poo poo to a server.

go play outside Skyler
Nov 7, 2005


Nolgthorn posted:

Wait till you do things the right way and figure out why they're also wrong. All solutions point back to vanilla js, so then you do that and realize why React is probably the right way. It's a never ending circle.

Every time I try to start a project without react I end up with a million calls to document.createElement and sometimes I feel that all JS needs is a standardized simple template system.

go play outside Skyler
Nov 7, 2005


roomforthetuna posted:

Man, if they'd made react *without* the state management system then there might be a framework that I don't hate and wish death upon.

but that's just JSX, which was my point: it should be part of javascript, and i shouldn't need webpack to use it

go play outside Skyler
Nov 7, 2005


i went through the pain of getting an electron+ts+import app running and also had some problems with debug working but release failing. it took me a whole loving day of fiddling with webpack and i hope i never have to do it again

Adbot
ADBOT LOVES YOU

go play outside Skyler
Nov 7, 2005


The Merkinman posted:

So because a time zone isn't defined, it's using a time zone where September 11, 2001 was a Monday? OK :confused:

No, it's because you are calling the function from a time zone where it was still monday september 10th in UTC time.

As another poster said, don't use JS Date object to parse a date. It's better to use something like moment or whatever the new hotness is.

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