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
Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
The .NET Framework as another HTTP client in it: System.Net.WebClient. Use that and its DownloadString method to get the HTTP response body as a string, which you can then throw into another XML parser.

Adbot
ADBOT LOVES YOU

FLEXBONER
Apr 27, 2009

Esto es un infierno. Estoy en el infierno.
EDIT: wrong thread

FLEXBONER fucked around with this message at 14:05 on Dec 23, 2011

Kekekela
Oct 28, 2004

Poop Delicatessen posted:

Boise is just raping ASU.

That's pretty interesting but not really javascript related. :downs:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Kekekela posted:

That's pretty interesting but not really javascript related. :downs:

code:
var whatIsBoiseDoingToASU = function() {
    return "raping";
};
Thread saved.

stoops
Jun 11, 2001
First of all, I’m pretty new to javascript/frameworks. (I know how to modify enough to get by, but I’m stuck on the basics.) Right now, I just need help in simple debugging techniques. (I’m on a cakephp framework if that even helps)

Okay, so I have a button that when clicked, calls a function, which then gets data from a database and displays on the webpage. When I click the button, I can see that it’s trying to do something, (loading keeps flashing) but the data never displays.

How can I easily debug? I’ve heard of Firebug but wasn’t sure how to get it working. What I’d like is to check if my data is even getting called first, then go from there.

This stuff is on a dev intranet, so I can’t really show any pages. Any help is appreciated.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
Get Firebug, install it, bring up your webpage and hit F12. Then watch the console or the net tabs at the bottom for the AJAX calls.

Javascript goes from horrible to kind of fun once you get a debugger like Firebug.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Every browser has dev tools for them these days.

