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
Xenoveritas
May 9, 2010
Dinosaur Gum
Well, yeah, that's because JavaScript doesn't natively do modules, so Require.js is a hack to create something like them. It's a decent solution to a problem that JavaScript flat-out doesn't attempt to solve on its own, and it works fairly well, if you ignore the part where the object coming out of a require.js module can be literally anything.

Adbot
ADBOT LOVES YOU

Pollyanna
Mar 5, 2005

Milk's on them.


I much prefer Browserify. It's a lot more obvious about what it's trying to do, and the Node-ish module syntax is better than the AMD (define([], function{}){}).call(this) mess.

v Purely for demonstration purposes!

Pollyanna fucked around with this message at 19:20 on Nov 25, 2014

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

Pollyanna posted:

(define([], function{}){}).call(this)

Well yeah if you right it that way it will be a mess (of not working).

Kobayashi
Aug 13, 2004

by Nyc_Tattoo
I was looking at some code the other day, and ran across a check in the constructor that I do not understand:

code:
function ClassName(options) {
	if (!(this instanceof ClassName)) {
		return new ClassName(options);
	}
	// rest of the constructor
}
It looks like this is checking to make sure the context isn't hosed up, and fixing it if it is. I'm not sure how the conditional would ever be satisfied, though, or how calling the same constructor fixes anything. Can someone explain what this is all about?

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

Kobayashi posted:

I was looking at some code the other day, and ran across a check in the constructor that I do not understand:

code:
function ClassName(options) {
	if (!(this instanceof ClassName)) {
		return new ClassName(options);
	}
	// rest of the constructor
}
It looks like this is checking to make sure the context isn't hosed up, and fixing it if it is. I'm not sure how the conditional would ever be satisfied, though, or how calling the same constructor fixes anything. Can someone explain what this is all about?

Because constructors in Javascript are just functions you can call ClassName({}) instead of new ClassName({}), which would cause some issues. This check basically watches for the first case and forces the actually-valid second case.

Kobayashi
Aug 13, 2004

by Nyc_Tattoo

necrotic posted:

Because constructors in Javascript are just functions you can call ClassName({}) instead of new ClassName({}), which would cause some issues. This check basically watches for the first case and forces the actually-valid second case.

Thanks, that makes sense. I just can't seem to break out of the traditional OO mindset.

Storgar
Oct 31, 2011
I ended up going down a rabbit hole while googling and I heard about something called "Progressive Enhancement". I'm trying to wrap my head around how this applies to many very complex websites these days.

For instance, let's say I use a REST api to load posts in a blog. Progressive Enhancement says that it should still contain all the same content with javascript support. But the posts are loaded with an ajax call. How would you get around this? Make the call server-side and then populate the page once before serving it? Seems like it adds a ton of overhead to be worth it...?

Is there a resource I could read more about this?

EVGA Longoria
Dec 25, 2005

Let's go exploring!

Storgar posted:

I ended up going down a rabbit hole while googling and I heard about something called "Progressive Enhancement". I'm trying to wrap my head around how this applies to many very complex websites these days.

For instance, let's say I use a REST api to load posts in a blog. Progressive Enhancement says that it should still contain all the same content with javascript support. But the posts are loaded with an ajax call. How would you get around this? Make the call server-side and then populate the page once before serving it? Seems like it adds a ton of overhead to be worth it...?

Is there a resource I could read more about this?

Why is your blog loading content with an Ajax call?

Progressive enhancement is just another term for graceful degradation. If a user has javascript turned off, they should still be able to use your site, just slightly differently.

Storgar
Oct 31, 2011

EVGA Longoria posted:

Why is your blog loading content with an Ajax call?

Progressive enhancement is just another term for graceful degradation. If a user has javascript turned off, they should still be able to use your site, just slightly differently.

I dunno... Just seems like a natural way of doing it to me? I have a REST api where I can get a list of posts. I want to make that the only method of obtaining such objects (rather than a having a second way of populating the page with a server-side function outside the REST api). How do people usually do it?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Storgar posted:

I dunno... Just seems like a natural way of doing it to me? I have a REST api where I can get a list of posts. I want to make that the only method of obtaining such objects (rather than a having a second way of populating the page with a server-side function outside the REST api). How do people usually do it?

Seems fine to me.

Also, what percentage of users even disable javascript? Is it even worth the effort for graceful degradation these days?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

fletcher posted:

Seems fine to me.

Also, what percentage of users even disable javascript? Is it even worth the effort for graceful degradation these days?

Search engines, for one. Good job making your content completely unfindable if it only appears via ajax.

