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
Tres Burritos
Sep 3, 2009

revmoo posted:

Can someone explain in a simple way what is the fastest way to append an object onto a JS array? I've seen a ton of benchmarks proving different things and I'm having a hard time deciding which method is fastest. I'm working on an app now that does around a million of these types of operations per minute and will need to scale to probably 5 million so even slight performance increases will be noticeable.

I think that if you're doing this much processing, browser side / JS maybe isn't the place to do it. What kind of performance are you getting now?

Adbot
ADBOT LOVES YOU

revmoo
May 25, 2006

#basta

peepsalot posted:

Are you sure that array appending is where you program is spending most of its time? Are you profiling your code?

Yes, quite a bit actually. The app is a live mapping application that renders thousands of dots in real-time with events and also has a logging backend so there is a whole lot of dynamic things happening on a relatively tight polling interval. The app is pretty watertight at this point, I've spent the last few days going through and fixing bottlenecks, and it runs extremely smoothly now, I'm just looking for the last of the low-hanging fruit. After looking at those benchmarks in different browsers, it looks like the best compromise in my situation is the arr.length method. I could use push() and get slightly better performance in Chrome but I'm not sure it's worth it.

I think at this point the only additional speedups I'd see would be to find a better way to search arrays rather than just looping over them. It seems like there should be a smarter way to locate specific objects in an array based on their contents than just looping over the whole thing, but I have no idea.

Reality
Sep 26, 2010

revmoo posted:

Yes, quite a bit actually. The app is a live mapping application that renders thousands of dots in real-time with events and also has a logging backend so there is a whole lot of dynamic things happening on a relatively tight polling interval. The app is pretty watertight at this point, I've spent the last few days going through and fixing bottlenecks, and it runs extremely smoothly now, I'm just looking for the last of the low-hanging fruit. After looking at those benchmarks in different browsers, it looks like the best compromise in my situation is the arr.length method. I could use push() and get slightly better performance in Chrome but I'm not sure it's worth it.

I think at this point the only additional speedups I'd see would be to find a better way to search arrays rather than just looping over them. It seems like there should be a smarter way to locate specific objects in an array based on their contents than just looping over the whole thing, but I have no idea.

I don't know how well it would work with the amount of data your using, but I've been basically appending properties to my array of things where the value is the index of the data. My data sets are much, much smaller than yours.
code:
SampleArray[uniqueid]=index
var someVal = SampleArray[SampleArray[uniqueid]] 
As long the uniqueid isn't an index of something you won't be overwriting data. But again, I don't know how well this would work with the amount of data your using since that would be a lot of property assignments. Should probably store it in a separate object that isn't the array though.

Munkeymon
Aug 14, 2003

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



Reality posted:

I don't know how well it would work with the amount of data your using, but I've been basically appending properties to my array of things where the value is the index of the data. My data sets are much, much smaller than yours.
code:
SampleArray[uniqueid]=index
var someVal = SampleArray[SampleArray[uniqueid]] 
As long the uniqueid isn't an index of something you won't be overwriting data. But again, I don't know how well this would work with the amount of data your using since that would be a lot of property assignments. Should probably store it in a separate object that isn't the array though.

Just want to pipe up and mention that I did something like that a long time ago and it became a maintenance nightmare. This was before even half good debuggers were available, though, so it might be less :psyboom: these days. Keeping a second object around to store indexes (or even object references) might be less annoying in the long run.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Ok yeah I was thinking break. That clears up a lot, thanks folks.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

peepsalot posted:

If you don't trust others' benchmarks then maybe do your own? There's probably a lot of variation depending on which js vm you are running in.

Here's one with quiet a few different ideas: http://jsperf.com/adding-items-array/12

You might also want to look into typed arrays if you want more speed https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

You can't store object references in typed arrays. It would be a security nightmare.

It also matters how big your array is: when it exceeds capacity, it'll be reallocated, which often involves copying the data. Depending on how much work you do per element, that can be meaningful. Pre-sizing arrays can work in surprising ways, because engines usually have a limit beyond which they either don't preallocate at all, or clamp the size of the storage.

I'd say to use a[length] = newThing; because it will keep you in the hot generated-code path except for the storage growth case (in all engines I'm familiar with). Calling out to a native incurs a meaningful overhead, though it's distorted in the micro benchmark case. The advice to measure your workload is wise, though.

