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
Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Thermopyle posted:

JavaScript code:
[
    {
        "id": 15,
        "name": "Your Mom",
        "address1": "345 Fucker Lane",
        "address2": "",
        "city": "Sucks",
        "zipcode": "55555",
        "state": "CA",
        "units": [
            "http://0.0.0.0:8100/api/unit/13/",
            "http://0.0.0.0:8100/api/unit/14/",
            "http://0.0.0.0:8100/api/unit/15/",
            "http://0.0.0.0:8100/api/unit/16/"
        ]
    }
]

Please don't doxx my mom.

Adbot
ADBOT LOVES YOU

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.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

necrotic posted:

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

Maybe? It's what I did when I wanted a sub-collection. Now that I think of it, I did have an array of objects instead of strings. That will teach me to try and help. :(

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.

Thermopyle posted:

A backbone collection backed by this endpoint has a bunch of models where the "units" is an array of strings. I guess units should be a collection? Is there a way to make it automatically create a collection from that when I fetch?

Why does units need to be a collection if the data contained within is an array of strings? What's the problem with an array of URLs? I ask because you seem unsure why you're doing this.
Isn't the point of a Backbone Collection to store a series of models, which are objects?

If you could cast the array into a Collection, how would you access the individual urls from the Collection without a model?
code:
var arrayCollection = new Backbone.Collection(['abc', 'def']);
arrayCollection.first().values()
// ["a", "b", "c"]
arrayCollection.first().get(0)
// "a"
That just doesn't work, so you probably want something like
code:
var urlCollection = new Backbone.Collection([{url:'abc'}, {url:'def'}]);
urlCollection.first().get('url')
// "abc"
Knowing this, the only way to get it is using what Lumpy said and munging the API data into the right format
code:
parse: function (response) {
    respons.units = new Backbone.Collection(
        respons.units.map(function(str) {
            return {url:str}; 
        })
    );
    return response;
}

Thermopyle
Jul 1, 2003

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

v1nce posted:

Why does units need to be a collection if the data contained within is an array of strings? What's the problem with an array of URLs? I ask because you seem unsure why you're doing this.
Isn't the point of a Backbone Collection to store a series of models, which are objects?

If you could cast the array into a Collection, how would you access the individual urls from the Collection without a model?


A HATEOAS api represents foreign key-related models with URLS instead of nesting JSON. Thus, that array of URLS is an array of models...on the server. I'm wondering if there is a best practices sort of way for consuming a HATEOAS api with Backbone.

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
Oh right, I thought you were just trying to parse the data into a Collection, not actually populate the collection of models. My bad for being retarded.

From looking at some references though, you're still is the situation where your API is returning something Backbone really isn't expecting. The standard structure has the model with a set rootUrl, or the owning Collection has a path and the Model's ID is used (see Backbone.Model.prototype.url).

The only thing I've dug up on the topic is this: http://stackoverflow.com/questions/9520275/using-hateoas-and-backbone-js
For your structure that would look more like this
code:
var UnitModel = Backbone.Model.extend({ 
    url: function() { 
        return get('_url'); 
    },
    parse: function(response) { 
        this._url = response._url; 
    }
});

var UnitCollection = Backbone.Collection.extend({
    model:UnitModel,
});

var TheOtherCollection = Backbone.Collection.extend({
    parse: function(response) {

        var units = response.units.map(function(str) {
            return {_url:str};
        });

        response.units = new UnitCollection(units);
    }
});
This lets you use your absolute URL in the Model, as passed by your collection, but it's not really the standard Backbone approach to use absolute URLs. As for best practice, I've no idea.

Chas McGill
Oct 29, 2010

loves Fat Philippe

v1nce posted:

Yep, to my mind d3.js is your best bet for something that's interactive , animated and pleasant. The only real limit to d3.js that I'm aware of is, because it uses SVG, it won't work in IE8 and below. You may or may not care about this.

This is from 2012, but here's a nice starter tutorial on d3.js that should give you lots of hints on how to get some of the way to where you want to be.
http://code.hazzens.com/d3tut/lesson_0.html

Once you've got the basics down, you should be able to fudge it together with a cross between these two:
http://bl.ocks.org/mbostock/4061502
http://bl.ocks.org/mbostock/3885304

If you don't know JavaScript, it can be a bit of a dick. A good syntax highlighting editor will go a long way towards saving you from yourself. If you get stuck, come ask questions - sometimes it will be the stupid mistakes that you get stuck on, rather than the technical hurdles.

Lumpy posted:

In addition to the good advice by v1nce, there is a Data Visualization Thread that might be helpful to you.

Thanks. Looks like I've got some learning to do. Even if I'm not actually handling data, is d3 still the best for interactivity/animation? The bars don't have to be accurate or run from a set of data - they just need to be roughly the right relative size.

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