down with slavery
Dec 23, 2013
STOP QUOTING MY POSTS SO PEOPLE THAT AREN'T IDIOTS DON'T HAVE TO READ MY FUCKING TERRIBLE OPINIONS THANKS

Jabor posted:

Search engines, for one. Good job making your content completely unfindable if it only appears via ajax.

https://developers.google.com/webmasters/ajax-crawling/docs/learn-more for those interested in learning more

Storgar
Oct 31, 2011
I read somewhere it might be less than a single percentage of the browser market or something. I don't think it's really a problem, but I was just curious how someone would go about doing this.

I haven't been keeping up with mobile devices, but I wouldn't be surprised if a larger percentage of mobile users didn't have javascript. I just want to see what "people in the field" do.

lunar detritus
May 6, 2009


Storgar posted:

I read somewhere it might be less than a single percentage of the browser market or something. I don't think it's really a problem, but I was just curious how someone would go about doing this.

There are some weirdos that use NoScript to block everything but they suck and they can enjoy the blank pages I'm serving them.

qntm
Jun 17, 2009

fletcher posted:

Seems fine to me.

Also, what percentage of users even disable javascript? Is it even worth the effort for graceful degradation these days?

Depends who uses your website:

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

a slime
Apr 11, 2005

Javascript newbie here, trying to wrap my head around some basic Angular stuff. I have two directives, both elements, as such:

code:
<item-selector></item-selector>
<item-display></item-display>
When the user selects something from item-selector, I'd like that item to be shown in item-display. I figured I would assign an id attribute to item-display, and add an attribute to item-selector pointing it to that id. Then somehow the controller for item-selector would call a "setItem" function on the controller for item-display. Somehow this doesn't seem idiomatic, and I don't know how to get at an element's controller from its id anyways.

What idioms am I looking for here? Can someone point me in the right direction?

EVGA Longoria
Dec 25, 2005

Let's go exploring!

Storgar posted:

I dunno... Just seems like a natural way of doing it to me? I have a REST api where I can get a list of posts. I want to make that the only method of obtaining such objects (rather than a having a second way of populating the page with a server-side function outside the REST api). How do people usually do it?

That's some ridiculous over engineering. What do you gain by using a RESTful API for a static site like a blog?

We're using that at work and it's caused us no end of problems. I'm currently ripping it out of our code and replacing it with simple server-side templates -- it's massively improving performance, and simplifying a lot of other interactions (like no need to pre-render for SEO).

a slime posted:

Javascript newbie here, trying to wrap my head around some basic Angular stuff. I have two directives, both elements, as such:

code:
<item-selector></item-selector>
<item-display></item-display>
When the user selects something from item-selector, I'd like that item to be shown in item-display. I figured I would assign an id attribute to item-display, and add an attribute to item-selector pointing it to that id. Then somehow the controller for item-selector would call a "setItem" function on the controller for item-display. Somehow this doesn't seem idiomatic, and I don't know how to get at an element's controller from its id anyways.

What idioms am I looking for here? Can someone point me in the right direction?

Generally, my preference for communication between parts of AngularJS is a Service. Just return a simple object, which is then shared amongst the directives. It can even be manipulated from the Controller, if there's some reason for that.

The other way to communicate between Directives is be using Events. When you select an item in the item-sector, emit an event. Had item display listen for this event, and react to it. It's not a bad way, but depending on how your directives are situated in your controllers, you might need to broadcast from the root scope or otherwise, which can be a bit messy.

leftist heap
Feb 28, 2013

Fun Shoe

a slime posted:

Javascript newbie here, trying to wrap my head around some basic Angular stuff. I have two directives, both elements, as such:

code:
<item-selector></item-selector>
<item-display></item-display>
When the user selects something from item-selector, I'd like that item to be shown in item-display. I figured I would assign an id attribute to item-display, and add an attribute to item-selector pointing it to that id. Then somehow the controller for item-selector would call a "setItem" function on the controller for item-display. Somehow this doesn't seem idiomatic, and I don't know how to get at an element's controller from its id anyways.

What idioms am I looking for here? Can someone point me in the right direction?

I'm not sure you'll need to jump through attribute those attribute hoops. There are a lot of ways to do this, really. You can bind the selector/display state to an object in shared scope (for example if the item ID or the item itself is within scope), you can do like EVGA Longoria said and use events or a service to share the state (I don't think I'd do this unless that state was meant to be shared or propagated to the entire application) or you can create a parent controller for both directives that does most of the state management. I find using a parent controller the simplest solution for the most part.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Kobayashi posted:

I just can't seem to break out of the traditional OO mindset.