Edit: you can use Array.prototype.indexOf for object identity, but for contents you want a secondary index for sure. I'm not sure how else the problem can be approached, independent of the language.

Subjunctive fucked around with this message at 22:37 on Apr 24, 2014

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Lumpy posted:

return will end the execution of a function immediately regardless if you are in a loop, switch or whatever as soon as it's hit.

In fact, jslint will complain about this pattern:

JavaScript code:
if (condition) {
	return someValue;
} else {
	return somethingElse;
}
Instead it wants you to use
JavaScript code:
if (condition) {
	return someValue;
}
return somethingElse;
because the else is redundant in this case.

Fish Ladder Theory
Jun 7, 2005

Anyone willing to look over some code and comment? This is my first real project with JS, so I'm not sure if I'm doing anything horribly wrong.

The repo is at https://github.com/olslash/impressive-tweets... relevant is impressive-tweets.js and home.html

There's a demo up at http://pacific-citadel-5007.herokuapp.com

Thank you kind goons

edit: I especially need help with my twitter API search calls... for example result_type=recent doesn't seem to do anything (I get results from 2008 and 2014 mixed together) and language=en doesn't either (i get a lot of Japanese results).

edit: I refactored quiet a bit in the last few hours, in case anyone had looked.

Fish Ladder Theory fucked around with this message at 08:09 on Apr 25, 2014

o.m. 94
Nov 23, 2009

I'm writing a 'lil incremental game ala Cookie Clicker and the like, and I want to try and hide some of the upgrades from the end user. At the moment, the details are stored in plaintext JSON on the server, so I'm restricting access to the file - but the problem is I have to parse and load the file as an object into memory with JSON.parse() at some point, which means anyone could inspect the object to reveal spoilers about content.

Is there a way I can access just a section of the file given say, an id number, so that the entire contents aren't revealed in some way?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
The only way you can not tell people about a thing is to not tell them about it. That means having the server have some ability to not tell them about it.

TildeATH
Oct 21, 2010

by Lowtax

Suspicious Dish posted:

The only way you can not tell people about a thing is to not tell them about it. That means having the server have some ability to not tell them about it.

Yeah, if it's client side, we will find it and give ourselves infinite lollipops. But that's okay.

Pollyanna
Mar 5, 2005

Milk's on them.


I'm trying to figure out a good way to get the values of everything under a certain "branch" level in a Javascript object. I have this object:

JavaScript code:
var tree = {

    branch1-1: {

        branch1-1-1: {

            branch1-1-1-1: int,

            branch1-1-1-2: int,

            branch1-1-1-3: int,

},

        branch1-1-2: {},

        branch1-1-3: {}

},

    branch1-2: {

        branch1-2-1: {},

        branch1-2-2: {},

        branch1-2-3: {}

},

    branch1-3: {

        branch1-3-1: {},

        branch1-3-2: {},

        branch1-3-3: {}

}

};
You really only need the entire first branch to get the idea. It's something akin to three branches, each with three branches, each with three branches. Basically, I'm trying to make a function that will return the values of everything at a given branch level. Like, I will need the sum of the leaves of branch 1-1, or the sum of the leaves of branch 1-1-1, or just the value of branch 1-1-1-1. Does this method have a particular name?

Anyway, I tried making this function (slightly different, sorry about that) in jQuery:

code:
function getSkills(tree) {

    // Finds and returns skill names and points
    
    $.each(char_data, function(field, skillset) {
    
        $.each(field, function(skillset, skill) {
        
            $.each(skillset, function(skill, points) {
            
                console.log(skill + ": " + points);
            
            } );
        
        } );
    
    } ); 

}

getSkills(char_skills);
but running it gives me Uncaught TypeError: Cannot use 'in' operator to search for '5' in social. I've used it with other objects before, and this method worked fine. I'm not sure why it doesn't, now. Am I approaching this wrong? Is there an easier way to say "get me everything under the branch named x"?

Sorry if this doesn't make a whole lot of sense, I'm surprisingly inept at Javascript.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Pollyanna posted:

I'm trying to figure out a good way to get the values of everything under a certain "branch" level in a Javascript object. I have this object:

[snip]

but running it gives me Uncaught TypeError: Cannot use 'in' operator to search for '5' in social. I've used it with other objects before, and this method worked fine. I'm not sure why it doesn't, now. Am I approaching this wrong? Is there an easier way to say "get me everything under the branch named x"?

Sorry if this doesn't make a whole lot of sense, I'm surprisingly inept at Javascript.

I think you will have to post the actual function and not some work-alike, as well as the actual data you're using. Or at least some actual runnable code and data that reproduces your problem. Your examples are a bit too vague.

My guess is that your javascript object doesn't have the structure what you expect it to be.

Pollyanna
Mar 5, 2005

Milk's on them.


Wheany posted:

I think you will have to post the actual function and not some work-alike, as well as the actual data you're using. Or at least some actual runnable code and data that reproduces your problem. Your examples are a bit too vague.

My guess is that your javascript object doesn't have the structure what you expect it to be.

Sorry. Here's a JSFiddle of exactly what I'm doing:

http://jsfiddle.net/PUaHT/8/

(It outputs some debugging data into the console right now, sorry about that.)

I made two functions for traversing through the first and second branches, which currently have a big-O factor of "pathetic". I'm wondering if there's some changes to the data structure I can make to change that...

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Pollyanna posted:

Sorry. Here's a JSFiddle of exactly what I'm doing:

http://jsfiddle.net/PUaHT/8/

(It outputs some debugging data into the console right now, sorry about that.)

I made two functions for traversing through the first and second branches, which currently have a big-O factor of "pathetic". I'm wondering if there's some changes to the data structure I can make to change that...

I'm still not sure what exactly you are trying to do, but maybe this? I added underscore.js as an external resource and I use reduce and isObject functions from it.

http://jsfiddle.net/PUaHT/14/

Here is the relevant snippet:
JavaScript code:
var skillsetSum = function (skillset) {
    return _.reduce(skillset, function (memo, value) {
        if (_.isObject(value)) {
            return memo + skillsetSum(value);
        }
        return memo + value;
    }, 0);
}
That will return the sum of all values in an object, or if the values are objects, the sum of their values (recursively, to any depth).

If you want to access the value of a single skill, just use the dot notation: char_skills.social.royal_demeanor.composure

If you want to access the value of a single skill and you don't know where in the tree it is, then you will have to search for it and performance will be poo poo.

Geisladisk
Sep 15, 2007

I need to create a page that presents a lot of tabular data; Basically, a CSV file with several hundred thousand entries. I'd like the user to be able to filter, search, etc. I haven't done anything in this style before, and I'm wondering if there are any frameworks or libraries made for this sort of thing to make my life easier. Can anyone point me in the right direction?

obstipator
Nov 8, 2009

by FactsAreUseless

Geisladisk posted:

I need to create a page that presents a lot of tabular data; Basically, a CSV file with several hundred thousand entries. I'd like the user to be able to filter, search, etc. I haven't done anything in this style before, and I'm wondering if there are any frameworks or libraries made for this sort of thing to make my life easier. Can anyone point me in the right direction?

Datatables is really awesome and will probably work well:
https://datatables.net/

However I don't know how well it would handle tons of data. It does have ajax loading if you do have tons of data, but that's more server side effort.

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL
Several hundred thousand records is gonna be chunky no matter how you dice it, unless you're displaying a portion at a time and using asynchronous storage to retrieve it (websql or indexeddb). Datatables will do what you want but the size of the array will be an issue.

emoji
Jun 4, 2004
Crossfilter is fast if your data fits it.

Dominoes
Sep 20, 2007

I'm new to JS. Does anyone have experience with the gmaps API? Is there a way to automatically check and uncheck form checkboxes after the page is mostly finished loading?

I have a gmaps API page with various overlay, such as polygons, polylines and symbols. Each has an associated text label, made using a custom overlay I adapted from the answer to this Stack Overflow post

The overlays are stored as an object called 'overlays' with layout 'description: [polyline, customoverlaylabel]'


