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
Haystack
Jan 23, 2005





Could someone explain this code pattern to me?

code:
var returnedValue = (function() {...})(parameter);
An example:
code:
var parameter = "Whiz! "
var firework = (function(supppliedParameter) {
  var sound = supppliedParameter + "Bang!";
  return sound;
})(parameter);

alert(firework); // Should alert "Whiz! Bang!"
I understand that this defines and then executes an anonymous function, assigning the return value to fireworks. What I don't understand is why this syntax works. Namely, why does wrapping a function in parenthesis and then immediately calling it work?

Edit: Fixed a stupid mistake with my parameter.

Haystack fucked around with this message at 16:31 on Dec 29, 2009

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Haystack posted:

Could someone explain this code pattern to me?

code:
var returnedValue = (function() {...})(parameter);
An example:
code:
var parameter = "Whiz! "
var firework = (function() {
  var sound = parameter + "Bang!";
  return sound;
})(parameter);

alert(firework); // Should alert "Whiz! Bang!"
I understand that this defines and then executes an anonymous function, assigning the return value to fireworks. What I don't understand is why this syntax works. Namely, why does wrapping a function in parenthesis and then immediately calling it work?

This says it much better than I can.

Basically the set of parenthesis around the function don't actually do anything... the second set just tell the function to execute (much like String.indexOf will return the method, and String.indexOf() will actually run it.)

Haystack
Jan 23, 2005





Ah, this explains it:

quote:

Given the oddness of the pattern (and lack of widespread understanding), it is very possible for developers to misinterpret this pattern as an actual function. It it recommended that an extra set of parentheses wrap the function definition as well so to provide a visual clue to the developer that the function isn’t a normal function.

I suppose the wrapper parenthesis did it's job, then. :downs:

Anyway, thanks for solving that little mystery for me.

RussianManiac
Dec 27, 2005

by Ozmaugh
Is there an easy way to rotate a div or an image? I did some googling and found http://www.walterzorn.com/rotate_img/rotate_img.htm and http://code.google.com/p/jquery-rotate/.

In Jquery rotate I am having trouble rotating the image about its center.

RussianManiac
Dec 27, 2005

by Ozmaugh
Ok, so I ended up solving my problem using Canvas. What is an equivalent feature in IE i could use?

Supervillin
Feb 6, 2005

Pillbug

RussianManiac posted:

Ok, so I ended up solving my problem using Canvas. What is an equivalent feature in IE i could use?

If the canvas code's already done, adding excanvas to the page would probably be easiest.

If it's exactly 90, 180, or 270 degrees you can actually use CSS (or set CSS with JavaScript):
code:
var element = document.getElementById('thingToRotate');

// no rotation
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';

// 90 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';

// 180 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';

// 270 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
Won't work for arbitrary angles, so excanvas may be your best bet.

RussianManiac
Dec 27, 2005

by Ozmaugh

Supervillin posted:

If the canvas code's already done, adding excanvas to the page would probably be easiest.

If it's exactly 90, 180, or 270 degrees you can actually use CSS (or set CSS with JavaScript):
code:
var element = document.getElementById('thingToRotate');

// no rotation
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';

// 90 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';

// 180 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';

// 270 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
Won't work for arbitrary angles, so excanvas may be your best bet.