What is the proper name of the railway-track notation used to describe syntax grammars on Json.org?

What is the significance of the double-barred start/finish points for string and number versus the single-barred start/finish of objects, arrays, and values?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Newf posted:

Minor questions.

What is the proper name of the railway-track notation used to describe syntax grammars on Json.org?

What is the significance of the double-barred start/finish points for string and number versus the single-barred start/finish of objects, arrays, and values?

Stolen from: http://stackoverflow.com/questions/2986518/railroad-diagrams-what-do-the-double-bars-on-the-ends-mean

One bar: whitespace can be inserted between pairs of tokens.
Two bars: no whitespace allowed between pairs of tokens.

And they are called "Railroad Diagrams" :v:

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

Lumpy posted:

And they are called "Railroad Diagrams" :v:

Well then.

Thanks :)

qntm
Jun 17, 2009

Newf posted:

What is the significance of the double-barred start/finish points for string and number versus the single-barred start/finish of objects, arrays, and values?

It was so long before I even noticed those.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Where do people get the sort of data presented in this sexy article? I'm looking to do something with google's autocomplete data, but I can't find a good foothold.

The first promising path that I found was this SO question, but doing it client side with an ajax call results in "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access." - eg, not allowed for xss prevention purposes?

Any suggestions?

Peanut and the Gang
Aug 24, 2009

by exmarx
Maybe it's somewhere in google trends? Idk. I would just email the guy.

The article posted:

Or consider the most common search about a girlfriend’s breasts: “I love my girlfriend’s boobs.” It is not clear what men are hoping to find from Google when making this search.

Lol.

EAT THE EGGS RICOLA
May 29, 2008

Chas McGill posted:

Thanks. Looks like I've got some learning to do. Even if I'm not actually handling data, is d3 still the best for interactivity/animation? The bars don't have to be accurate or run from a set of data - they just need to be roughly the right relative size.

I've used it for that kind of stuff before, and it works about the same.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Can a local file be loaded into a web app (hosted on a remote server) without uploading to the server?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

Sure can, the big caveat is the only file picker allowed is the browser default, but once the HTML element has that file you'll have access to it. There are more complicated methods like drag and drop, but ultimately they all give you the ability to access the file in Javascript without communicating with server.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Remember how I was complaining about stupid, inconsistent implementations of things? Here's one that's consistently stupid:

JavaScript code:
var actx = new AudioContext(),
  oscillator = actx.createOscillator();

try {
	oscillator.stop();
	oscillator.stop();
} catch (jfcreally) {/*
how to make an interface really loving annoying:
	throw exceptions if you try to set a binary to its current state
	but don't bother exposing the state of the binary or anything
*/}
Maybe IE won't do that whenever they bother to support it but it's too late so oh well.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

If the state can be changed in parallel with script execution, then being able to sample it just invites race conditions. It would be interesting to find the archive of conversations about that behavior, though, because I'm sure your objection has come up. (The Audio stuff was bitterly fought for ages between the "expose simple primitives, do the rest in script" and "CoreAudio.js" camps; no objection was left unraised.)

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Granted I just started poking around in this area on Friday but I'm not seeing where the state could change from outside the script except in one of the source/decoder nodes and I'd still like to be able to ask one of them if they're still outputting without hooking an event handler to each one.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Munkeymon posted:

Remember how I was complaining about stupid, inconsistent implementations of things? Here's one that's consistently stupid:

JavaScript code:
var actx = new AudioContext(),
  oscillator = actx.createOscillator();

try {
	oscillator.stop();
	oscillator.stop();
} catch (jfcreally) {/*
how to make an interface really loving annoying:
	throw exceptions if you try to set a binary to its current state
	but don't bother exposing the state of the binary or anything
*/}
Maybe IE won't do that whenever they bother to support it but it's too late so oh well.

Weird, according to http://webaudio.github.io/web-audio-api/#widl-OscillatorNode-stop-void-double-when it should not throw anything.

I looked it up because it sounded wrong. Then again, that spec was last updated a bit over a month ago, so who knows what it has been before and how browsers have implemented it.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Wheany posted:

Weird, according to http://webaudio.github.io/web-audio-api/#widl-OscillatorNode-stop-void-double-when it should not throw anything.

I looked it up because it sounded wrong. Then again, that spec was last updated a bit over a month ago, so who knows what it has been before and how browsers have implemented it.

The specced behavior still annoying considering the semantics they used. I didn't expect to have to go all the way into the W3C docs to learn that it's expected that you're not even supposed to be able to start a stopped node - that's also pretty weird.