Firefox has Firebug (extension), which you've heard of.
IE has F12 developer tools (or whatever the gently caress they're called) built-in
Chrome (and Safari) have Developer Tools (Chrome's can be activated by right-clicking on any element on a page and selecting "inspect element")
Opera has Dragonfly (also activated by right-cliking and selecting "inspect element")

Golbez posted:

Javascript goes from horrible to kind of fun once you get a debugger like Firebug.

Agreed.

The best part, I think, is using the console and just trying all kinds of poo poo. Like if you're using jQuery, just doing something like jQuery(".fancy").css('background', 'pink').

Octopus Magic
Dec 19, 2003

I HATE EVERYTHING THAT YOU LIKE* AND I NEED TO BE SURE YOU ALL KNOW THAT EVERY TIME I POST

*unless it's a DSM in which case we cool ^_^
I remember back in the day before dev tools and it was very dark and scary.

Munkeymon
Aug 14, 2003

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



Wheany posted:

IE has F12 developer tools (or whatever the gently caress they're called) built-in

It really is just called 'F12 developer tools' of all things

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Octopus Magic posted:

I remember back in the day before dev tools and it was very dark and scary.

alert('result was:' + result);

e: Actually, the three things that have made javascript development better are: developer tools, frameworks and more meaningful error messages. The errors used to be "poo poo broke somewhere, gently caress you", now they might actually tell you which part of foo.bar.quux.message is null.

Wheany fucked around with this message at 09:16 on Dec 30, 2011

mobby_6kl
Aug 9, 2009

by Fluffdaddy
Ugh so I was dicking around with JS a bit, trying to animate some stuff on my page. The problem, I think, is that my semaphore isn't working. To prevent the animations from spazzing out, I add the parameters (what, how, etc) to a queue, and then have a function shift one item off that array and run the animation. The semaphore is toggled at the beginning and end of the function, and should prevent it from being launched multiple times while it's still running, but doesn't. Here's the slightly cleaned up code:

code:
function animate(a, b, c) {
	//do animating stuff here
	if (need_more_animatin) {
		setTimeout("animate("..., 25);
	}
}

function process_queue() {
	running = true;

	while (ani_q.length > 0) {
		ani_data  = ani_q.shift();
		animate(ani_data[0], ani_data[1], ani_data[2]); 
	}

	running = false;
}

function queue_add(a, b, c) {
	ani_q.push([a, b, c]);
	if (!running) {
		process_queue();
	}
}
queue_add is triggered from various mouse events, mainly, but instead of having the animations executed in order, several animations are played at once as if the animating function was called directly by the event handlers. Any ideas what I might be missing here?

Peanut and the Gang
Aug 24, 2009

by exmarx

mobby_6kl posted:


setTimeout() doesnt work how sleep() would in other languages. It pushes the function to the event loop and then continues executing where it left off. Then when its done with everything, it returns to the event loop and looks for anything that's waiting to be executed. Thus, your while loop in process_queue() is finishing up before the first setTimeout() triggers. You probably want to set running=false when you know the animation is over in the animate() function

code:
function animate(a, b, c) {
	//do animating stuff here
	if (need_more_animatin) {
		setTimeout("animate("..., 25);
	}
	else{
		running = false;
	}
}
Also, depending on how youre animating, you might want to use jquery's animation functions. It queues animations one after the other, you can stop animations midway, and query whether an element is currently animating.

SplitDestiny
Sep 25, 2004

mobby_6kl posted:


code:
function animate(a, b, c) {
    running = true;
    //do animating stuff here
    setTimeout("animate_queue("..., 10);
    running = false;
}

function animate_queue() {
    if (running) {
        return;
    }
    if (ani_q.length > 0) {
        running = true;
        ani_data  = ani_q.shift();
        animate(ani_data[0], ani_data[1], ani_data[2]); 
    }
}

function queue_add(a, b, c) {
    ani_q.push([a, b, c]);
    animate_queue();
}
I'd imagine you would want to do something like this. Lock the queue during animation and call the next queue pop after each animation. What setTimeout does is actually just tells the interpreter to call the function after a set amount of time and allows the current JS to finish executing. For animation, setTimeout is great to not chain a ton of heavy javascript all at once.

Fiend
Dec 2, 2001
Is there a way of getting window.location.href to change the address bar in IE9? I get redirected when I do this, but the address bar stays the same :(

subx
Jan 12, 2003

If we hit that bullseye, the rest of the dominoes should fall like a house of cards. Checkmate.
Can someone point me to a good reference of how javascript "objects" actually work? Coming from normal programming languages trying to work with javascript objects is just flat out loving confusing.

I am trying to store some data from an XML as an array of objects, but I can't seem to retrieve the data from those objects.

Say my array is Names with FirstName and LastName properties:

In Firebug I can view Names[0] and it shows me [ Object { FirstName="John", LastName="Smith" } ], which seems like exactly what I wanted. But then if I try to reference Names[0].FirstName it just returns "undefined" - what am I missing here that's probably obvious?

Also is there a difference between:
"FirstName": $(this).find('FirstName').text(),
and
FirstName: $(this).find('FirstName').text(),
(with no quotes)

Edit - I guess I figured it out - [ Object ] means that it was in another array apparently, so referencing it as Names[0][0].FirstName gave me the correct value. Though everything I read said Javascript arrays work with [ { xxx: "something } ] but maybe that's a JSON Object? gently caress if I know I'm still confused as poo poo by javascript objects.

subx fucked around with this message at 20:53 on Jan 6, 2012

echobucket
Aug 19, 2004

subx posted:

Can someone point me to a good reference of how javascript "objects" actually work? Coming from normal programming languages trying to work with javascript objects is just flat out loving confusing.

I am trying to store some data from an XML as an array of objects, but I can't seem to retrieve the data from those objects.

Say my array is Names with FirstName and LastName properties:

In Firebug I can view Names[0] and it shows me [ Object { FirstName="John", LastName="Smith" } ], which seems like exactly what I wanted. But then if I try to reference Names[0].FirstName it just returns "undefined" - what am I missing here that's probably obvious?

That's exactly right
code:
>>> Names = [{FirstName:"John",LastName:"Smith"}];
[Object { FirstName="John", LastName="Smith"}]
>>> Names[0]
Object { FirstName="John", LastName="Smith"}
>>> Names[0].FirstName
"John"
do a console.log(Names[0]) right before to try to access Names[0].FirstName in your code. I'm guessing you have a bug somewhere that it making Names[0] undefined before you even get to finding the FirstName

Edit: One thing to check is to make sure Names hasn't dropped out of scope and gotta garbage collected.

echobucket fucked around with this message at 20:51 on Jan 6, 2012

sonic bed head
Dec 18, 2003

this is naturual, baby!

subx posted:

Can someone point me to a good reference of how javascript "objects" actually work? Coming from normal programming languages trying to work with javascript objects is just flat out loving confusing.

I am trying to store some data from an XML as an array of objects, but I can't seem to retrieve the data from those objects.

Say my array is Names with FirstName and LastName properties:

In Firebug I can view Names[0] and it shows me [ Object { FirstName="John", LastName="Smith" } ], which seems like exactly what I wanted. But then if I try to reference Names[0].FirstName it just returns "undefined" - what am I missing here that's probably obvious?

Also is there a difference between:
"FirstName": $(this).find('FirstName').text(),
and
FirstName: $(this).find('FirstName').text(),
(with no quotes)

For the first question - What language is the "normal" language you are coming from? It might help if I can explain in those terms, but the misunderstanding here is straightforward. Names[0] is an Array, not an Object. It is an Array of one item, as per what you've copied from firebug. Try Names[0][0].FirstName, and that should be what you're looking for.

A Javascript array is just a HashMap in Java, an associative array in PHP, a dict in Python.

Second question - In javascript, no, there is no difference. The reason that quotes are sometimes used is because there is a data serialization format called JSON (Javascript Object Notation), which requires the keys of an object to be quoted. Javascript interpreters interpret them in the same way, but if you have a key with a keyword in it, you need to use quotes.

For example {"for":"you"} will not produce a syntax error, but {for:"you"} will.

subx
Jan 12, 2003

If we hit that bullseye, the rest of the dominoes should fall like a house of cards. Checkmate.

sonic bed head posted:

For the first question - What language is the "normal" language you are coming from? It might help if I can explain in those terms, but the misunderstanding here is straightforward. Names[0] is an Array, not an Object. It is an Array of one item, as per what you've copied from firebug. Try Names[0][0].FirstName, and that should be what you're looking for.

A Javascript array is just a HashMap in Java, an associative array in PHP, a dict in Python.

Second question - In javascript, no, there is no difference. The reason that quotes are sometimes used is because there is a data serialization format called JSON (Javascript Object Notation), which requires the keys of an object to be quoted. Javascript interpreters interpret them in the same way, but if you have a key with a keyword in it, you need to use quotes.

For example {"for":"you"} will not produce a syntax error, but {for:"you"} will.

I think it was mostly just the tutorials that were confusing me. Thanks for clearing up the quotes thing - I didn't notice any difference when I changed them in code, but I wasn't sure if it changed how they were being referenced or something like that.

And I haven't done much Java/Python, mostly come from C++/C#. I had to mess with PHP at my previous job a bit and prefer to forget as much of it as possible, good lord is that a mess of a language.

subx fucked around with this message at 21:02 on Jan 6, 2012

echobucket
Aug 19, 2004

sonic bed head posted:

For the first question - What language is the "normal" language you are coming from? It might help if I can explain in those terms, but the misunderstanding here is straightforward. Names[0] is an Array, not an Object. It is an Array of one item, as per what you've copied from firebug. Try Names[0][0].FirstName, and that should be what you're looking for.

A Javascript array is just a HashMap in Java, an associative array in PHP, a dict in Python.

Second question - In javascript, no, there is no difference. The reason that quotes are sometimes used is because there is a data serialization format called JSON (Javascript Object Notation), which requires the keys of an object to be quoted. Javascript interpreters interpret them in the same way, but if you have a key with a keyword in it, you need to use quotes.

For example {"for":"you"} will not produce a syntax error, but {for:"you"} will.

Ah, man I totally missed that he has an array of arrays there.

sonic bed head
Dec 18, 2003

this is naturual, baby!

subx posted:

I think it was mostly just the tutorials that were confusing me. Thanks for clearing up the quotes thing - I didn't notice any difference when I changed them in code, but I wasn't sure if it changed how they were being referenced or something like that.

And I haven't done much Java/Python, mostly come from C++/C#. I had to mess with PHP at my previous job a bit and prefer to forget as much of it as possible, good lord is that a mess of a language.

I'm pretty sure it's called a dictionary in C# too. You can think about it as a basic hashtable [String -> Object].

FLEXBONER
Apr 27, 2009

Esto es un infierno. Estoy en el infierno.

Fiend posted:

Is there a way of getting window.location.href to change the address bar in IE9? I get redirected when I do this, but the address bar stays the same :(

Just use window.location and not window.location.href

Munkeymon
Aug 14, 2003

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



sonic bed head posted:

A Javascript array is just a HashMap in Java, an associative array in PHP, a dict in Python.

Object - an object ls basically a key-based lookup. An array is a special case of object where it acts a lot like a C# List as long as you use numbers in the square brackets, will tell you how big it is (or let you tell it how big to be) using the special length property and has a bunch of nice helper methods stuck on.* You can still tack arbitrary stuff on to an array just like an object if you really want to:

code:
ary = []
ary[0] = 1
ary.fart = 2
ary.lengh === 1 //this would be true
ary[3] = 'what'
ary.length === 4
ary.length = 1 //note single equals - this will truncate the array
ary.fart === 2 //still there!
* This is not meant to be an exact and perfect description of how an array is different from an object or even how an object 'really' works - rtfm etc.

subx
Jan 12, 2003

If we hit that bullseye, the rest of the dominoes should fall like a house of cards. Checkmate.

Munkeymon posted:

Object - an object ls basically a key-based lookup. An array is a special case of object where it acts a lot like a C# List as long as you use numbers in the square brackets, will tell you how big it is (or let you tell it how big to be) using the special length property and has a bunch of nice helper methods stuck on.* You can still tack arbitrary stuff on to an array just like an object if you really want to:

code:
ary = []
ary[0] = 1
ary.fart = 2
ary.lengh === 1 //this would be true
ary[3] = 'what'
ary.length === 4
ary.length = 1 //note single equals - this will truncate the array
ary.fart === 2 //still there!
* This is not meant to be an exact and perfect description of how an array is different from an object or even how an object 'really' works - rtfm etc.

I think things just not being typed is where I get confused. Just being able to tack random poo poo onto a variable feels weird.

sonic bed head
Dec 18, 2003

this is naturual, baby!

Munkeymon posted:


Oops, drat typo. Yes, Object, not array. They are deceivingly similar.

Munkeymon
Aug 14, 2003

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



subx posted:

I think things just not being typed is where I get confused. Just being able to tack random poo poo onto a variable feels weird.

It can be a lot of fun when you get used to it :)

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

subx posted:

I think things just not being typed is where I get confused. Just being able to tack random poo poo onto a variable feels weird.

If it quacks like a duck, it is a duck.

var a_thing = {};

a_thing.quack=function(){alert("hello, I'm totally a duck")};

a_thing.quack();

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Arrays are just objects that have special behavior for property names that are integer-able. All objects in JavaScript are hash-maps, and the property names/keys are always strings. Just like object.foobar is the same as object["foobar"], arr[0] is the same as arr["0"] is the same as arr.0, if that were valid syntax.

code:
>>> var arr = [];
>>> arr.length
0
>>> arr[0] = 42;
>>> arr.length
1
>>> arr["0"]
42
>>> arr["1"] = "hot dog";
>>> arr.length
2
>>> arr[1]
"hot dog"
>>> arr.toString()
42,"hot dog"
Primary source: section 15.4.5.1 in the ECMAScript specification. "DefineOwnProperty" is the internal method that's called for a JavaScript object when a property is set for the first time. You theoretically can't make your objects that have a "DefineOwnProperty" method, although ES6 proxy objects allow it. This is implemented in Mozilla's JavaScript engine

Mogomra
Nov 5, 2005

simply having a wonderful time

subx posted:

I think things just not being typed is where I get confused. Just being able to tack random poo poo onto a variable feels weird.

If you think that feels weird, you should look into Function.call() and Function.apply()!

* I actually love Javascript if anyone thought I was making fun of it.

ashgromnies
Jun 19, 2004
I patched together some libraries and now I can write backbone.js apps that persist to CouchDB, even remotely, by using the PostMessage API.

This means that you can write a fully featured web app without writing any backend code. I haven't finished any of the security and access restrictions(and writing business logic will be tricky, I guess you're still writing "backend code" by putting documents in Couch) but you don't need to write your models more than once.

Would anyone be interested in learning more about this? It's pretty cool -- you can access a CouchDB database on any server from Javascript. I'm using it right now to develop a Chrome browser extension that needs to share data across users -- basically adding an additional layer of functionality on top of an existing site, and we needed a database and writing a traditional web services endpoint would have been too much work so it's nice to basically just say, "database, save my poo poo" and "database, get my poo poo" from Javascript.

Kekekela
Oct 28, 2004

ashgromnies posted:

Would anyone be interested in learning more about this?
Yeah definitely. backbone.js and document db's are both things I'm interested in hearing more about.

ashgromnies
Jun 19, 2004

Kekekela posted:

Yeah definitely. backbone.js and document db's are both things I'm interested in hearing more about.

Backbone.js is neat because it gives structure to your Javascript. With a decent build script and toolchain alongside it it's actually a pretty comfortable OO environment, which has been missing from JS for a while.

Document stores are interesting because you don't have to spend so much time thinking about your data. I'm not sure how comfortable I would feel using CouchDB for a production application but for rapid prototyping, it's pretty great.

My goal is to create an easy to use "framework" for JS-based prototype apps. Install CouchDB somewhere, point Backbone.js at your instance, and start coding almost entirely business logic, which is neat!

magic_toaster
Dec 26, 2003
No.
How can I create a function that can store a value, , but also allows it to be updated, and then retrieved from again?


An example would be a function that, when called, can retrieve a value from a cookie, and then in each subsequent request, can just return the value that it retrieved from the cookie. And if needed, the function can be passed an id, set the cookie, and then return that value each time the function is called.

Any help would be appreciated.

e: i don't need syntax for retrieving/setting the cookie.

magic_toaster fucked around with this message at 03:06 on Jan 11, 2012

subx
Jan 12, 2003

If we hit that bullseye, the rest of the dominoes should fall like a house of cards. Checkmate.

magic_toaster posted:

How can I create a function that can store a value, , but also allows it to be updated, and then retrieved from again?


An example would be a function that, when called, can retrieve a value from a cookie, and then in each subsequent request, can just return the value that it retrieved from the cookie. And if needed, the function can be passed an id, set the cookie, and then return that value each time the function is called.

Any help would be appreciated.

e: i don't need syntax for retrieving/setting the cookie.

I'm assuming you just need to set the variable before you run the function?

code:
var x;
var previouslyUpdated = false;

function blah(_xValue) {
  if (previouslyUpdated = false) {
    x = cookieValue;
    previouslyUpdated = true;
  }
  else {
    x = _xValue;
  }
Something like that? It's possible that's terrible and there is a better way as I am still getting used to Javascript.

Aquarium of Lies
Feb 5, 2005

sad cutie
:justtrans:

she/her
Taco Defender
Can anybody offer any links to reliable base 64 encoding/decoding functions? I need to encode a series of integers on the fly, and the pair I originally selected started choking once I got above 255 (which I was somewhat expecting).

For the record, I was using fromCharCode/charCodeAt to convert the integers into Unicode characters and passing that to the base64 functions, but it'd be extra convenient if I could pass the array directly.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

magic_toaster posted:

How can I create a function that can store a value, , but also allows it to be updated, and then retrieved from again?


An example would be a function that, when called, can retrieve a value from a cookie, and then in each subsequent request, can just return the value that it retrieved from the cookie. And if needed, the function can be passed an id, set the cookie, and then return that value each time the function is called.

Any help would be appreciated.

e: i don't need syntax for retrieving/setting the cookie.


Why wouldn't you just set and read the cookie every time?

Here's a function that returns a default value if nothing got set, but then returns a new value if you send it one, but your case with the cookies is kind of silly, since if you set the cookie when you pass in a new value, you might as well just user he cookie

code:
Blah = {
  blob: function (newVal) {
    var updatedVal, defaultVal = "flan";
    If (newVal) updatedVal = newVal;
    return updatedVal || defaultVal;
  }
}
You'd have to tweak if you were ever going to update the value to false, but you get the idea.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
edit: ignore

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
Does anyone know of any lightweight & fast generic language parsers in JS?

I want to parse a very constrained and modified form of CSS (the BNF grammar is pretty simple) and am happy to code my own tokenizer and recursive descent parser but would rather not re-invent the wheel if something decent already exists.

Deus Rex
Mar 5, 2005

ynohtna posted:

Does anyone know of any lightweight & fast generic language parsers in JS?

I want to parse a very constrained and modified form of CSS (the BNF grammar is pretty simple) and am happy to code my own tokenizer and recursive descent parser but would rather not re-invent the wheel if something decent already exists.

pegjs or jison seem to be the leading contenders as far as JS parser generators go.

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
Both of those look great. Thanks!

Edit: In particular I appreciate how pegjs has strong parse error reporting. That'll really help pull this project up from being a toy hack into something more useful.

ynohtna fucked around with this message at 11:47 on Jan 11, 2012

Adbot
ADBOT LOVES YOU

205b
Mar 25, 2007

I broke something again. I've got this model

code:
        this.LocationMiniModel = function(x, y, z) {
            this.x = x;
            this.y = y;
            this.z = z;
        };
        this.LocationMiniModel.prototype.setViewAdapter = function(viewAdapter){
            this.viewAdapter = viewAdapter;
        };
        this.LocationMiniModel.prototype.append = function(element) {
            this.viewAdapter.append(element);
        };
and I'm trying to set up a view for a different model

code:
                    var category = new this.CategoryMiniModel(categoryData.name,
                                                              categoryData.uid,
                                                              locationData.uid);
                    category.setViewAdapter(
                        viewAdapter.makeCategoryMiniViewAdapter(
                            categoryData.name, category, location.append));
where location.append points to the append function in the first block of code. (The idea is that the constructor for the new view gets passed a function that it can use to append itself to a parent div.) The issue is that when location.append actually gets called, "this" points to the DOMWindow object and not the proper LocationMiniModel instance. What am I doing wrong?

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