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
necrotic
Aug 2, 2005
I owe my brother big time for this!

Dr Monkeysee posted:

arguments is a particular quirk of JavaScript but other languages have something sorta similar (C# has params arguments, C/C++ has variadic functions, and nearly every dynamic language has *some* way of passing arbitrary arg lists to methods).

The main difference between Javascript's arguments and other languages is that arguments a) contains all of the passed arguments and b) is not actually an array. Any other language I can think of that supports variable argument definitions has both an explicit way of defining access to them (*args in ruby) and the list of variable arguments is not some special "object".

Adbot
ADBOT LOVES YOU

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

nexus6 posted:

I'm not trying to be fancy, I'm trying to get it to do its default functionality. Something appears to be blocking it, I can see that there should be a JS file being run that, for some reason, isn't. Since I'm not getting any console errors I'm at a loss to find out what is (or isn't) happening.

That seems like an issue with Drupal that should be taken up in a related thread? Or maybe their support site.

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

Bruegels Fuckbooks posted:

You can stop an image (or anything else) download by doing something like:

code:
if(window.stop !== undefined)
{
     window.stop();
}
else if(document.execCommand !== undefined)
{
// ie
     document.execCommand("Stop", false);
}
This will trigger the onabort of everything that has an onabort (like ajax calls) so it's usually a Bad Idea to use.

This is exactly what was suggested 3 posts up (and what Subjunctive was responding to).

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

Wheany posted:

Maybe with some fuckery like this:
JavaScript code:
var scriptTag = document.createElement("script"); 
scriptTag.src="filename.js?cacheBuster=" + new Date().getTime(); 
document.head.appendChild(scriptTag);

Yeah, something like this should work. You'll want to make sure you are handling "unloading" the old script (unhooking events, stopping timers, etc...) though.

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

Well, to get a modal you'd want to use the built-in confirm or one of the many modal libraries (bootstrap, foundation, jquery UI's dialog). Then use $.ajax when they confirm the save.

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

Wheany posted:

Don't use alert() or confirm() for anything, just use some UI kit's dialogs.

Which is why I mentioned them. `confirm` works fine for quick mockups and mucking about, though.

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

Raskolnikov2089 posted:

I need to write this example over and over 100 times. In my mind, I couldn't figure out why JavaScript wasn't pointing to the global foo(), but I didn't fully grasp how local variables can take precedence over global ones.

Thank you. A lot more of this beautiful language makes sense now.

Scope is one of the most important things to grasp in Javascript. This StackOverflow post has a terse but good overview of variable scoping in JS.

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

Tomed2000 posted:

This might be a dumb question but why do JavaScript libraries use IIFEs if they simply modify the global object in the end anyway? For example this guy says to declare the library in an IIFE then says window.Q = Q. Why not just declare a function named Q which returns the new library object when called? In both cases you are creating new scopes and in both cases you are only adding one function to the global scope. What am I missing here?

Two reasons why IIFE is important here:

  • The Library object (and subsequently Q.fn) is created one time; creating it all inside of Q would rebuild it every call (which could get expensive).
  • Exposing Q.fn (which is also Library.prototype) allows you to create plugins on top of the library. If you were to create a new Library for every call to Q it would require any plugin authors to wrap Q with their own function that would apply the plugin and return it.

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

Opulent Ceremony posted:

I'm confused, how is Library being created once in this case? It looks like whenever you call Q() the Library constructor function is run and a new object is returned.

A new object is allocated, but the prototype of that object is already allocated in the IIFE. If you did the entire thing in Q() the object and the prototype would be allocated for each call.

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

loquacius posted:

Another question related to my previous issue: I have scroll event listeners in place that make changes to the page depending on where the user has scrolled. If I scroll around using a laptop touchpad (or tablet touchscreen), the scroll event fires and the listeners do their job as long as my fingers are still touching the pad/screen. If I "flick" my way around the page with a quick swipe, though, neither the "scroll" event nor the "touchmove" event seems to fire. Is there another event I should be listening on to deal with swipes or am I SOL?

Probably SOL? I have had an awful time trying to interact with touchpads/screens and scroll/touch events.

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

Storgar posted:

Wow, great response! I guess its not too early to start using jQuery. Is there anything that stands out in particular that jQuery makes a lot easier? (besides cross browser compatibility)

If you're not worrying about older browsers you can skip jquery just fine. It does add some convenience (for example, adding event listeners to a bunch of elements matching a similar selector), but its definitely not necessary.

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

Pollyanna posted:

Require.js is bizarre and I just cannot wrap my head around it. I have a Yeoman-generated app that's based on a React UI, and I just cannot figure out how I'm supposed to add Backbone to the dependencies and be able to use it. I ran bower install backbone --save then grunt bower just like the Yo docs tell me to do, and it says that it "Updated RequireJS config with installed Bower components" , but Backbone is never actually loaded and the config doesn't actually change! :( Require.js has been such a pain in the rear end to wrangle that I'm really regretting using it for my project. Can anyone tell me how to get this frickin' thing to work?

If it helps, here's my main.jsx:

code:
/** @jsx React.DOM */
'use strict';

require.config({
	baseUrl: 'scripts',
	paths: {
		react: 'script/react.min'
	},
	shim: {
		react: {
			exports: 'React'
		}
	}
});

require(['app'], function (App) {

	// use app here
	React.renderComponent(
		<App />,
		document.getElementById('app')
	);
});

You need to add backbone: "path/to/backbone" to the paths key in the config.

Also, require.js doesn't load anything until you reference it. Does app reference backbone in the dependency list? If not, it will not get loaded in your example.

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

Kobayashi posted:

Modern web tooling is such a loving joke.

It gets me every time. I will never understand why they thought it was a good idea.

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

Xenoveritas posted:

Of course I have no clue why that logic also applies to the part where you're explicitly indicating where to locate a given named module.

That's kind of my point. Pick one and stick with it.

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).

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.

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.

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

Dangerllama posted:

This code always returns the empty JSON via the API: [{}]

Because you are returning the initial value ({}) from getDuData. To make it work asynchronously you need to do something like:

code:
exports.index = function(req, res) {
  getDuData(function(data) {
    res.json([data]):
  });
};
function getDuData(cb) {
  var request_url = 'http://denveruniv-web.ungerboeck.com/coe/coe_p1_all.aspx?oc=01&cc=ICEDI30';

  request(request_url, function (error, response, html) {
    cb(response);
  });
}
Also yeah, look at something like async linked above.

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

Hughmoris posted:

I have a simple, single webpage that has a button called "Start Over" with coding of:
code:
<INPUT type=reset value="Start Over" name=resetButton>&nbsp;
Is it possible to add a hidden functionality to that, using javascript? I have a JS function called "TestFunction". Is there a way to have "TestFunction" execute if I hold the Shift key + click on the "Start Over" button?

Add a click event listener and check for the shiftKey modifier: http://jsfiddle.net/m9zy63v9/1/

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

Suspicious Dish posted:

Please use the "input" event, not "click", just in case someone uses the Enter or Space keys to activate your button. Unless those activate "click" now. They didn't used to.

If he wants shift-enter to accomplish the same thing then yes. To mean that seems like an odd input combo as enter usually submits a form and its not that hard to accidentally hold shift in the process.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Also, don't use eval. You can access properties on an object using brackets: console.log(classroom.room1.students[student2].grade + 5);

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

Lumpy posted:


JavaScript code:
 parse: function (response) {
        response.units = new UnitCollection(response.units);
        return response;
    }
will automagically do that for you.

Will that work given the response? I thought the collection initializer took an array of objects, not URLs.

necrotic
Aug 2, 2005
I owe my brother big time for this!
JavaScript code:
getArticle().spread(replaceImages.bind(this, article, meta));
would be

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

Misogynist posted:

article and meta are undefined in this scope

Oh, of course.

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

Ranzear posted:

JavaScript code:
if (Object.prototype.hasOwnProperty.call(options, key)) {
}

Guarantees no errors (as options.hasOwnProperty can be changed). I've started going with Object.keys to remove that dumb loving call. Downside is the scope change, but in most cases it's not that bad.

code:
Object.keys(options).forEach(function(key) {
});
Also, if you have jQuery or underscore you can do options = $.extend({}, options, defaults); or options = _.extend({}, options, defaults)

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

Subjunctive posted:

At the limit, Object.prototype.hasOwnProperty can be changed as well, of course, but it's rarer and usually compatible when things like that happen.

Yeah, that's true, but if you use something like jQuery you would notice very quickly if the root Object.prototype.hasOwnProperty was overridden (unless you changed it after including, I guess). Most of the time its not a problem anyway, but its good to understand why it can be an issue.

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

Wheany posted:

Does anything change hasOwnProperty anywhere?

Maybe like, evil.js. But nobody would seriously do it. Just use Object.keys, though. It ensures you get only the actual properties of the object, not crap from the prototype chain.

necrotic
Aug 2, 2005
I owe my brother big time for this!
If you move the new Inner() below Inner.prototype.p it works. I don't know why, exactly, but it's a fix!

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

Newf posted:

Ah... OK. The function definitions get 'hoisted' and are scoped throughout the block that they're declared in (so Inner() is available where new Inner() is called), but the property placed onto the prototype is only available below its definition. Thanks.