Checkbox example code:
HTML code:
<input type="checkbox" id="sun" onclick="refreshCheck('sun')">Sun</input>
This is how I sync whether a display is hidden or visible to the checkbox:
JavaScript code:
  function refreshCheck(overlay) {
                var box = document.getElementById(overlay).checked
                var lines = overlays[overlay][0]
                var text = overlays[overlay][1]
                lines.setVisible(box, overlay)
                if (box === true) {
                    text.show()
                }
                else {
                    text.hide()
                }
            }
This code refreshes all the checkmarks, at the end of the javascript head.
JavaScript code:
var overlayNames = []
for (var k in overlays) overlayNames.push(k)
for (var o in overlayNames) refreshCheck(overlayNames[o])
The result: On page load, the actual overlays (polylines, polygons, markers etc - the built in API objects) work correctly. They are displayed based on the default checkbox states. However, the labels are all displayed, regardless if their check box was set by default. If I cycle the checkboxes, everything works correctly.

Here's the hide method of the custom text overlay:
JavaScript code:
               TxtOverlay.prototype.hide = function(){
                    if (this.div_) {
                        this.div_.style.visibility = "hidden";
                    }
                }
It's failing the if (this.div_) check, and not doing anything. If I remove the check, it produces an error since this.div_ doesn't exist.

Here's what the bulk of the custom overlay code looks like, for reference. I don't really understand it:
JavaScript code:
  function TxtOverlay(pos, txt, cls, map){
                // Now initialize all properties.
                this.pos = pos;
                this.txt_ = txt;
                this.cls_ = cls;
                this.map_ = map;

                // We define a property to hold the image's
                // div. We'll actually create this div
                // upon receipt of the add() method so we'll
                // leave it null for now.
                this.div_ = null;

                // Explicitly call setMap() on this overlay
                this.setMap(map);
            }

            TxtOverlay.prototype = new google.maps.OverlayView();

            TxtOverlay.prototype.onAdd = function(){

                // Note: an overlay's receipt of onAdd() indicates that
                // the map's panes are now available for attaching
                // the overlay to the map via the DOM.

                // Create the DIV and set some basic attributes.
                var div = document.createElement('DIV');
                div.className = this.cls_;
                div.innerHTML = this.txt_;

                // Set the overlay's div_ property to this DIV
                this.div_ = div;
                var overlayProjection = this.getProjection();
                var position = overlayProjection.fromLatLngToDivPixel(this.pos);
                div.style.left = position.x + 'px';
                div.style.top = position.y + 'px';
                // We add an overlay to a map via one of the map's panes.

                var panes = this.getPanes();
                panes.floatPane.appendChild(div);
            }
            TxtOverlay.prototype.draw = function(){

                var overlayProjection = this.getProjection();

                // Retrieve the southwest and northeast coordinates of this overlay
                // in latlngs and convert them to pixels coordinates.
                // We'll use these coordinates to resize the DIV.
                var position = overlayProjection.fromLatLngToDivPixel(this.pos);

                var div = this.div_;
                div.style.left = position.x + 'px';
                div.style.top = position.y + 'px';

                }
Let me know what you think! I think I need a way to do the initial refresh after this.div_ is created, but I'm not sure how to do that.

Dominoes fucked around with this message at 11:41 on Apr 29, 2014

Pollyanna
Mar 5, 2005

Milk's on them.


Wheany posted:

I'm still not sure what exactly you are trying to do, but maybe this? I added underscore.js as an external resource and I use reduce and isObject functions from it.

http://jsfiddle.net/PUaHT/14/

Here is the relevant snippet:
JavaScript code:
var skillsetSum = function (skillset) {
    return _.reduce(skillset, function (memo, value) {
        if (_.isObject(value)) {
            return memo + skillsetSum(value);
        }
        return memo + value;
    }, 0);
}
That will return the sum of all values in an object, or if the values are objects, the sum of their values (recursively, to any depth).

If you want to access the value of a single skill, just use the dot notation: char_skills.social.royal_demeanor.composure

If you want to access the value of a single skill and you don't know where in the tree it is, then you will have to search for it and performance will be poo poo.

I figured it out using jQuery. JSFiddle here, but the question now is if the way I made the data structure will play nice with React :gonk: Cause I don't wanna have to make components for each subset of data when the entire point of frameworks like this is modularity and sticking to DRY principles.

aBagorn
Aug 26, 2004
I have a (probably retarded) knockout question.

