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
Eggnogium
Jun 1, 2010

Never give an inch! Hnnnghhhhhh!

Munkeymon posted:

That would use just as much memory which was what everyone seems to be concerned about.

A DAWG (which is a specialized trie) is the best way to store a list of words for quick membership checking. If it's a static list, the code could be loaded as a pre-built object graph and that would be very quick.

Unless you have a huge list, it's probably not going to be an issue for a modern browser on reasonably fast hardware. Still could be fun to implement if you like to do that sort of thing.

I mistakenly assumed trie was just a typo of tree, as in binary search tree, which would take the same amount of memory (or more) if I'm not mistaken. I learned two new data structures today!

Adbot
ADBOT LOVES YOU

corgski
Feb 6, 2007

Silly goose, you're here forever.

ynohtna posted:

There may be better methods but what I've done before for this in JS is build small iterator objects that allow next/previous node traversal as well as up & down by retaining the current node's path to root.

Thanks, what I ended up doing was using this as the prototype for all the nodes, along with a custom iterator designed to filter on the isNode property. Works surprisingly well for being a dirty hack.

code:
function treeNode() {

    this._parent = {a: null};
    this.isNode = true;

    this.childOf = function (node) {
        this._parent = {a: node};
    }

    this.parent = function() {
        return this._parent.a;
    }

}

Deus Rex
Mar 5, 2005

still trying to get my head around JavaScript's object model... so in general if I'm writing a "singleton" sort of object that doesn't ever need to be instantiated with 'new' I'm fine adding methods directly to the object/function right? like this,

code:
function OneTrueGod() {
  this.name = "Yahweh";
  this.beardColor = "white";
  ...
}

OneTrueGod.smite = function(victim) {
  ...
};

OneTrueGod.smite("Sodom");
but if, on the other hand, I am writing a sort of "class definition" that will be instantiated with 'new' I should be adding methods to the prototype?

code:
function God(name, beard) {
  this.name = name;
  this.beardColor = beard || "shaved";
  ...
}

God.prototype.smite = function(victim) {
  ...
};

var destroyer = new God("Shiva");
destroyer.smite("universe");

angrytech
Jun 26, 2009
My dad has been hinting very strongly that he wants a book on javascript, are there any really awesome resources?

NotShadowStar
Sep 20, 2000
Every object in Javascript can be considered a singleton. The 'new' keyword just returns the object's prototype and isn't actually as useful as it's made out to be. All you need is:

code:
var OneTrueGod = {
  name: "Yahweh",
  beardColor: "white"
  ...
}

OneTrueGod.smite = function(victim) {
  ...
};

OneTrueGod.smite("Sodom");

quote:

My dad has been hinting very strongly that he wants a book on javascript, are there any really awesome resources?

The Crockford book is all you need if you have any experience with any other language.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Deus Rex posted:

still trying to get my head around JavaScript's object model... so in general if I'm writing a "singleton" sort of object that doesn't ever need to be instantiated with 'new' I'm fine adding methods directly to the object/function right? like this,


but if, on the other hand, I am writing a sort of "class definition" that will be instantiated with 'new' I should be adding methods to the prototype?


If you are going to create lots and lots and lots of instances of an object, you use your second example along with new to create them. This has the advantage of not creating instances of member functions for every instance of your object, as it will look to the (single) prototype for it.

If you are creating a singelton, you can either use object literal notation as in NotShadowStar's example, or you can use what is generally called the "Module Pattern" to invoke a self-calling function. The advantage of that is you can have private variables and methods, which you can't do in object literal fashion:

code:
mySingelton = (function () {
   var privateVar, privateFunc;
   privateVar = "oooooh";
   privateFunction = function () {
     return "askdhasd";
   }
   return {
     publicVar: "hi there",
     publicFunc: function () {
        return "wow" + privateFunction();
     }
   }
}());
You can also create objects without doing the whole prototype thing by using functional inheritance.

smug forum asshole
Jan 15, 2005
Do you guys feel like some kind of unit testing suite like QUnit is important for javascript developers to work into their repertoire? I want to be a stronger JS developer, and learning that is something I'm considering.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
This isn't strictly a Javascript question, but is there a way to find the margin of an element if it has not been assigned from javascript?

Example document and java script:
code:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Table</title>
    <style>
div
{
	margin:2px;
	background:pink;
}
    </style>
  </head>
  <body>
	<div id="fff">a</div>
  </body>
</html>
code:
document.getElementById("fff").style.margin

That Javascript snippet is an empty string.