Also just noticed that ScriptProcessor is deprecated in favor of an AudioWorker that loads a script URL. Because as a _______, I expect my audio API to load scripts for me :confused:

(yes, I'm sure people have argued the minutiae of this into the bedrock but that doesn't mean I have to like it)

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Workers are specified in terms of script URLs, it's just how it works. I use this hack to ease development:

JavaScript code:
function makeWorkerFromFunction(func) {
    var blob = new Blob([func.toString(), func.name + '(this);'], { type: 'text/javascript' });
    var url = window.URL.createObjectURL(blob);
    var w = new Worker(url);
    window.URL.revokeObjectURL(url);
    return w;
}
Yes, I know func.toString() is slow and func.name is nonstandard. Shut up.

playground tough
Oct 29, 2007
So I am working on an audio visualizer in javascript using webAudioAPI. Im hoping someone can give me some direction.

My FFT is 2048 so frequencyBinCount is supposed to give me 1024 datapoints to work with. However, on windows, I am only getting ~200 datapoints that display a condensed version of the datapoints I am getting displayed on my mac(around 800). What gives?

Even when I reduce the fftSize, on windows in chrome I only get a fraction of the points I should be getting.

EDIT: so upon further investigation, it seems that windows is failing to pick up on frequencyBins beyond 200, because when I change analyser.minDecibels to a lower value.. I see some readout...