I'm trying to get hip with the times and make my web apps more snappy and nice by doing client side binding and moving more towards Single Page Applications and whatnot. Problem is I'm very bad at javascript, apparently. I have a search that I want to use knockout with, in the following way. Tell me if there are any glaring errors:

JavaScript code:
function ApplySearchViewModel(node) {
    
    var SearchPageViewModel = {
        resultsArray: [],
        updateResults: function () {
            var self = this;
            var searchParams = GetSearchParams();
            $.getJSON('SearchResults', { JSONParams: JSON.stringify(searchParams) }, function (data, status, xhr) {
                self.resultsArray = ko.mapping.fromJS(data)
            });
        }
    }
    ko.applyBindings(SearchPageViewModel, document.getElementById(node));
}
In my html, I have the following, nested within the same node:

HTML code:
<button data-bind="click: updateResults" id="searchIncidents">Search</button>
Which is working nicely. With firebug opened up I can see immediately that the $.getJSON is being called, woohoo! I check the console to make sure that the return is a nice JS array, and turns out it is! So far, so good. Which brings us to the table that is supposed to be updated

code:
<tbody data-bind="foreach: resultsArray">
The table is never being populated. Am I doing something wrong when I instantiate my viewModel?

Chill Callahan
Nov 14, 2012
Pretty sure you have to make resultsArray an observable array.

Fish Ladder Theory
Jun 7, 2005

I'm skimming over some slides on JS basics, which I'm pretty familiar with already, just making sure I'm not missing anything. There's one concept that he keeps going back to that's kind of confusing to me: treating arrays and function as objects like this:

code:
var ary = [];
ary['keyname'] = 'someval';
and similarly
code:
var a = function(){};
a['keyname'] = 'someval';
Now I see that you can retrieve these keys in both instances, like console.log(ary.keyname) and could technically store data this way, but is this ever done? Is there any reason I wouldn't just use a generic object for this behavior?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Fish Ladder Theory posted:

I'm skimming over some slides on JS basics, which I'm pretty familiar with already, just making sure I'm not missing anything. There's one concept that he keeps going back to that's kind of confusing to me: treating arrays and function as objects like this:

code:
var ary = [];
ary['keyname'] = 'someval';
and similarly
code:
var a = function(){};
a['keyname'] = 'someval';
Now I see that you can retrieve these keys in both instances, like console.log(ary.keyname) and could technically store data this way, but is this ever done? Is there any reason I wouldn't just use a generic object for this behavior?

"It depends", but for all intents and purposes, you'd always use a plain object. My guess is that the person is trying to reinforce the "everything is an object"-ness of javascript.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Seems bad for arrays but for functions I could see it in node where you set a property as a subclass of the main constructor/function

aBagorn
Aug 26, 2004

Chill Callahan posted:

Pretty sure you have to make resultsArray an observable array.

This didn't help. Array is still coming back but not populating the table.

Munkeymon
Aug 14, 2003

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



aBagorn posted:

This didn't help. Array is still coming back but not populating the table.

You have to add stuff to the observable array, not replace it.

JavaScript code:
ko_array.unshift(thing);
ko_array.push(thing);
If you have a lot of things to add to your array, you should limit the notification rate to keep the page from drawing too much.

Vicar
Oct 20, 2007

Are you actually inserting the results into the observable array? You can't do

code:
resultsArray = resultsArray: ko.observableArray(),
updateResults = function () {
    this.resultsArray = ["Alice", "Bob"];
}
as that would just replace the observable array with a regular array. You have to do:
code:
resultsArray = resultsArray: ko.observableArray(),
updateResults = function () {
    this.resultsArray(["Alice", "Bob"]);
}
Here's a jsfiddle:
http://jsfiddle.net/8rgxW/1/

edit: welp, beaten

Ether Frenzy
Dec 22, 2006




Nap Ghost
I have a question about setting cookies - does anyone know if it's even possible to cookie a user so that he's rendered a different domain's site in a no-mobile (desktop) state?

Like, for instance - set the cookie on page load on a http://adserver.company.com location that links users to http://www.company.com but tell them to only be served the desktop site when they get there, regardless of device? (our mobile team shat the bed and forgot a pretty major feature in their product, so in the rush to not play the blame game they're dumping all the work on my group who doesn't normally write cookies.)