Oh wait, yeah. After looking at it again it make sense: the constructor is called before p is set on the prototype. Oops!

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

EAT THE EGGS RICOLA posted:

I need to implement relatively complex dynamic autocomplete for a form using a Solr instance as the data source. Is there a straightforward way to implement this (maybe I should just rely on jquery's autocomplete stuff)?

I'd just use one of the autocomplete libs. Bootstrap has a relatively decent one, I haven't used jQuery's though I'm sure it works mostly fine.

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

ufarn posted:

Anyone know whether it's possible to transpile the JS in an HTML file from es6 to es5?

Want to start using es6, but I prefer all the code in one file rather than editing the JS as an external file.

You could maybe probably hack it in with something like:

code:
<script type="text/javascript-es6" id="transcode-me">
</script>
<script src="//whatever/transpiler.js"></script>
<script>
var code = document.getElementById('transcode-me').innerText;
eval(Transpiler.compile(code))
</script>
But that's pretty dumb. Just use a normal build process.

necrotic
Aug 2, 2005
I owe my brother big time for this!
JS in the browser can't do TCP/IP directly, but node or one of the other server-side ones can.

necrotic
Aug 2, 2005
I owe my brother big time for this!
If they are just animated constantly its not scroll hijacking. That crap people do with parallax backgrounds on scroll is janky as gently caress.

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

WrathOfBlade posted:

Not particularly, but I'll still need to parse it and evaluate it at some point. Preferably without the use of eval.

(E. Also don't take the object paths literally here, I'll have logic to fetch those values, the issue is parsing the Boolean logic to perform on them)

Is it always going to be groups of AND separated by OR conditions? So (first) || (second) || (third)...? If that's the case it could be pretty straightforward:

code:
{
  "sword_get": [
    {"inventory.sword.owned": true, "inventory.sword.sharpened": true},
    {"quests.sword": "complete"}
  ]
}
You'd likely want to cache the "parsing" somehow.

Alternatively, while this is not a good solution, if you need more complex conditions you could simply store them as strings and eval them :)

necrotic
Aug 2, 2005
I owe my brother big time for this!
Something like this should work with a fixed schema:

JavaScript code:
function createTree(arr) {
    var root;

    arr.reduce(function(prev, el, i) {
        var cont = {},
            node = {property: el.property};

        cont[el.title] = node;
        if (i > 0) prev.children = cont;
        else root = cont;
        
        return node;
    }, {});
    
    return root;
}
Making it work with an arbitrary list of objects would simply require looping through el's keys and skipping the title.

necrotic
Aug 2, 2005
I owe my brother big time for this!
The only way to ensure order is using arrays, objects in Javascript are not ordered. For a 2D grid, use a 2-dimensional array where the first dimension is rows and the second is columns.

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

Subjunctive posted:

Objects and Arrays can both have numbered properties, which can be looped over with for. The only real difference between Arrays and Objects is that Arrays maintain a length property.

http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf

quote:

4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

So, sure, you can use numbers if you want. But the order is not guaranteed! You may experience behavior that makes it look like it is, but the spec doe not require it and browsers do behave differently.

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

Subjunctive posted:

Arrays aren't ordered either, you just access their numeric properties in order by looping from 0 to length; you can do the same with an Object. See 15.4 of the ES5 spec, or the specification of things like Array.prototype.forEach which explicitly count from 0 to length. 12.6.4 explicitly says that the enumeration order is not specified, and that holds for all objects including Arrays.

I think you're confusing JSON's (non-)guarantees about the order that properties appear in serializations with some inherent property order for Arrays.

Right, but if you care about order why would you use an Object with numeric keys instead of an Array (which gives you forEach that is ordered, whereas Object.keys().forEach would not be)? The only case I could see using an Object over an Array is if your starting index isn't 0 or something (since every index before N would "exist" as undefined).

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

Subjunctive posted:

But your starting index claim is not true either; if you don't set a property on an array it doesn't exist either, per keys() or in:

Ah, I could've sworn it was. Thanks for the correction.

Munkeymon posted:

Because you're a PHP developer and that's how it works there so that's how every other language must work, right?

I haven't worked with PHP in over 6 years, so no. rear end.


edit: My confusion on sparse arrays came from JSON-ifying them :downs:

necrotic fucked around with this message at 18:08 on May 21, 2015

Adbot
ADBOT LOVES YOU

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

MasterSlowPoke posted:

Looks like deep paranoia level sanitizing. Isn't Java strongly typed?

Yes. Javascript is not, though. Guess you were referring to the now-removed post above?

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