I've just read Principles of Object Oriented Javascript and it's done a great job clearing the fog from my reading/writing of js. This very short book is meant exactly for people who have written the sentence I have quoted.

Storgar
Oct 31, 2011

EVGA Longoria posted:

That's some ridiculous over engineering. What do you gain by using a RESTful API for a static site like a blog?

We're using that at work and it's caused us no end of problems. I'm currently ripping it out of our code and replacing it with simple server-side templates -- it's massively improving performance, and simplifying a lot of other interactions (like no need to pre-render for SEO).

What if I want to do things like filter posts by topic, rearrange them, or reload posts without refreshing after publishing a new post? I might want to do other, more complicated things and I'm just using a blog as a learning example.

It satisfies my OCD to know that I can separate my website into a layer that does nothing but serve JSON strings, and then another layer that uses a lot of javascript to create a front end using API calls... I just want to know if there is a way to have my cake and eat it too.

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

Storgar posted:

What if I want to do things like filter posts by topic, rearrange them, or reload posts without refreshing after publishing a new post? I might want to do other, more complicated things and I'm just using a blog as a learning example.

All of those can be done without requiring javascript to even function as a simple blog. Its great if you're using it as a bed for learning, but a blog is one of the simplest things to build with both javascript and non-javascript users in mind. Use it as a learning bed for not just all of those amazing javascript features, but how to gracefully degrade at the same time.

EVGA Longoria
Dec 25, 2005

Let's go exploring!

Storgar posted:

What if I want to do things like filter posts by topic, rearrange them, or reload posts without refreshing after publishing a new post?

Well, kudos, you're over engineering your site to avoid a refresh.

Considering modern caching and compressing, refreshes aren't a big deal. You're cutting out a portion of your user base and requiring pre-rendering for Google.

Storgar posted:

I might want to do other, more complicated things and I'm just using a blog as a learning example.

It satisfies my OCD to know that I can separate my website into a layer that does nothing but serve JSON strings, and then another layer that uses a lot of javascript to create a front end using API calls... I just want to know if there is a way to have my cake and eat it too.

Yes, there are tons of great purposes for this. Single Page Apps certainly have their purpose, and I'm not against them. I use quite a few. But pick the right solution to the right problem. Blogs don't need to be API based, and I guarantee you that if you're making a blog in production that does this, you'll regret it.

Progressive enhancement is based on a certain basic level of functionality and content. You'd need to have server-side templates rendering with your content to start, and the filtering options having basic links that would then get overridden if Javascript is enabled. You can't have a blank page that depends 100% on Javascript and have it degrade in other cases.

Storgar
Oct 31, 2011

EVGA Longoria posted:

Well, kudos, you're over engineering your site to avoid a refresh.

I'm not trying to avoid a refresh for performance reasons, I want the user to see new content fade into view.

EVGA Longoria posted:

Progressive enhancement is based on a certain basic level of functionality and content. You'd need to have server-side templates rendering with your content to start, and the filtering options having basic links that would then get overridden if Javascript is enabled. You can't have a blank page that depends 100% on Javascript and have it degrade in other cases.

Thanks, this is pretty clear. I'll have to think about my design some more.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Simple html (+css) pages are pretty rad for document-like sites. They work fast (unless you go crazy with transitions and such) and are indexable by search engines.

If you want to add some kind ajax fetching for more posts on top of that, sure. But my request is that instead of making your page "infinite scroll", use pages, because my browser will crash when I'm reading "page 20" of your blog and then when I restart the browser I'm staring at the first page again. Then I will close the tab because gently caress scrolling down 20 "pages" again, waiting for posts to get fetched and "fade in" after a screenful.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Sites that can enhance on top of a static load, rather than relying on JavaScript for every single feature, are far more robust and accessible. I think one day we'll have a reliable way to do SPA style functionality whilst having a reliable page load for slow connections, but we ain't there yet for most dev teams. At least, we don't have a reliable methodology/framework for doing it yet.

For sites that have pages, permalinks and whatnot, JavaScript is progressive enhancement. Write semantic HTML that is accessible and usable without JavaScript. Then come in and hook the links and other functionality with your fancy poo poo. You get your ajax for the good browsers and connections, but everything's still good if the JavaScript is delayed for whatever reason or its turned off.

Storgar
Oct 31, 2011
Ok :negative:

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
For what's its worth I think that some day is going to be moving all templating to a small node server or something. Then you would have essentially shared JavaScript that either renders on the client using JSON supplied by the API, or JSON delivered to the server side JavaScript, that then renders the page.