I can't seem to find googled consensus that you can go cross-domain like this reliably, and being pretty unfamiliar with cookies I'm not even sure where to start attempting and I'd rather skip the fun of trying if it's not even doable.

*I am not 100% sure that http://adserver.company.com is a fully a 'subdomain' of http://www.company.com, so that further muddies my searching.*

This is what I'm using and it's working on my http://adserver.company.com pages, showing up as set with the correct value and expiry date, but as soon as the user moves on to the http://www.company.com pages, it's lost (and they get the broken mobile site.)

code:
<script>
function setCookie()
{
var d = new Date();
d.setTime(d.getTime()+(30*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = "nomobile=1; "+expires;
}
</script>
So if anyone who actually knows what they're doing can show me what to add (if this action is even possible) I'd be super grateful.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
adserver.company.com and www.company.com are both subdomains of company.com so you don't have to worry about cross-domain anything (which is good because cross-domain cookies do no exist).

Take a look at the domain attribute of the cookie string. You'll want to specify domain=.company.com so the cookie can be used by all subdomains of company.com.

aBagorn
Aug 26, 2004

Munkeymon posted:

You have to add stuff to the observable array, not replace it.

JavaScript code:
ko_array.unshift(thing);
ko_array.push(thing);
If you have a lot of things to add to your array, you should limit the notification rate to keep the page from drawing too much.

Vicar posted:

Are you actually inserting the results into the observable array? You can't do

code:
resultsArray = resultsArray: ko.observableArray(),
updateResults = function () {
    this.resultsArray = ["Alice", "Bob"];
}
as that would just replace the observable array with a regular array. You have to do:
code:
resultsArray = resultsArray: ko.observableArray(),
updateResults = function () {
    this.resultsArray(["Alice", "Bob"]);
}
Here's a jsfiddle:
http://jsfiddle.net/8rgxW/1/

edit: welp, beaten

You guys are awesome, thanks! Now I'm off to figure out how to 'paginate' the table that comes back with a quasi-infinite scrolling function

Ether Frenzy
Dec 22, 2006




Nap Ghost

fletcher posted:

adserver.company.com and https://www.company.com are both subdomains of company.com so you don't have to worry about cross-domain anything (which is good because cross-domain cookies do no exist).

Take a look at the domain attribute of the cookie string. You'll want to specify domain=.company.com so the cookie can be used by all subdomains of company.com.

Thanks... read through that and it made sense but I'm still not having any luck making the domain definition work correctly, I still haven't ruled out the fact that our redirect process is dropping out the cookie even if I DO have it set correctly here. F'n mobile team.

StateOwned
Dec 30, 2005

this lane closed
I'm new to javascript/jquery and this one is tough to google

when i do this:

var foo = $(selector);

afterwards, what's the difference between foo and $(foo) ?

I'm noticing some jquery functions work on either and some only work on $(foo).

o.m. 94
Nov 23, 2009

foo is a jQuery object, and $(foo) is a jQuery object with a jQuery object as the argument (instead of a selector string):

http://jsfiddle.net/eLP9p/2/

o.m. 94 fucked around with this message at 21:35 on May 8, 2014

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

StateOwned posted:

I'm new to javascript/jquery and this one is tough to google

when i do this:

var foo = $(selector);

afterwards, what's the difference between foo and $(foo) ?

I'm noticing some jquery functions work on either and some only work on $(foo).

Read the API docs, they're actually pretty good: http://api.jquery.com/jQuery/

Once you have a jQuery object (which is what foo should be in your case), you should not need to pass it into $ again. Doing so will create a clone of the jQuery object, as the link above explains.

aBagorn
Aug 26, 2004
Another day, another stupid knockout question from me:

When I change my viewModel from an object literal to a function, it no longer works. For example, if I call this

JavaScript code:
function GetIncidentGeneralInfo(incidentID, node) {
    $.getJSON('IncidentInformation', { IncidentID: incidentID }, function (data, status, xhr) {
        var generalViewModel = { };
        generalViewModel = ko.mapping.fromJS(data);
        ko.applyBindings(generalViewModel, document.getElementById(node));
    });
}
I get back the data in the correct places based on my bindings. However, I wanted to be able to give the viewModel more functionality, like the ability to handle a post request. So I swapped out the literal for this:

JavaScript code:
function ApplyGeneralViewModel(incidentID, node) {
    var generalViewModel = function () {
        var self = this;

        this.Incident = ko.observable();
        this.Employee = ko.observable();


        this.initializeData = function (incID) {
            $.getJSON('IncidentInformation', { IncidentID: incID }, function (data, status, xhr) {
                self.Incident(data.Incident);
                self.Employee(data.Employee);
            });
        }

        this.updateEmployee = function (employeeName){
            $.getJSON('GetEmployee', { EmployeeName: employeeName }, function (data, status, xhr) {
                self.Employee(data);
            });
        }

        this.savetoServer = function (incID, buttonID) {
            var incident = ko.toJSON(self.Incident);
            var employee = ko.toJSON(self.Employee);
            $.post('SaveIncident', { IncidentID: incID, JSONIncident: incident, JSONEmployee: employee, button: buttonID }, function (data, status, xhr) {
                self.initializeData(data);
            });
        }
    }
    var model = new generalViewModel();
    model.initializeData(incidentID);

    ko.applyBindings(model, document.getElementById(node));
}
To allow the user to swap the employee out for another one and have the relevant information populate, as well as to save the incident information to SQL.

What am I doing wrong in the second part. I changed nothing else about the application, I just called ApplyGeneralViewModel() rather than GetIncidentGeneralInfo().

This is what the console comes up with:

code:
Uncaught TypeError: Unable to process binding "value: function (){return Employee.EmpName() }"
Message: undefined is not a function
edit: so I was able to get the viewModel working as a function if I wrap in inside the $.getJSON call. I guess it was trying to apply the bindings before the data was initialized?

2nd edit: when I hit the savetoServer function and call self.initializeData, it's giving me an "undefined is not a function" error at the self.Incident(data.Incident) line

aBagorn fucked around with this message at 20:14 on May 9, 2014

stoops
Jun 11, 2001
I have a textfile with lines like this: (about 65000 lines, 6 columns)

1 0.500 -89.500 725.330 88.743 -66.551
2 1.500 -89.500 725.359 88.744 -66.543
...

64799 358.500 89.500 800.325 271.256 66.543
64800 359.500 89.500 800.370 271.257 66.551


What I need to do is read that text file and then do a search for the line that closely matches the numbers in the 2nd and 3rd columns.
I don't know much javascript, so apologies for that. (I did this in php with a preg_split. Is there something like that in javascript?)

Is it faster if I put each line in an array like this and then search thru those arrays?

arrayLine 0 (1, 0.500, -89.500, 725.330, 88.743, -66.551)
arrayLine 1 (2, 1.500, -89.500, 725.359, 88.744, -66.543)

Currently, all I have is the reading of the text file into a variable. Any point in the right direction would help.

spiritual bypass
Feb 19, 2008

Grimey Drawer

stoops posted:

I did this in php with a preg_split. Is there something like that in javascript?

Not sure how to answer the rest of your question from the top of my head, but here's a start on that string split: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Javascript splits strings with either another string or regex from the same method. It's really nice.

Adbot
ADBOT LOVES YOU

obstipator
Nov 8, 2009

by FactsAreUseless
Yeah, go with what rt4 said and split the entire huge variable on linefeeds

JavaScript code:
var arr = contents.split('\n');
Do the 2nd and 3rd rows always follow the pattern of +1 for the 2nd until it hits360, then loops back to 0 and increments the 3rd row by 1? If so, you can do some math to figure out which row in the array has the line you want.
Something like this (untested and probably mathematically wrong for your data):

JavaScript code:
function getLine(x, y) {
  var xOffset = Math.round(x - 0.5);
  var yOffset = Math.round(y - 0.5) + 90;
  return arr[nearestY * 180 + nearestX];
}
What I'm doing there is converting the input x and y to offsets of the lowest coord for the 2nd and 3rd columns, so that the first row of (0.5, -89.5) gives xOffset = 0, yOffset = 0. Then do math on that to find which row matches. This assumes that the x increments by 1 and when it loops past 360, it increments y by 1.


e: copied a line but forgot to change the variables in it.

obstipator fucked around with this message at 22:07 on May 9, 2014

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