You can find the height and border widths by using offsetHeight and clientHeight, but is there any such trick for margin? This is something that would need to work (only) in FF 3.6, if at all. (:ssh:maintaining poo poo code)

The Merkinman
Apr 22, 2007

I sell only quality merkins. What is a merkin you ask? Why, it's a wig for your genitals!

Wheany posted:

This isn't strictly a Javascript question, but is there a way to find the margin of an element if it has not been assigned from javascript?

Example document and java script:
code:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Table</title>
    <style>
div
{
	margin:2px;
	background:pink;
}
    </style>
  </head>
  <body>
	<div id="fff">a</div>
  </body>
</html>
code:
document.getElementById("fff").style.margin

That Javascript snippet is an empty string.

You can find the height and border widths by using offsetHeight and clientHeight, but is there any such trick for margin? This is something that would need to work (only) in FF 3.6, if at all. (:ssh:maintaining poo poo code)
You should be able to do that in jQuery with.css()

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

The Merkinman posted:

You should be able to do that in jQuery with.css()

Yeah, there is no jQuery. We have MooTools, I could look into that.

OddObserver
Apr 3, 2009
getComputedStyle.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

OddObserver posted:

getComputedStyle.

Yes, thank you.

Magicmat
Aug 14, 2000

I've got the worst fucking attorneys
I'm looking for a JS library that lets me visualize network/force/etc. diagrams, but lets me use HTML objects (e.g., a div) as nodes.

I've seen a few different graphing libraries that do network/force/etc. diagrams, but they render their nodes in their native type, like SVG or <canvas> graphics. I need to use intractable <div>s as the node.

trinary
Jul 21, 2003

College Slice

Magicmat posted:

I'm looking for a JS library that lets me visualize network/force/etc. diagrams, but lets me use HTML objects (e.g., a div) as nodes.

I've seen a few different graphing libraries that do network/force/etc. diagrams, but they render their nodes in their native type, like SVG or <canvas> graphics. I need to use intractable <div>s as the node.

I haven't used it myself, but the approach taken by d3.js might be the thing you're looking for.

http://mbostock.github.com/d3/ex/force.html

Magicmat
Aug 14, 2000

I've got the worst fucking attorneys

trinary posted:

I haven't used it myself, but the approach taken by d3.js might be the thing you're looking for.

http://mbostock.github.com/d3/ex/force.html
But isn't that just a SVG graphic? How would I attach a DIV to those nodes?

trinary
Jul 21, 2003

College Slice
I think I misunderstood what you wanted when giving the recommendation, but d3 might not end up being entirely wrong for your purposes.

The overview page might provide a better description. http://mbostock.github.com/d3/

It's basically a binding system between DOM elements and arbitrary data. SVG is a convenient way to turn that into a visualization, but instead of binding to SVG elements you can bind to whatever DOM elements you want.

In theory, anyway. I don't have any practical experience with it.

