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
Maltag
Oct 1, 2007

Valeyard posted:

This is the only place I can post just now, and it was actually relevant since I was yet again battling with trying to get counters to sync up with ajax requests. The solution was to not use counters it seems

Setting aysnch:false still gave me too many problems when it probably shouldn't have

Or more likely I just still don't understand asynchronism too well.

Hey, I have a piece of code for you. Check it out below and tell me what you think.

code:
get { clue }

Adbot
ADBOT LOVES YOU

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.
As awful as this line of logic actually is, it's getting very Slashdot in here

obstipator
Nov 8, 2009

by FactsAreUseless

Valeyard posted:

This is the only place I can post just now

Ahahaha, did you get trained to SH/SC and its subforums?

You must embrace async.

revmoo
May 25, 2006

#basta
Long shot; I need to automatically loop scroll an unordered list with slide movement animation every few seconds that pauses on mouseover. Anybody know of a snippet?

I've tried a few different methods including doing it from scratch and I haven't been happy with the results.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

revmoo posted:

Long shot; I need to automatically loop scroll an unordered list with slide movement animation every few seconds that pauses on mouseover. Anybody know of a snippet?

I've tried a few different methods including doing it from scratch and I haven't been happy with the results.
Mind a quick MSPaint or something so we know exactly what you're looking for?

Valeyard
Mar 30, 2012


Grimey Drawer

Beezy Bee posted:

Stupid Bitch

I am glad that my friends have followed me here :D Also somebody already pointed out that I am infact NOT a Stupid Bitch

obstipator posted:

Ahahaha, did you get trained to SH/SC and its subforums?

You must embrace async.

I am currently trained to SH/SC and Cavern of Cobol, not even YOSPOS is available lol

I am doing everything I can do avoid async :argh:

revmoo
May 25, 2006

#basta

Misogynist posted:

Mind a quick MSPaint or something so we know exactly what you're looking for?

I can do you one better: http://demos.flesler.com/jquery/serialScroll/

Look at the scrolling list example. That's very close to what I need. I can't get SerialScroll or ScrollTo to work though, not sure why. I get function not defined. I'm stuck with old jquery but it's like 1.5 so I'm not sure why it doesn't work.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Valeyard posted:

I am glad that my friends have followed me here :D Also somebody already pointed out that I am infact NOT a Stupid Bitch


I am currently trained to SH/SC and Cavern of Cobol, not even YOSPOS is available lol

I am doing everything I can do avoid async :argh:

wish your posts were async

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Valeyard posted:

Or more likely I just still don't understand asynchronism too well.

This is literally all there is to asychronous functions: callbacks.

If you're having Javascript problems, I feel bad for you son, but probably you're not using enough functions.

JavaScript code:
(function() {
	var callback = function (result) {
		console.log(result);
		put_result_in_some_data_structure(result);
		update_ui(result);		

		restart_timer();
	}
	var set_callback = function () {
		some_asyncronous_function_call(callback);
	}
	var restart_timer = function () {
		setTimeout(set_callback, 1000);
	}
	set_callback();
}());

Valeyard
Mar 30, 2012


Grimey Drawer

Wheany posted:

This is literally all there is to asychronous functions: callbacks.

If you're having Javascript problems, I feel bad for you son, but probably you're not using enough functions.

JavaScript code:
(function() {
	var callback = function (result) {
		console.log(result);
		put_result_in_some_data_structure(result);
		update_ui(result);		

		restart_timer();
	}
	var set_callback = function () {
		some_asyncronous_function_call(callback);
	}
	var restart_timer = function () {
		setTimeout(set_callback, 1000);
	}
	set_callback();
}());

The specific problem this time was trying to have a counter that was being accessed by different callback functions. I figured it out by removing the counters

Another question though, is there some way for me to have console.log() only print to console when I have a debug boolean set to true, or something? If not, could I easily override the function to add this?

revmoo
May 25, 2006

#basta
http://stackoverflow.com/questions/7042611/override-console-log-for-production

Valeyard
Mar 30, 2012


Grimey Drawer

I actually did do a search but...well anyway, thank you very much again :tipshat:

revmoo
May 25, 2006

#basta
Chasing memory leaks. This function leaks dom nodes like crazy:

code:
function getLogs(type) {
        var unsortedLogs = [];
        if (typeof type == 'undefined') {
                // Return all logs
                $.each(deviceLog, function(index, statusType) {
                        $.each(statusType, function(index, logEntry) {
                                unsortedLogs.push(logEntry);
                        });
                });
        } else {
                // Return a specified log status type
                try {
                        $.each(deviceLog[type], function(index, logEntry) {
                                unsortedLogs.push(logEntry);
                        });
                } catch (e) {
                        console.error('getLogs() - Bad argument parameter: ' + type);
                        return false;
                }
        }
        // Sort logs based on unixtime
        return unsortedLogs.sort(function(a,b) {return a.time - b.time});
}
The problem is the call to push(). What can I do to stop this from leaking?

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

revmoo posted:

Chasing memory leaks. This function leaks dom nodes like crazy:

code:

function getLogs(type) {
        var unsortedLogs = [];
        if (typeof type == 'undefined') {
                // Return all logs
                $.each(deviceLog, function(index, statusType) {
                        $.each(statusType, function(index, logEntry) {
                                unsortedLogs.push(logEntry);
                        });
                });
        } else {
                // Return a specified log status type
                try {
                        $.each(deviceLog[type], function(index, logEntry) {
                                unsortedLogs.push(logEntry);
                        });
                } catch (e) {
                        console.error('getLogs() - Bad argument parameter: ' + type);
                        return false;
                }
        }
        // Sort logs based on unixtime
        return unsortedLogs.sort(function(a,b) {return a.time - b.time});
}

The problem is the call to push(). What can I do to stop this from leaking?

Are the logEntrys DOM nodes? If so, copy some information out of them and store that copy instead of the nodes themselves. What happens to the array after it's returned?

revmoo
May 25, 2006

#basta

Subjunctive posted:

What happens to the array after it's returned?

Doh!

revmoo fucked around with this message at 16:04 on Apr 18, 2014

Pollyanna
Mar 5, 2005

Milk's on them.


Is there an easier way to create and add a bunch of elements to the DOM at once? I'm trying to do something like this:

JavaScript code:
function(result) {
	for (var i = 0; i < result.data.length; i++) {
		var table_row = document.createElement('tr');

		for (field in result.data[i]) {
			var table_cell = document.createElement('td');
			var table_contents = document.createTextNode(field);
			table_cell.appendChild(table_contents);
			table_row.appendChild(table_cell);
		}
	}
It seems a bit verbose, though, especially if/when the DOM additions start getting more complicated. What else could I do to cut down on the work required?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
If the structure is easy to reason about you could just create a long HTML string and set that for the table with innerHTML, otherwise templating libraries.

bartkusa
Sep 25, 2005

Air, Fire, Earth, Hope

Pollyanna posted:

Is there an easier way to create and add a bunch of elements to the DOM at once? I'm trying to do something like this:

JavaScript code:
function(result) {
	for (var i = 0; i < result.data.length; i++) {
		var table_row = document.createElement('tr');

		for (field in result.data[i]) {
			var table_cell = document.createElement('td');
			var table_contents = document.createTextNode(field);
			table_cell.appendChild(table_contents);
			table_row.appendChild(table_cell);
		}
	}
It seems a bit verbose, though, especially if/when the DOM additions start getting more complicated. What else could I do to cut down on the work required?

I think you want something called a DomFragment.

E: Doc fragment. gently caress, I knew I got something wrong.

bartkusa fucked around with this message at 13:30 on Apr 19, 2014

Sergeant Rock
Apr 28, 2002

"... call the expert at kissing and stuff..."
Use document.createDocumentFragment - append everything to that, then when it's all in place append the fragment. What's nice about fragments is that they just serve as temporary containers; when you append them they vanish, leaving just the contents you added.

DholmbladRU
May 4, 2006
I have a dynamically added InfoBox on a google map apiv3. When the enableEventPropagation is set to false the scrolling works properly. However if it is set to true, then it will be disabled. Is there anyways to dynamically set the enableEventPropagation if a specific element is clicked/dragged??

code:
new InfoBox({
        content: document.getElementById("infobox-wrapper-hotel"),
        disableAutoPan: false,
        enableEventPropagation: false,


.infoBox #scroll{
  overflow:scroll;
  overflow-x: hidden;
  display:block;
  height:250px;
  width: 300px;
  -webkit-overflow-scrolling: touch;
}
This is scrolling on a ipad device which is causing issues. Does anyone have a solution to this?

edit if you access this jsfiddle on an ipad you will see the issue.

http://jsfiddle.net/LTyB4/

You cannot scroll.

DholmbladRU fucked around with this message at 14:35 on Apr 22, 2014

Valeyard
Mar 30, 2012


Grimey Drawer
code:
$( ".infoBox" ).click(function(event) {
  event.stopPropagation(); 
})
like that?

DholmbladRU
May 4, 2006
I tried the following

code:
$(document.body).on('click touchstart', '.infoBox #scroll', function(){
 	alert('start');
          event.stopPropagation(); 
});
And I see the alert when I click on the #scroll. However event.stopPropagation() doesnt seem to do anything. Again this is on the ipad device

also tried this
code:
iWindow.setOptions({enableEventPropagation:false});
I see why from the documentation " and enableEventPropagation properties have no affect until the current InfoBox is closed and a new one is opened." .....

DholmbladRU fucked around with this message at 15:08 on Apr 22, 2014

Strong Sauce
Jul 2, 2003

You know I am not really your father.





DholmbladRU posted:

I tried the following

code:
$(document.body).on('click touchstart', '.infoBox #scroll', function(){
 	alert('start');
          event.stopPropagation(); 
});
And I see the alert when I click on the #scroll. However event.stopPropagation() doesnt seem to do anything. Again this is on the ipad device


Where is event coming from?

revmoo
May 25, 2006

#basta
I think that function() should be function(event)

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL

DholmbladRU posted:

I tried the following

code:
$(document.body).on('click touchstart', '.infoBox #scroll', function(){
 	alert('start');
          event.stopPropagation(); 
});
And I see the alert when I click on the #scroll. However event.stopPropagation() doesnt seem to do anything. Again this is on the ipad device

also tried this
code:
iWindow.setOptions({enableEventPropagation:false});
I see why from the documentation " and enableEventPropagation properties have no affect until the current InfoBox is closed and a new one is opened." .....

Like revmoo said you need function (event), and it's also going to trigger on both events, which are not simultaneous in iOS devices - click is triggered 300ms after touchstart.

DholmbladRU
May 4, 2006
Thanks for the reply. I ended up solving this by adding the following two eventListners to the scrolling div

code:
  document.getElementById(id).addEventListener("touchstart", function(event) {
                scrollStartPos=this.scrollTop+event.touches[0].pageY;
                event.preventDefault();
            },false);

            document.getElementById(id).addEventListener("touchmove", function(event) {
                this.scrollTop=scrollStartPos-event.touches[0].pageY;
                event.preventDefault();
            },false);
It turns out you cannot stop event propagation dynamically, only when a new InfoBox is opened

mmachine
Jan 5, 2006
A client wants a static site that has a lot of flashy well-animated transitions. I'd love to use a combination of director.js for routing and Handlebars for the templating, though that poses some big concerns regarding SEO. Is there a better routing / template combo I should look into that would be more responsive to having the site get crawled?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

mmachine posted:

A client wants a static site that has a lot of flashy well-animated transitions. I'd love to use a combination of director.js for routing and Handlebars for the templating, though that poses some big concerns regarding SEO. Is there a better routing / template combo I should look into that would be more responsive to having the site get crawled?

Put all the content on screen and use CSS for your animations / transitions? If it's a static site, why would you need templating?

mmachine
Jan 5, 2006

Lumpy posted:

Put all the content on screen and use CSS for your animations / transitions? If it's a static site, why would you need templating?

Ah, my mistake. When I said static what I really meant was no back end / database. The site does have multiple pages, which is what I'm using the Handlebar templating for.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
The HTML5 History APIs are widely-supported, just find a routing engine that knows how to use those instead of hacking it with hashes (or that only hacks it with hashes when the APIs are unsupported).

Or if your setup is literally just a bunch of pages and a fixed map of urls => pages, save yourself the bandwidth and write it yourself instead of pulling in a glorified regex matcher "routing library".

mmachine
Jan 5, 2006

Jabor posted:

The HTML5 History APIs are widely-supported, just find a routing engine that knows how to use those instead of hacking it with hashes (or that only hacks it with hashes when the APIs are unsupported).

By widely supported, do you mean SEO-friendly and responds properly to a request by a crawler?

Jabor posted:

Or if your setup is literally just a bunch of pages and a fixed map of urls => pages, save yourself the bandwidth and write it yourself instead of pulling in a glorified regex matcher "routing library".

I've thought about this too, though for this project doing it that way would probably make the final code super un-maintainable very quickly. This is a front-end heavy design, so from the client's perspective minute details are key, which means a lot of my workflow will encompass lots of minor tweaking and adjustments.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

mmachine posted:

By widely supported, do you mean SEO-friendly and responds properly to a request by a crawler?

Well no, you've got to code that yourself. The History API basically lets you go from example.com/butts to example.com/fart without reloading the page, so you can have clean SEO-friendly URLs while still having slick animations and transitions between pages.

The important thing to remember for SEO is that crawlers don't run javascript on your pages, so you need to be able to render content on your server when asked (which shouldn't be a problem with a reasonable templating system). The best way of implementing what you want is probably to:

1. Use regular links to travel from one page to another. Crawlers know how to follow links.
2. When a browser requests a particular page directly, have the server render the content and serve that page. This is mainly for the benefit of crawlers, but it also means your regular users get faster load times since it's rendered immediately rather than in javascript once everything's been downloaded.
3. When the user clicks on a link on one of your pages, intercept that, cancel the default action, render the new page client-side and replace the URL.

quote:

I've thought about this too, though for this project doing it that way would probably make the final code super un-maintainable very quickly. This is a front-end heavy design, so from the client's perspective minute details are key, which means a lot of my workflow will encompass lots of minor tweaking and adjustments.

None of this seems related to the "mapping urls to pages" part though? I mean if the client wants you rename the "farts" page to "fartz" you're still going to have to tweak the route mapping whether you're using a library or not.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.
"Javascript navigation" and "static site" don't go well together in this context, unfortunately. If you care about SEO, you really should be serving complete documents from the server and doing progressive enhancement.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

mmachine posted:

Ah, my mistake. When I said static what I really meant was no back end / database. The site does have multiple pages, which is what I'm using the Handlebar templating for.

Can't you just use (for example) PHP on the server?

You could make basically static html files with the content and then include them from some central index file, or have multiple files that all include the same headers/footers/whatever decoration.

There's probably some CMSs that don't require a database, if the lack of a database is the big issue.

mmachine
Jan 5, 2006
Thanks everyone -- super solid points and I am convinced JS-powered is not going to fly.

New question: My experience building PHP sites is primarily with very 'flat' pages -- content that shows immediately, with some JS stuff to add flourish or interactions. What would be a good practice for building a PHP-powered site that has a lot of page layout transitions that needs to happen from page to page? All I can think of right now is a JS-init function that runs on each page would show content on each load based on some layout definitions.

revmoo
May 25, 2006

#basta
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.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Another very simple question:

'Write a function named numbers that returns true if all the parameters it is passed are numbers. Otherwise, the function should return false. The function should accept any number of parameters.'

NaN usage is obvious, but I wanted to play with typeof instead. My problem is I don't understand how the following solution is correct:

code:
function numbers(){
	var k = arguments.length;
	for(i=0; i<k; i++){
		if (typeof arguments[i] !== "number"){
		return false;
		}
	}
	return true;
};
If I call:
code:
numbers(1,"a",3);
the if() statement should return "false" on the "a".

However isn't "true" returned regardless? The code runs through the for loop, returns a "false", then jumps to the next code block which returns true no matter what.

How is this correct?

ManoliIsFat
Oct 4, 2002

Raskolnikov2089 posted:

However isn't "true" returned regardless? The code runs through the for loop, returns a "false", then jumps to the next code block which returns true no matter what.

How is this correct?
huh? No, that returns and breaks out of the function. http://jsfiddle.net/xV9tQ/ that fiddle works as expected. Put a breakpoint in your debugger and step through, watch it happen.

ManoliIsFat fucked around with this message at 20:08 on Apr 24, 2014

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

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.


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

Where is the data coming from? Is it being loaded from a server into a browser, or is this all server side node or something? Is there a way that whatever is generating/sending the data can just send do that as a javascript literal instead of one element at a time?

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

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

peepsalot fucked around with this message at 20:21 on Apr 24, 2014

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Raskolnikov2089 posted:

Another very simple question:

'Write a function named numbers that returns true if all the parameters it is passed are numbers. Otherwise, the function should return false. The function should accept any number of parameters.'

NaN usage is obvious, but I wanted to play with typeof instead. My problem is I don't understand how the following solution is correct:

code:
function numbers(){
	var k = arguments.length;
	for(i=0; i<k; i++){
		if (typeof arguments[i] !== "number"){
		return false;
		}
	}
	return true;
};
If I call:
code:
numbers(1,"a",3);
the if() statement should return "false" on the "a".

However isn't "true" returned regardless? The code runs through the for loop, returns a "false", then jumps to the next code block which returns true no matter what.

How is this correct?

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. You might be confusing it with break (docs) which will terminate a loop and continue on.

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