excanvas kinda worked, but it fucks up transparency when it renders an image:(

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh
A cursory look at MSDN says the Matrix property should work.

nullfox
Aug 19, 2008

RussianManiac posted:

Ok, so I ended up solving my problem using Canvas. What is an equivalent feature in IE i could use?

VML... Research VML

Here is an old article about it from Sitepoint: http://www.sitepoint.com/blogs/2006/01/03/canvas-for-ie-with-vml/

Tron Paul
Dec 5, 2006

I was considering a new thread for this, but it doesn't really deserve one on second thought. Anyway, I do a bit of Javascript, and I currently use Prototype, with scriptaculous for UI effects.

However, when I look for jobs, and discuss Javascript libraries with other developers, most people seem to prefer jQuery. Looking at the UI effects built-in (I don't think you even need a special external file like with scriptaculous), they seem to be just as good.

So the question here is, is it worth transitioning over to jQuery? Will I get confused since the syntax is similar but not quite the same? Will I be missing anything?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

usingpond posted:

I was considering a new thread for this, but it doesn't really deserve one on second thought. Anyway, I do a bit of Javascript, and I currently use Prototype, with scriptaculous for UI effects.

However, when I look for jobs, and discuss Javascript libraries with other developers, most people seem to prefer jQuery. Looking at the UI effects built-in (I don't think you even need a special external file like with scriptaculous), they seem to be just as good.

So the question here is, is it worth transitioning over to jQuery? Will I get confused since the syntax is similar but not quite the same? Will I be missing anything?

You will wonder why you used prototype for so long.

MrMoo
Sep 14, 2000

Lumpy posted:

You will wonder why you used prototype for so long.

It's not too bad, it's just that jQuery is a lot less cluttered and all the APIs have a standard form. jQuery certainly has more progress these days than Scriptaculous.

Ned
May 23, 2002

by Hand Knit
Switch to jQuery. It is pretty much the standard now.

Kekekela
Oct 28, 2004

usingpond posted:

I was considering a new thread for this, but it doesn't really deserve one on second thought. Anyway, I do a bit of Javascript, and I currently use Prototype, with scriptaculous for UI effects.

However, when I look for jobs, and discuss Javascript libraries with other developers, most people seem to prefer jQuery. Looking at the UI effects built-in (I don't think you even need a special external file like with scriptaculous), they seem to be just as good.

So the question here is, is it worth transitioning over to jQuery? Will I get confused since the syntax is similar but not quite the same? Will I be missing anything?

It gained steam with the Alt.Net crowd then with MSFT itself, so its being used a lot more in the corporate world (from what I can see, anyway). I was using Prototype when we decided to switch over to jQuery at the shop where I was working once we saw the way the wind was blowing as far as the Alt.Net'er/MVP crowd loving on jQuery over Prototype, and I do like it a lot better now. That said, the only thing I've used Prototype for since then was for a UI widgit that Scriptaculous did better (in my opinion) than jQuery UI.

RussianManiac
Dec 27, 2005

by Ozmaugh
is there any sycnrhonizatino in javacsript? Do most browsers implement pure user level threads for JS or do some of them actually might execute in parallel?

MrMoo
Sep 14, 2000

RussianManiac posted:

is there any sycnrhonizatino in javacsript? Do most browsers implement pure user level threads for JS or do some of them actually might execute in parallel?

Check out HTML 5 or Gears for threading support,

http://code.google.com/apis/gears/api_workerpool.html

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

RussianManiac posted:

is there any sycnrhonizatino in javacsript? Do most browsers implement pure user level threads for JS or do some of them actually might execute in parallel?
Javascript was originally explicitly designed to be single-threaded, as the sorts of things it was intended for don't need threads and they vastly complicate things. HTML5 is adding worker threads, but for now no browsers natively support threads in javascript at all.

RussianManiac
Dec 27, 2005

by Ozmaugh
So how do callbacks work? I mean in a situation where you register some onLoad thing or you do the timer like setInterval.

In those cases don't you have multiple threads because you have the main javascript thread and the callbacks should be executed in new threads?

One situation where I thought this could be relevant is in my page where I load many image objects and register onload for all of them, and have a counter for how many images have been succesfully loaded so far. That counter is incremented by the callback for onload for each image, and it is checked if it is certain value. So in this situation there could be no race condition?

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

RussianManiac posted:

So how do callbacks work? I mean in a situation where you register some onLoad thing or you do the timer like setInterval.

Javascript code always runs in a single thread. If you register a callback, the browser notes when that piece of code should next run. It runs it in the javascript thread when it's supposed to, as long as no other javascript code is currently running. It never interrupts an existing javascript execution; there is no "javascript scheduler" that switches between "javascript threads" or anything like that.

In your situation, there will only ever be one callback running at any given time. There can be no race condition. If an image finishes loading while some other javascript code is still running, the callback won't be called until the current javascript finishes.

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL
There is an event queue. Callbacks don't get executed in parallel; they run immediately if nothing else is executing, or else they are scheduled to run when the main thread falls idle again. When you set a timeout or an interval, there is no guarantee that the callback will run exactly at the specified time — you can only provide a minimum wait. Likewise, onload event handlers are not necessarily called at the instant an asset loads, and if many events occur simultaneously their handlers will still execute in a sequence.

oops, beaten to a pulp

RussianManiac
Dec 27, 2005

by Ozmaugh
Thanks for your guys' explanation. It certainly explains a lot.

ynef
Jun 12, 2002
Mozilla usually provides very good documentation: https://developer.mozilla.org/En/Using_web_workers

Note how Workers cannot modify the DOM, which means that they are intended for AJAX handling, calculations, and the like.

Workers are supported in most non-IE browsers, IIRC.

Tron Paul
Dec 5, 2006

Ned posted:

Switch to jQuery. It is pretty much the standard now.

Thanks everyone. Hopefully it won't take too long to transition -- either way though, it will be worth it, apparently.

MononcQc
May 29, 2007

I'm writing my own syntax highlighting regexps for http://learnyousomeerlang.com and everything looks fine in IE8, FF and Safari. However, Chrome and Opera both behave differently and seem to be randomly dropping some stuff.

Is there any difference between the regular expression engines of different js browser implementations? If so, anyone got a lib to fix this (although I'd hate having to include yet more stuff on the page)?

Supervillin
Feb 6, 2005

Pillbug

MononcQc posted:

Is there any difference between the regular expression engines of different js browser implementations?

Not likely. Can you post an example of something that one browser gets but the others don't?

MononcQc
May 29, 2007

Supervillin posted:

Not likely. Can you post an example of something that one browser gets but the others don't?

http://learnyousomeerlang.com/higher-order-functions#anonymous-functions

The code snippet is:

code:
14> c(hhfuns).
{ok, hhfuns}
15> b(hhfuns:a()).
"a/0's password is pony"
In FF, the line "a/0's password is pony" is getting picked up right as 'shell output', but Opera doesn't see it that way and spots it out as a string.

Here are the regexes the plugin uses:

code:
{ regex: new RegExp('^[^0-9].*','gm'), css: 'shell_output'}, // not starting with something like "14> Expression"
{ regex: new RegExp('^[0-9.]+$','gm'), css: 'shell_output'}, // only numbers as output to counterbalance the previous regex
...
{ regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // strings, prebuilt regex by the plugin
They're applied in order, but it sounds like half of the time, chrome and opera will see a string being output to the shell as a string rather than shell output. The other half of the time it does it right.

I've got other examples where it's skipping certain keywords and seeing them as other syntax objects, but I think the example above is enough to show the difference in regexes' results.

Supervillin
Feb 6, 2005

Pillbug

JSLint reports some unescaped characters in those regexes, that ambiguity could lead to the browser differences you're seeing.

The lines it mentions were for not for the shell output regex, but it might make a difference depending on how each browser attempts to correct them. I copied just your shell_output regex and it returns true in Chrome and Firefox:

http://arguments.callee.info/sandbox/regex/ test page, view source.

So if Chrome sees that shell output as a string, it might be testing the regexes in the wrong order. Any way to debug and verify each regex as it's being applied?

Edit: vvv Default settings, I just loaded jslint and pasted the whole script. Stuff like \s came up, which is whitespace in an actual regex but ambiguous in new RegExp(str). Since the argument is a string, \s may be interpreted as whitespace (which is obviously what is intended) or it may be interpreted as an attempt at escaping an s. Inside a string, backslashes need to be escaped, like '\\s'.

Supervillin fucked around with this message at 05:35 on Jan 16, 2010

Munkeymon
Aug 14, 2003

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



If you're using those with the for loop form for(something in somethingElse), Chrome will apply them in whatever order it wants rather than the one you expect. Opera may as well, but I know Chrome does.

Supervillin, what options did you use? I'm not getting any complaints about unescaped characters (nor do I see anything wrong with the expressions myself).

MononcQc
May 29, 2007

I'm digging into the SyntaxHighlighter bug list to see how if anything could cause this but nothing is there. I can't believe I'm the only one with that problem, so I'm suspecting my stuff is wrong.

I'm a bit at a loss. I've just tested with IE6 and IE7 and it looks fine in both too (although I don't support IE6).

I'll try updating to the most recent version (although nothing's mentioned there) and then maybe explore the looping & ordering problems to see if anything could explain this.

That's certainly one of the most hosed up problems I had with javascript.

RussianManiac
Dec 27, 2005

by Ozmaugh
What are the event callbacks for when the javascript just loads and then one for when all the content including images is done? I would like to implement an effect where while the page is loading there is a small graphic playing and I would also probably like to load the graphic(plus javascript animation code) before everything else, then stop it when all content is loaded.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

RussianManiac posted:

What are the event callbacks for when the javascript just loads
You probably want something like "document.ready" which there isn't really any single standard event for it, but libraries like jQuery can handle the cross-browser differences for you.

RussianManiac posted:

and then one for when all the content including images is done?
window.onload fires after everything has loaded


RussianManiac posted:

I would like to implement an effect where while the page is loading there is a small graphic playing and I would also probably like to load the graphic(plus javascript animation code) before everything else, then stop it when all content is loaded.
I think most people would refer to this sort of thing as a "spinner", there's probably some examples out there if you search for that. I think you need to use the Image object. I haven't tried this sort of thing in ages, but I'm pretty sure that instantiating Image in your script blocks until that one is loaded.

peepsalot fucked around with this message at 08:45 on Jan 22, 2010

MrMoo
Sep 14, 2000

RussianManiac posted:

What are the event callbacks for when the javascript just loads

Common hack is to use a <script> element at the end of the page, otherwise use this:

http://api.jquery.com/ready/

mcsquared
Nov 19, 2005

I'm setting about making a carpooling website (very basic). What I'm planning on doing is using the google maps API to plot each user's journey to their workplace, and show as markers other users who are within whatever radius of the journey route. All the lats are gonna be pulled from a database.

Looking through the API quickly, I can't see that this is going to be very simple. Does anyone have any thoughts of either how I could go about achieving this (or something similar to it), or another way of visually displaying users? I'm not particularly bothered about efficiency so I could just plot all users as markers and set the zoom level if all else fails.

RussianManiac
Dec 27, 2005

by Ozmaugh
I am animating a spinning image using canvas. I am using a callback to do so that is called quite frequently and as such the CPU usage is quite high. What is a good way to do simple but smooth animation in javascript without using a very frequent callback?

What I would like to do is just make an image rotate about its center. It works perfect when I just do it using canvas.

anotherone
Feb 8, 2001
Username taken, please choose another one

RussianManiac posted:

I am animating a spinning image using canvas. I am using a callback to do so that is called quite frequently and as such the CPU usage is quite high. What is a good way to do simple but smooth animation in javascript without using a very frequent callback?

What I would like to do is just make an image rotate about its center. It works perfect when I just do it using canvas.

can you just use an animated gif?

RussianManiac
Dec 27, 2005

by Ozmaugh

anotherone posted:

can you just use an animated gif?

That would mean a large file size, no? I am also looking for very smooth animation solution 24+ FPS, ideally 30fps. I can do it with canvas + frequent callback just fine its just that CPU usage gets high, and firefox, due to its lovely JS implementation is especially vulnerable to this.

epswing
Nov 4, 2003

Soiled Meat
Say I have
code:
var map = {};
map['key'] = 'value';
Is there a difference between delete map['key']; and map['key'] = undefined; ?

Edit: I guess there IS a difference:

code:
map = { foo: 0, bar: 0 };
delete map.foo;
map.bar = undefined;

[map.hasOwnProperty('foo'), map.hasOwnProperty('bar')] // [false, true]

epswing fucked around with this message at 23:29 on Jan 28, 2010

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
Date.parse seems to be pretty slow. Does anyone have any well-performing alternative suggestions for parsing RFC 1123 dates?

Supervillin
Feb 6, 2005

Pillbug

epswing posted:

Say I have
code:
var map = {};
map['key'] = 'value';
Is there a difference between delete map['key']; and map['key'] = undefined; ?

Edit: I guess there IS a difference:

code:
map = { foo: 0, bar: 0 };
delete map.foo;
map.bar = undefined;

[map.hasOwnProperty('foo'), map.hasOwnProperty('bar')] // [false, true]

Yeah, more specifically delete unsets the actual property, but assigning undefined leaves the property and unsets its value. Both map.foo === undefined and map.bar === undefined are true after your example, so in most cases there's a literal difference but not a functional difference.

Adbot
ADBOT LOVES YOU

spiritual bypass
Feb 19, 2008

Grimey Drawer
I'm trying to keep track of the URL of a frame on my page. Is it possible to do this with JavaScript?

php:
<?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert($("#inside").toString());
            });
        </script>
    </head>
    <frameset cols="100%" noresize="noresize">
        <frame id="inside" src="content.php">
    </frameset>
</html>
?>
I'm expecting toString() to tell me what's available in that object, but I just keep getting [Object object]
All I really want is the URL. What should I be doing instead?

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