SelfOM
Jun 15, 2010
I have a problem I can't figure out in backbone.js and underscore.js.
code:
window.FooApp = Backbone.View.Extend({
     initialize: function(){
         _.bindAll('this', 'addAll');
         this.stuffs = new ABackboneCollection();
         this.stuffs.bind('refresh', this.addAll);
         this.stuff.bind('add', this.addOne);
         this.stuffs.fetch();
     },
     addAll: function(){
         console.log(this); // This works fine
         console.log(this.stuffs); // This does as well with models generated by fetch()
         console.log(this.stuffs.models); // Returns undefined
         this.stuffs.each(this.addOne);  //Doesn't work either
         this.stuffs.create(...); //Works 
     },

     addOne: function(){
     // Renders
}

app = new FooApp();
_ is underscore.js
Calling app.addAll() or just running app.stuffs.each(app.addOne) works as well from the chrome console, however some reason not in a script. So why doesn't the this.stuffs.models work?

I have a very weak foundation in Javascript, so I could be missing something very simple.

Leshy
Jun 21, 2004

I've checked a few pages back, but couldn't find this issue or similar.

I have a page listing multiple contacts at various companies. They're organised in a list, with each company rendered as a 'block' that can be opened or closed with a link through a simple javascript function.

The example is here: example page.

In the spirit of writing unobtrusive javascript, I have a script adding all the ids and hooks that are needed for the toggle function to work. Nearly all of it works perfectly, except for one rather important thing: the actual toggle link itself.

I'm trying to add an onmousedown event to the link which calls the toggle function and passes the variable for that particular company, but for some reason every link ends up passing the variable for the last company in the list instead. Since the ids are getting added properly for each company, this line must be at fault, but I don't know for the life of me why. It does work, except not for the right company.

It's probably because I'm not very good with javascript :(

code:
contactToggle[0].onmousedown = function(){toggleContactLayer(contactID);};
Any help would be appreciated!

Leshy fucked around with this message at 21:55 on Oct 10, 2011

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Leshy posted:

code:
contactToggle[0].onmousedown = function(){toggleContactLayer(contactID);};

All of the contactId's refer to the same variable. At the end of the loop it's "company4", so every toggleContactLayer call gets the same value.

You could do this:
code:
      contactToggle[0].onmousedown = (function(){
	var myId = contactID;
	return function(){toggleContactLayer(myId)};
	})();
Variables in Javascript have function scope, so we create a new function, assign contactID to a variable inside it, then return an inner function which has access to the outer function's variables.

That last line with the parentheses just calls the outer function immediately so that "myId" gets assigned and the inner function created.

PresidentCamacho
Sep 9, 2009
:feelsgood:

PresidentCamacho fucked around with this message at 02:03 on Feb 27, 2012

MonkeyMaker
May 22, 2006

What's your poison, sir?

Leshy posted:

I've checked a few pages back, but couldn't find this issue or similar.

I have a page listing multiple contacts at various companies. They're organised in a list, with each company rendered as a 'block' that can be opened or closed with a link through a simple javascript function.

HTML5's summary/details markup plus the polyfill would be my solution.

Leshy
Jun 21, 2004

Wheany posted:

All of the contactId's refer to the same variable. At the end of the loop it's "company4", so every toggleContactLayer call gets the same value.
I figured something like this must be happening, I'm just not sure why.

On each iteration of the loop, the variable has a different value, so I expected that much like in setting the id of an element, setting the onmousedown event would assign the then current value of the variable. Eg:
code:
<a ... id='contact-company1-toggle' onmousedown='function(){toggleContactLayer("company1");};'>&#9660;</a>
<a ... id='contact-company2-toggle' onmousedown='function(){toggleContactLayer("company2");};'>&#9660;</a>
etc.
instead of
code:
<a ... id='contact-company1-toggle' onmousedown='function(){toggleContactLayer("company4");};'>&#9660;</a>
<a ... id='contact-company2-toggle' onmousedown='function(){toggleContactLayer("company4");};'>&#9660;</a>
etc.
Your solution works perfectly, however, so thanks a lot! I'm still learning this whole javascript thing as I go along, and I couldn't really find a solution for this. Another thing learned!

MonkeyMaker posted:

HTML5's summary/details markup plus the polyfill would be my solution.
That's actually not a bad idea either. Unfortunately the page has to work in MSIE8 and do so pretty much right now, which would require me to use jQuery anyway. As I'm trying to get to grips with how JavaScript works, I'll go with the regular JS solution for now. If I end up doing a lot more or more complicated DOM manipulation, I'd definitely start looking at a framework, most likely jQuery.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Leshy posted:

I figured something like this must be happening, I'm just not sure why.

Inner functions have access to outer function's scope.

Your code has 2+n scopes:
Global scope variables:
var contact, contactID, i, contactCompany, contactHeader, contactToggle, contactContent;

Other scopes:
function toggleContactLayer,
contact.length * anonymous function (the ones you assign to contactToggle[0].onmousedown)

Every one of those anonymous functions has their own scope, but can also access outer (global) variables. So each anonymous function refers to the exact same (global) contactID.

When you assign the onmousedown, the Javascript engine just thinks "that sure is a function". Only when the event fires does the engine care about what happens inside the function. In your case it is simply
toggleContactLayer( (global) contactID). There are several anonymous functions, but only one contactId (the global one).

My example:
code:
contactToggle[0].onmousedown = (function(){
	var myId = contactID;
	return function(){toggleContactLayer(myId)};
})();
On the surface it looks like this: ()();, that is "something inside parentheses (the first set of parentheses), that is to be invoked like a function (the second set of parentheses)".
Well, the first set of parentheses actually contains a function definition, so you're defining an anonymous function and then immediately invoking it.

When you invoke the function, you create a new scope, with the variable "myId". Each myId sits inside its own anonymous scope and gets assigned the current value of the global contactID.
Then, from inside this anonymous scope, you return a new anonymous inner function :eek:. This anonymous inner function gets assigned to onmousedown, and once again the Javascript engine just thinks "that sure is a function".

Finally, when the event fires, the anonymous inner function gets run. Again, it's simply
toggleContactLayer( (the outer function's) myId). There are several outer functions, so there are several myId's :lsd:

quote:

On each iteration of the loop, the variable has a different value, so I expected that much like in setting the id of an element, setting the onmousedown event would assign the then current value of the variable.

No, the code inside function(){} is, well, code. It is evaluated when the function is called. You could have assigned contactToggle[0].onmousedown = function(){toggleContactLayer(thisvariableDoesNotEvenExist)}, and you would only get an error on the mousedown event.

quote:

Your solution works perfectly, however, so thanks a lot! I'm still learning this whole javascript thing as I go along, and I couldn't really find a solution for this. Another thing learned!

Well, I only started to appreciate Javascript's (good) weirdness in the last 6 months or so.

Leshy
Jun 21, 2004

Well, that sure is a thorough explanation! :lsd: indeed.

I do get why it's happening now, though, so once again thanks. Knowing why something is going wrong is usually more instructional than knowing what the fix is :)

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

I have been playing with Javascript a little bit but coming from C/Ruby, everything about the language is strange to me.

I'm making a change to an existing web page where you can choose an object by it's color, red/yellow/blue/orange/green/other. It's using a JQuery accordion view and we're going to get rid of that. Instead there needs to be an alphabetical categorization/search. There's already a search box where you can enter a couple letters of the objects name and that works fine.

What I was going to do is add each letter at the top of the page, and then if you clicked on 'F' it would only show the objects that had names starting with 'F'. I'll probably make a copy of the existing function so that it takes the letter and returns results that start with 'F' instead of contain 'F' (which is how it works now).

I'm stuck on what kind of HTML tag I should make each letter so that when they are clicked, I can pass that letter to the search function.

Right now the code that makes the page is something like:

from A to Z do letter
write <a href='#' id='letter_link'>letter</a>
end

Should I add another property like letter='%letter&' to the <a> tag? Could I think grab it via DOM? Should I put the letter in the 'letter_link' id (letter_link_a, letter_link_b) and parse it out?

I'm just lost and need to buy a JQuery book this week.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Bob Morales posted:

from A to Z do letter
write <a href='#' id='letter_link'>letter</a>
end

Should I add another property like letter='%letter&' to the <a> tag? Could I think grab it via DOM? Should I put the letter in the 'letter_link' id (letter_link_a, letter_link_b) and parse it out?

I'm just lost and need to buy a JQuery book this week.

Are you literally using id="letter_link" for every letter? Because id's are supposed to be unique. I'd use class="letter_link", and then something like id = "letter_a", "letter_b" and so on.

In the onclick handler, your letter would be this.id.charAt(7).

Peanut and the Gang
Aug 24, 2009

by exmarx
This is what data attributes are for
code:
<a href="#" class="letter" data-letter="a">A</a>
<a href="#" class="letter" data-letter="b">B</a>
<a href="#" class="letter" data-letter="c">C</a>

$('.letter').click(function(){
    var letter = $(this).data('letter');
    // do stuff
});

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

Wheany posted:

Are you literally using id="letter_link" for every letter? Because id's are supposed to be unique. I'd use class="letter_link", and then something like id = "letter_a", "letter_b" and so on.

In the onclick handler, your letter would be this.id.charAt(7).

I ended up doing this, thanks.

Keevon
Jun 11, 2002
You know maybe instead of being an angry nerd and writing your paper about how poorly notch wrote a multi million dollar game you could try being productive and write your own game but properly and show him whats what:qq:
I'm curious, is there something wrong with just grabbing the value inside the <a> tag and using that? Why add the extra properties?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Keevon posted:

I'm curious, is there something wrong with just grabbing the value inside the <a> tag and using that? Why add the extra properties?

That would work at least now and in this case. But the first thing that I could think of was if you later change the structure of the page like so: <a href="#"><img src="a.gif"></a>, you'd have to change your javascript as well.

Keevon
Jun 11, 2002
You know maybe instead of being an angry nerd and writing your paper about how poorly notch wrote a multi million dollar game you could try being productive and write your own game but properly and show him whats what:qq:

Wheany posted:

That would work at least now and in this case. But the first thing that I could think of was if you later change the structure of the page like so: <a href="#"><img src="a.gif"></a>, you'd have to change your javascript as well.

Thanks, I was thinking something about how if you had changed the view portion of it your data would break, but in this case I couldn't think of how you might replace the letter since it's a simple case. I certainly understand if it's a much more complex view structure.

This makes sense to me.

az jan jananam
Sep 6, 2011
HI, I'M HARDCORE SAX HERE TO DROP A NICE JUICY TURD OF A POST FROM UP ON HIGH
Anyone have any ideas as to why this code isn't working? http://jsfiddle.net/mGdcm/

HTML-

code:
<a href="#" id="toggleButton">toggle</a>
<div id="toggleSection" style="opacity:0;">
    Why isn't this working?
</div>
Javascript-

code:
$('#toggleButton').click(function() {
    if ($('#toggleSection').css("opacity") === 0) {
        $('#toggleSection').fadeIn("slow");
    }
    else {
        $('#toggleSection').fadeOut("slow");
    }
    return false;
});

az jan jananam fucked around with this message at 02:11 on Oct 18, 2011

OddObserver
Apr 3, 2009
Because css("opacity") returns a string, as a 5-second test using typeof would show.
Also, you really should be beware of equality-testing floating point numbers exactly --- not that it's the issue here.

Edit: woops, didn't see the link --- so you're using mootools and not jQuery? Under mootools $('#toggleButton') evaluates to null.

OddObserver fucked around with this message at 02:36 on Oct 18, 2011

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
This works: http://jsfiddle.net/mGdcm/23/

1. I included the jQuery framework.
2. When jQuery completes a fadeOut it sets the target element's display property to "none" and resets it's opacity to 100. Thus, testing for display none will correctly choose the fadeIn path. (Personally, I'd add a marker class to the element after it's completed the fade out and check for that.)
3. Check your browser's JavaScript error console: "TypeError: 'null' is not an object (evaluating '$('#toggleButton').click')"

ynohtna fucked around with this message at 02:42 on Oct 18, 2011

smug forum asshole
Jan 15, 2005
I want to play with Javascript and gain a better understanding of how the language works by writing a few object prototypes and playing with language features like closures. Is there anything like irb (ruby) for JavaScript, or would my best choice for this kind of exploration be my web developer tools console?

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen

smug forum rear end in a top hat posted:

I want to play with Javascript and gain a better understanding of how the language works by writing a few object prototypes and playing with language features like closures. Is there anything like irb (ruby) for JavaScript, or would my best choice for this kind of exploration be my web developer tools console?

http://jsfiddle.net in conjunction with your browser's web developer tools is a good start for interactive exploration.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

az jan jananam posted:

Anyone have any ideas as to why this code isn't working? http://jsfiddle.net/mGdcm/

HTML-

code:
<a href="#" id="toggleButton">toggle</a>
<div id="toggleSection" style="opacity:0;">
    Why isn't this working?
</div>
Javascript-

code:
$('#toggleButton').click(function() {
    if ($('#toggleSection').css("opacity") === 0) {
        $('#toggleSection').fadeIn("slow");
    }
    else {
        $('#toggleSection').fadeOut("slow");
    }
    return false;
});

Because opacity doesn't have anything to do with the end state of the element after fadeOut or fadeIn, and as was pointed out, even if it did, you are testing for it wrong. Plus, look at the example I posted in the jQuery thread when you asked your very similar question there about using the "toggle" variants of effects to avoid writing extra code.

Munkeymon
Aug 14, 2003

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



ynohtna posted:

http://jsfiddle.net in conjunction with your browser's web developer tools is a good start for interactive exploration.

If you just want to poke at the JavaScript language without messing with HTML, there's also http://jsconsole.com/ and http://www.jconsole.com/

az jan jananam
Sep 6, 2011
HI, I'M HARDCORE SAX HERE TO DROP A NICE JUICY TURD OF A POST FROM UP ON HIGH

Lumpy posted:

Because opacity doesn't have anything to do with the end state of the element after fadeOut or fadeIn, and as was pointed out, even if it did, you are testing for it wrong. Plus, look at the example I posted in the jQuery thread when you asked your very similar question there about using the "toggle" variants of effects to avoid writing extra code.


Thanks!

Adbot
ADBOT LOVES YOU

Boz0r
Sep 7, 2006
The Rocketship in action.
I'm trying to make checkboxes that can change the border of a table and it works perfectly in Chrome, Firefox and newer IEs, but in IE 6 and 7 it's giving me beef.

code:

    element.attr("onClick","updateBorder(this)");
    element.onclick = "updateBorder(this)";
    alert("onClick " + element.attr("onClick"));

this is the bit that's giving me trouble. I have an alert as the very first thing in the updateBorder function, and it's never called on older IEs. How do I fix this?

EDIT: element is a JQuery element. Probably a little relevant.

Boz0r fucked around with this message at 15:47 on Oct 19, 2011

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