How do I normalize the frequency readout so it is the same on mac and windows :(

playground tough fucked around with this message at 01:02 on Feb 11, 2015

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Suspicious Dish posted:

Yes, I know func.toString() is slow and func.name is nonstandard. Shut up.

func.name is in ES6 and de facto in everything anyway, you're good.

E: actually, holy poo poo, IE might still not support it? :psyduck:

Subjunctive fucked around with this message at 01:29 on Feb 11, 2015

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Suspicious Dish posted:

Workers are specified in terms of script URLs, it's just how it works. I use this hack to ease development:

JavaScript code:
function makeWorkerFromFunction(func) {
    var blob = new Blob([func.toString(), func.name + '(this);'], { type: 'text/javascript' });
    var url = window.URL.createObjectURL(blob);
    var w = new Worker(url);
    window.URL.revokeObjectURL(url);
    return w;
}
Yes, I know func.toString() is slow and func.name is nonstandard. Shut up.

Thanks that's good to have. I'm just going to stop yelling into the wind now :sigh:

George Sex - REAL
Dec 1, 2005

Bisssssssexual
I'm interested in learning Jacascript in my free time and was wondering a good place to start? I understand there are some online courses that are supposed to be pretty good, but I haven't heard anything specific. I have some experience with Java and C from highschool, so I'm not a complete beginner. Thanks brahs.

Fish Ladder Theory
Jun 7, 2005

Dorkopotamis posted:

I'm interested in learning Jacascript in my free time and was wondering a good place to start? I understand there are some online courses that are supposed to be pretty good, but I haven't heard anything specific. I have some experience with Java and C from highschool, so I'm not a complete beginner. Thanks brahs.

Assuming you mean Javascript, https://www.eloquentjavascript.net is the best resource, imo.

George Sex - REAL
Dec 1, 2005

Bisssssssexual

Fish Ladder Theory posted:

Assuming you mean Javascript, https://www.eloquentjavascript.net is the best resource, imo.

Yeah, I did mean Javascript. I've been going through some of the lessons on CodeAcademy and it seems pretty rote, but manageable. Has anyone else gone through their lessons?

bpower
Feb 19, 2011
Just getting into javascript. I'm using VS 2013. I'm trying to set up my workflow/environment. Coming from c# with ReSharper its agony.

I'm running JSCS and its seems schizophrenic.

code:
( function () {
//stuff
})();
The first line gives 4 warnings

JSCS: Illegal space before opening round brace
JSCS: Illegal space before opening curly brace
JSCS: Invalid line break
JSCS: Expected a padding newline after opening curly brace

Removing the "Illegal space before opening curly brace"
code:
( function (){
//stuff
})();
Now I have 6 warnings on the first line

JSCS: Missing space after opening round bracket
JSCS: Illegal space before opening round brace
JSCS: Missing space before opening curly brace
JSCS: Missing space before opening curly brace for block expressions
JSCS: Invalid line break
JSCS: Expected a padding newline after opening curly brace


What on earth is happening?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I have no experience with JSCS specifically, but I would imagine that it comes with a set of configurable rules, and you're supposed to turn on the ones that enforce your particular code style. If you have all the rules enabled, some of them will contradict, and it will have some complaints in every situation.

Even if you've configured it properly for your code style, it's going to be very hard for someone to tell you what you're screwing up unless they also know what rules you've set it to enforce.

ufarn
May 30, 2009
jscs has a lot of seriously dumb rules. Don't use it, unless you make your own custome rulset.

The defaults on linters outside of pep8 stuff are usually untenable.

EDIT: If you *have* written your own ruleset, it's also possible to create rules that contradict each other and leave you with 100% chance of an error - especially with the space-or-no-space rules.

ufarn fucked around with this message at 19:36 on Feb 12, 2015

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
I only just found office.js


Has anyone used it? I love excel so I'm cautiously excited.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
I don't think I fully understand the order in which code runs.

Say I have the following:


code:
var myArray = [{type: "Foo", amount:20},{type: "Bar", amount:30}, {type:"Foo", amount: 500}];

console.log(myArray);  //in my mind - should return the above values

function changeStuff(){
    for(var x=0; x< myArray.length; x++){
         if(myArray[x].type = "Foo"){
             myArray[x].amount += 10;
         }
    }
};

console.log(myArray);   //myArray[0].amount = 30 &&  myArray[2].amount = 510;

Why does my first console.log return the myArray values that result after changeStuff() has run?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Raskolnikov2089 posted:

I don't think I fully understand the order in which code runs.

Say I have the following:


code:
var myArray = [{type: "Foo", amount:20},{type: "Bar", amount:30}, {type:"Foo", amount: 500}];

console.log(myArray);  //in my mind - should return the above values

function changeStuff(){
    for(var x=0; x< myArray.length; x++){
         if(myArray[x].type = "Foo"){
             myArray[x].amount += 10;
         }
    }
};

console.log(myArray);   //myArray[0].amount = 30 &&  myArray[2].amount = 510;

Why does my first console.log return the myArray values that result after changeStuff() has run?

That can't be all of your code because it doesn't run changeStuff at any point, so maybe flesh out the example?

enthe0s
Oct 24, 2010

In another few hours, the sun will rise!
e: I can't actually read either, so ignore me.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

Munkeymon posted:

That can't be all of your code because it doesn't run changeStuff at any point, so maybe flesh out the example?


Sorry, I added it, but I think I just realized why.
code:
var myArray = [{type: "Foo", amount:20},{type: "Bar", amount:30}, {type:"Foo", amount: 500}];

console.log(myArray);  //in my mind - should return the above values

changeStuff();

function changeStuff(){
    for(var x=0; x< myArray.length; x++){
         if(myArray[x].type = "Foo"){
             myArray[x].amount += 10;
         }
    }
};

console.log(myArray);   //myArray[0].amount = 30 &&  myArray[2].amount = 510;

Is the changeStuff declaration being hoisted above my initial console.log, thus resulting in the value changes?

Raskolnikov2089 fucked around with this message at 23:55 on Feb 17, 2015

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Raskolnikov2089 posted:

Sorry, I added it, but I think I just realized why.
code:
var myArray = [{type: "Foo", amount:20},{type: "Bar", amount:30}, {type:"Foo", amount: 500}];

console.log(myArray);  //in my mind - should return the above values

changeStuff();

function changeStuff(){
    for(var x=0; x< myArray.length; x++){
         if(myArray[x].type = "Foo"){
             myArray[x].amount += 10;
         }
    }
};

console.log(myArray);   //myArray[0].amount = 30 &&  myArray[2].amount = 510;

Is the changeStuff declaration being hoisted above my initial console.log, thus resulting in the value changes?

You realize you are assigning 'Foo' as the type instead of checking against it, right? Make a JSFiddle that shows your problem, since I'm not sure the code you are typing in here is what you are running.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

Lumpy posted:

You realize you are assigning 'Foo' as the type instead of checking against it, right? Make a JSFiddle that shows your problem, since I'm not sure the code you are typing in here is what you are running.


Urgh. Long day


http://jsfiddle.net/tr6abac4/8/

I just don't understand why my first console.log reflects the changeStuff() updated values, when it hasn't even run yet.

*edit - got rid of the console.log workaround from http://jsfiddle.net/tr6abac4/5/

Raskolnikov2089 fucked around with this message at 00:32 on Feb 18, 2015

Sedro
Dec 31, 2008
You're printing a reference to myArray to the console and then mutating the object. When you inspect the object in the browser you will see its latest state.

You could instead print the object as JSON which will copy its current state
JavaScript code:
console.log(JSON.stringify(myArray));

Adbot
ADBOT LOVES YOU

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

Sedro posted:

You're printing a reference to myArray to the console and then mutating the object. When you inspect the object in the browser you will see its latest state.

You could instead print the object as JSON which will copy its current state
JavaScript code:
console.log(JSON.stringify(myArray));

So console.log(object) will always show the object in its final form? is that also why console.log(myArray[0].amount) shows what I actually expected, depending on when it's called?

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