The problem is this isn't really a practical well defined workflow at present, so it really just makes sense to lay the JQuery over the top of standard sites, were good at that. We've done it for long enough, and its reasonably predictable.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Maluco Marinero posted:

For what's its worth I think that some day is going to be moving all templating to a small node server or something. Then you would have essentially shared JavaScript that either renders on the client using JSON supplied by the API, or JSON delivered to the server side JavaScript, that then renders the page.

There are large production sites that do this with React now, it can work quite well.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Subjunctive posted:

There are large production sites that do this with React now, it can work quite well.

Yeah, I'm aware. I more mean that there's not really a framework out there for someone to say, I'm gonna build a blog like that, and have an easy time of it.

I think I'm the future it'll start to become the default, but its still specific to needs for the moment.

Hanpan
Dec 5, 2004

I'm trying to research whether to go SPA (Angular) or Hybrid (Web Components / Polymer) for a dashboard project I am working on. Is there a general set of rules for deciding when an SPA is overkill or not? Does it boil down to personal preference?

Thermopyle
Jul 1, 2003

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

Hanpan posted:

I'm trying to research whether to go SPA (Angular) or Hybrid (Web Components / Polymer) for a dashboard project I am working on. Is there a general set of rules for deciding when an SPA is overkill or not? Does it boil down to personal preference?

A single page app isn't really overkill for anything but really, really basic stuff. I mean, it's not super complicated or anything.

One of the deciding factors should be if you need the page content to be search engine indexable. I guess it's easier to do that when you're not doing a single page app.

Hanpan
Dec 5, 2004

Thermopyle posted:

A single page app isn't really overkill for anything but really, really basic stuff. I mean, it's not super complicated or anything.

One of the deciding factors should be if you need the page content to be search engine indexable. I guess it's easier to do that when you're not doing a single page app.

No need to be indexable. I guess the cons of an SPA is setting up the production and deployment processes although once you've done that a few times it isn't such a big deal. Hmm.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Having a scoping issue. I'd like to attach a parametrized event to a bunch of divs, but the parameter is failing to 'stick' on each div. Check out this fiddle. Clicking the divs alerts '2', since that's the current value of i. I want div0 to alert '0', and div1 to alert '1'.

I think that what I 'want' to be doing here is to attach an 'instantiated' function object to each div, but I'm not immediately sure how to do this.

edit: This works, but is it a horror?

JavaScript code:
$(function(){
    var i;
    for (i=0; i<2; i++){
        $('#div'+i).click(new Function("alert("+i+")"));
    }
});

Newf fucked around with this message at 14:37 on Dec 2, 2014

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Newf posted:

Having a scoping issue. I'd like to attach a parametrized event to a bunch of divs, but the parameter is failing to 'stick' on each div. Check out this fiddle. Clicking the divs alerts '2', since that's the current value of i. I want div0 to alert '0', and div1 to alert '1'.

I think that what I 'want' to be doing here is to attach an 'instantiated' function object to each div, but I'm not immediately sure how to do this.

edit: This works, but is it a horror?

JavaScript code:
$(function(){
    var i;
    for (i=0; i<2; i++){
        $('#div'+i).click(new Function("alert("+i+")"));
    }
});

JavaScript code:
var getHandler = function (num) {
	return function () {
		alert(num);
	};
};

$(function(){
    var i;
    for (i=0; i<2; i++){
        $('#div'+i).click(getHandler(i));
    }
});
JS has function scope. Your alert(i) refers to the i in the for loop whose value is 2 after the loop has run.

edit: Doing anything by concatenating strings is usually a horror.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Wheany posted:

JavaScript code:
var getHandler = function (num) {
	return function () {
		alert(num);
	};
};

$(function(){
    var i;
    for (i=0; i<2; i++){
        $('#div'+i).click(getHandler(i));
    }
});
JS has function scope. Your alert(i) refers to the i in the for loop whose value is 2 after the loop has run.

edit: Doing anything by concatenating strings is usually a horror.

Ah, yes. What I was missing was that you can just return function(){/*blah blah blah*/};, so I was fixated on inheriting from Function or performing that awful new Function instantiation from my post.

Thanks.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Newf posted:

return function(){/*blah blah blah*/};

Welcome to the next level

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Basically,

qntm
Jun 17, 2009
The major piece of advice is "don't make functions in a loop".

Opulent Ceremony
Feb 22, 2012
I'd post the link to the canonical "JavaScript closure example" since the problem code is almost exactly what was posted but I can't find it.

Adbot
ADBOT LOVES YOU

o.m. 94
Nov 23, 2009

It is subtleties like this so easily encountered which makes me laugh whenever someone recommends JavaScript as a beginner's language

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