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
biznatchio
Mar 31, 2001


Buglord
Fixed version: http://jsfiddle.net/LQMKn/

You need to declare the observable fields on the AppViewModel that you're binding to the value property of the textboxes so that the textboxes have somewhere to store the values entered into them; then in your addApp action read those observable fields' values (as plain strings) and pass them to your JobApp constructor (which then re-wraps the values as its own observable fields).

Adbot
ADBOT LOVES YOU

Pollyanna
Mar 5, 2005

Milk's on them.


biznatchio posted:

Fixed version: http://jsfiddle.net/LQMKn/

You need to declare the observable fields on the AppViewModel that you're binding to the value property of the textboxes so that the textboxes have somewhere to store the values entered into them; then in your addApp action read those observable fields' values (as plain strings) and pass them to your JobApp constructor (which then re-wraps the values as its own observable fields).

Oh man, that's such an obvious fix. I futzed around with stuff like "$root.addApp" n poo poo and now I feel dumb :downs: Thanks! Kind of a clunky way of doing this, though; I'd have thought Knockout had some sorta helper function to deal with that...

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Can you seriously not debug greasemonkey scripts like a civilized person? Is dumping variables to the console the only way to know what the hell is going on inside a script?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Wheany posted:

Can you seriously not debug greasemonkey scripts like a civilized person? Is dumping variables to the console the only way to know what the hell is going on inside a script?

In Chrome I can go to Sources->Content Scripts->apbdobdcekdieksnciesxksdiskkdsisdi->script.js and see my greasemonkey script and set breakpoints and stuff

In Firefox/Firebug I'm also able to see my script in the sources tab, breakpoints seem to work fine there too

I have // @grant window in my script, not sure if that impacts the ability to use the debugger or not

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

fletcher posted:

In Firefox/Firebug I'm also able to see my script in the sources tab, breakpoints seem to work fine there too

:wtf: I swear I didn't see them there before. But now they're there.

LP0 ON FIRE
Jan 25, 2006

beep boop
I can't seem to get UTF-8 special characters to display in a Javascript source file. If it's Javascript that's on the html file it's fine. I made sure both the html and Javascript were encoded UTF-8 when I saved the files, and that I have the proper markup that I thought I needed.

In my html file's header I have <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

In my script tag I have: <script type="text/javascript" charset="utf-8" src="escape.js"></script>

Again, if I paste my script within the script tags and get rid of the src definition, it works fine. escape.js is encoded UTF-8. What gives?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Maybe your webserver is returning the file with the wrong charset? Check the response headers on the network tab:

LP0 ON FIRE
Jan 25, 2006

beep boop
Thanks. Nothing is listed for a Content-Type.


Connection:Keep-Alive
Date:Sat, 25 Jan 2014 04:02:46 GMT
Etag:"7352e6-7f2-4f0c34a7b2ed6"
Keep-Alive:timeout=5
Proxy-Connection:Keep-Alive
Server:Apache


Only this I guess?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

LP0 ON FIRE posted:

Thanks. Nothing is listed for a Content-Type.

Your browser is falling back to its default encoding, which for me is iso-8859-1

You can probably fix that with some .htaccess or other such server-side fuckery. If all else fails and you must use the utf-8 character and not an escape sequence, use some server-side script like php to serve the javascript and set the content type.

LP0 ON FIRE
Jan 25, 2006

beep boop

Wheany posted:

... use some server-side script like php to serve the javascript and set the content type.

Yes! This worked. Just simply made the html into php and included <?php header('Content-Type: text/html; charset=utf-8'); ?> THANKS!

edit: :doh: It's working in Chrome but not Safari... lame.

Also tried different .htaccess files:

AddType 'text/javascript; charset=UTF-8' js

AddCharset UTF-8 .js

AddCharset UTF-8 .php

LP0 ON FIRE fucked around with this message at 14:48 on Jan 25, 2014

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.
So this is dumb, but I'm working on an application with my team that seems to have randomly stopped logging runtime error messages -- I can [].butt('fart') and the task will abort but not log an error. It's like something is globally catching exceptions. window.onerror is not set. The application is loaded and run through RequireJS.

Any ideas where to start looking?

Bruegels Fuckbooks
Sep 14, 2004

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

Misogynist posted:

So this is dumb, but I'm working on an application with my team that seems to have randomly stopped logging runtime error messages -- I can [].butt('fart') and the task will abort but not log an error. It's like something is globally catching exceptions. window.onerror is not set. The application is loaded and run through RequireJS.

Any ideas where to start looking?

Look to see if someone did:
code:
console.log = function() {}
somewhere. That would turn off all logging.

You can also just intentionally throw a loggable exception, put a breakpoint on it, and step through to see where it goes.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
So I'm building a site at work that uses a lot of javascript. Is there an easier way to work on this at home other than drop-boxing the .js .htm and .css and changing the file destinations to my home pc?

down with slavery
Dec 23, 2013
STOP QUOTING MY POSTS SO PEOPLE THAT AREN'T IDIOTS DON'T HAVE TO READ MY FUCKING TERRIBLE OPINIONS THANKS

Raskolnikov2089 posted:

So I'm building a site at work that uses a lot of javascript. Is there an easier way to work on this at home other than drop-boxing the .js .htm and .css and changing the file destinations to my home pc?

If it's just html, js, and css you should be fine. If you're not, consider it a lesson on why to use relative paths :)

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Raskolnikov2089 posted:

So I'm building a site at work that uses a lot of javascript. Is there an easier way to work on this at home other than drop-boxing the .js .htm and .css and changing the file destinations to my home pc?

Well, I'm not saying it's a universal solution, but it works pretty well for me: I have a web server on my home computer (WAMP) and I have several domains added to different mercurial repositories. The domains are hosted on their own servers, but also mirrored on my PC, under WAMP's www directory in a directory that has the same name as the domain.

So, to develop/test any page, I go to http://localhost/domain.com/some_directory/something.php. Then when I've had done some progress, I push the changes with Mercurial to the actual server, and simply delete the localhost/ from the address bar in my browser's address bar to visit the page on the live site.

And even if you don't want to install a web server, you should still use version control. I've also edited files on one computer in some arbitrary directory, then cloned the repository inside dropbox, let the dropbox directory sync itself onto my other machines, and then clone the repository from the dropbox directory back into some other directory. Then I just push and pull changes from the dropbox repository on both machines (and you could easily add other computers if you need to).

EVGA Longoria
Dec 25, 2005

Let's go exploring!

Raskolnikov2089 posted:

So I'm building a site at work that uses a lot of javascript. Is there an easier way to work on this at home other than drop-boxing the .js .htm and .css and changing the file destinations to my home pc?

I started on my first project depending on Dropbox to sync it. It works, but it's not the most efficient (and many organizations have started blocking Dropbox).

I'd suggest setting up a BitBucket (if it needs to be private) and using git to sync it between the two. It's best practice, instills better habits, and will sync is externally. You can use SourceTree for a Git GUI if your editor doesn't support git natively.

obstipator
Nov 8, 2009

by FactsAreUseless

Wheany posted:

So, to develop/test any page, I go to http://localhost/domain.com/some_directory/something.php. Then when I've had done some progress, I push the changes with Mercurial to the actual server, and simply delete the localhost/ from the address bar in my browser's address bar to visit the page on the live site.

You can also edit your vhosts to make http://local.domain.com/ go to the directory you want. That's what I like to do with all my projects. That way you can put your work poo poo wherever and it Just Works(tm) without having to remember where it is, and base href's won't bother you.

And yeah, version control is a really good idea for any project even if it's just for you on one computer. Having a history you can look back on and undo any mistakes you made a month ago, as well as easily have an updated copy of the project on any computer is so convenient.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

posted:

version control suggestions

I'd been avoiding Git because I don't have any experience with it, but that's no excuse. I just need to suck it up and learn it. Thanks for the suggestions.

excidium
Oct 24, 2004

Tambahawk Soars

Raskolnikov2089 posted:

I'd been avoiding Git because I don't have any experience with it, but that's no excuse. I just need to suck it up and learn it. Thanks for the suggestions.

Here's a real basic free intro.

https://www.codeschool.com/courses/try-git

Pollyanna
Mar 5, 2005

Milk's on them.


This might be a better place to ask: I'm trying to do Ajax with my app, and it doesn't seem to work. This code clip:

JavaScript code:
    self.saveData = function () {
        $.ajax({
            type: "POST",
            url: '/echo/json/',
            data: ko.toJSON(self),
            dataType: 'json'
        });
    };
causes nothing to be posted, and I can't figure out why. Does anyone know why this doesn't work the way I think it should?

Here's a fiddle:

http://jsfiddle.net/s8bTP/

edit: It seems like the MIME type and everything is correct, I just don't get the right data echoed back to me. I output the data I'm sending to the console and it looks correct, it just doesn't actually get sent. This is bizarre.

Pollyanna fucked around with this message at 03:19 on Jan 28, 2014

Peanut and the Gang
Aug 24, 2009

by exmarx
You should learn how to debug your code.

https://developers.google.com/chrome-developer-tools/docs/javascript-debugging
https://developers.google.com/chrome-developer-tools/docs/network

Pollyanna
Mar 5, 2005

Milk's on them.


I was using the Chrome devtools, but it didn't tell me enough to figure out exactly what went wrong. I did fix it now, though:

http://jsfiddle.net/s8bTP/4/

But it still doesn't work well with the non-fiddle app I've got going in Flask. First of all, I have this function for posting data:

JavaScript code:
// Editable Text object:
function EditableText(text, editable) {
    var self = this;
    self.text = ko.observable(text);
    self.editing = ko.observable(editable);
}

// Job app object:
function JobApp(title, description, company, submit_date, link) {
    var self = this;

    self.title = ko.observable(new EditableText(title, false));
    self.description = ko.observable(new EditableText(description, false));
    self.company = ko.observable(new EditableText(company, false));
    self.submit_date = ko.observable(new EditableText(submit_date, false));
    self.link = ko.observable(new EditableText(link, false));

    self.edit = function (model) {
        console.log(model);
        model.editing(true);
    };
}

// Main KO logic:
function AppViewModel() {
    var self = this;

    self.apps = ko.observableArray([new JobApp('Noodle Picker', 'Picks, noodles, and leaves', 'Noodle Pickers, Inc.', '2014-1-25', 'noodlepickers.com'),
    new JobApp('Not A Real Job', 'Not a real job', 'Not A Real Company', '1969-1-1', 'nope.com')]);

    self.addApp = function () {
        self.apps.push(new JobApp('Job Title', 'Description', 'Company', 'Submission Date', 'Link'));
    };

    self.logToConsole = function () {
        console.log(ko.toJSON(self));
    };

    self.saveData = function () {
        $.ajax("{{ url_for('echo') }}", {
            data: ko.toJSON(self), 
            type: "POST",
            contentType: "application/json",
            success: function(result) { alert(result); }
        });
    };
}

ko.applyBindings(new AppViewModel());
The data is fine, but looking in the network tab, it seems that the URL is malformed: %7B%7B%20url_for('echo')%20%7D%7D. I thought that's what you were supposed to do in Flask? I'm so confused :gonk:

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
That's what you're supposed to do in Flask when it's Python code that is being executed server side, but you're in JavaScript land and that code is executed by your browser. JavaScript has no idea about Flask stuff and what url_for() is.

EVGA Longoria
Dec 25, 2005

Let's go exploring!

Pollyanna posted:

This might be a better place to ask: I'm trying to do Ajax with my app, and it doesn't seem to work. This code clip:

JavaScript code:
    self.saveData = function () {
        $.ajax({
            type: "POST",
            url: '/echo/json/',
            data: ko.toJSON(self),
            dataType: 'json'
        });
    };
causes nothing to be posted, and I can't figure out why. Does anyone know why this doesn't work the way I think it should?

Here's a fiddle:

http://jsfiddle.net/s8bTP/

edit: It seems like the MIME type and everything is correct, I just don't get the right data echoed back to me. I output the data I'm sending to the console and it looks correct, it just doesn't actually get sent. This is bizarre.

I'll pick this up here:

1) That's just a submit button submitting a hidden data attribute via post to the Echo, you're not actually calling saveData as far as I can see.
2) That ajax will submit it, but you need to have it console.log the response if you want to see it

http://jsfiddle.net/s8bTP/21/

EVGA Longoria
Dec 25, 2005

Let's go exploring!

Pollyanna posted:


The data is fine, but looking in the network tab, it seems that the URL is malformed: %7B%7B%20url_for('echo')%20%7D%7D. I thought that's what you were supposed to do in Flask? I'm so confused :gonk:

Generally, Templating leaves JS files untouched (since there can be a lot of crossover). You can see if Flask has some way to force this (probably bad practice) or just use a relative url (i.e. '/echo/json/' like fiddle uses)

Pollyanna
Mar 5, 2005

Milk's on them.


I ended up changing the submission deal around and sticking with Ajax. It's easier.

I finally got it to work - it was the url_for issue, which I could have sworn Flask knew how to fix... Also, you have to flask.jsonify() the incoming object. But I should be able to work with this now! Thanks. Now I need to figure out how to write this to a database or something...

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Raskolnikov2089 posted:

I'd been avoiding Git because I don't have any experience with it, but that's no excuse. I just need to suck it up and learn it. Thanks for the suggestions.

You might also want to look into Mecurial (hg). It's a DVCS like git, but with a much saner (at least to me) command set. By no means is git a bad choice, but I found hg much easier to learn and get comfortable with.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Lumpy posted:

You might also want to look into Mecurial (hg). It's a DVCS like git, but with a much saner (at least to me) command set. By no means is git a bad choice, but I found hg much easier to learn and get comfortable with.

Well since someone else already said this, I'm going to second it. Personally I think that Mercurial simply feels better and less janky than git.

Munkeymon
Aug 14, 2003

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



http://jsfiddle.net/dtanders/2RZKT/ Can anyone see a reason that Knockout is ignoring the megabytes member of my objects?

excidium
Oct 24, 2004

Tambahawk Soars

Munkeymon posted:

http://jsfiddle.net/dtanders/2RZKT/ Can anyone see a reason that Knockout is ignoring the megabytes member of my objects?

Stop data-bing'ing it!

Munkeymon
Aug 14, 2003

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



excidium posted:

Stop data-bing'ing it!

Yeah, I just came here to say I noticed it. blargh

honky dong
Sep 2, 2011

Hey Everyone. I have a measure that I'm putting on Qualtrics (web-based survey platform). I need the cursor to default to the text entry box when the page loads. Participants in my study have to go through 60 plus trials and each trial needs to be on a separate page, thus I want the info to appear and have them be able to write a response then click 'enter' without having to use the mouse at all. I figured out the 'press enter to advance' from help I got here some months back. I'm wondering if there's javascript code to be able to focus the cursor in the text box. Any help is greatly appreciated! Here's my code so far:

code:
Qualtrics.SurveyEngine.addOnload(function()
{
	/*Place Your Javascript Below This Line*/
	
	
	
		    var that = this;
    Event.observe(document,'keydown',function(e){
    var choiceID = null;
    if (e.keyCode == 13) //Enter was pressed
        {
    that.setChoiceValue(choiceID,true);
    that.clickNextButton();
    }
	}
  
 

				  
				  
});

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Borderview posted:

Hey Everyone. I have a measure that I'm putting on Qualtrics (web-based survey platform). I need the cursor to default to the text entry box when the page loads. Participants in my study have to go through 60 plus trials and each trial needs to be on a separate page, thus I want the info to appear and have them be able to write a response then click 'enter' without having to use the mouse at all. I figured out the 'press enter to advance' from help I got here some months back. I'm wondering if there's javascript code to be able to focus the cursor in the text box. Any help is greatly appreciated! Here's my code so far:

code:
Qualtrics.SurveyEngine.addOnload(function()
{
	/*Place Your Javascript Below This Line*/
	
	
	
		    var that = this;
    Event.observe(document,'keydown',function(e){
    var choiceID = null;
    if (e.keyCode == 13) //Enter was pressed
        {
    that.setChoiceValue(choiceID,true);
    that.clickNextButton();
    }
	}
  
 

				  
				  
});

document.getElementById('id_of_the_text_box').focus();

If the box doesn't have an id, then if the box has some unique-enough CSS selector: document.querySelector('.maybe-the-class-of-some-parent-element input[type=text]').focus();

Vanadium
Jan 8, 2005

I've fallen backwards into promising to write some ajax-heavy jquery while having no clue about idiomatic javascript, let alone idiomatic asynchronous javascript. For making upwards of 300 POST requests, I ended up with an abomination like

code:
var i = 0;
function go() {
  return $.post(blahblah, data[i]).pipe(
    function(stuff) {
      if (++i >= data.length)
        return;
      else
        return go();
    });
}
go().pipe(next_step)
and it seemed to work pretty well to begin with but after all the POSTs had gone through, Firefox would say "too much recursion" and welp. It seems like my go() function is run with a fairly shallow call stack but then it tries to unwind all the promises and there's just a huge pile of resolve > resolve > resolve frames in the callstack.

On top of that I'd like it not to die if one of the POSTs fails so I can just report what didn't work at the end, but I couldn't really figure out how to go back to a non-error state for the next step in the promise chain once my error callback had been called.

Is there a clever way to avoid deeper and deeper callstacks while chaining asynchronous stuff together like this? I got this particular example to not throw up at me by returning a new Deferred instead of something resulting from calling something on the $.post() object and manually resolving it at the end of this particular set of requests, but that doesn't seem nearly as intuitive or representative of the program flow, and anyway I'm not sure if it really avoids the problem in the general case or if I'm just pushing it down the road a bit.

I'm sure there's cleverer patterns for this but I don't really know where to look. :shobon:

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS
The clever pattern is not making 300 POST requests.

Vanadium
Jan 8, 2005

I don't control that end of the API.

spiritual bypass
Feb 19, 2008

Grimey Drawer
You can avoid the recursion problem by handling this inside a for loop. Use jquery's ajax method synchronously and they'll fire one-by-one as many times as you need. This is going to take loving forever, but it sounds like that's out of your hands :shrug:

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Maybe put all your request parameters into an array or something, then when you get a result, push them into another array and then window.setTimeout(makeTheNextRequest, 0)?

When your parameter-array is empty, you're done.

BigRedDot
Mar 6, 2008

Hey guys, just FYI if you are interested in a canvas-based, performance sensitive library for interactive visualizations I just wanted to mention that we just released Bokeh version 0.4. We wrote it to target the browser from Python, but the JS side of the library is a standalone component that can be used to develop pure web applications. For example, theres' a neat live spectrogram example in the source. Check it out at:

http://bokeh.pydata.org
https://github.com/ContinuumIO/Bokeh

And a growing collection of fiddle examples at:

http://jsfiddle.net/user/bokeh/fiddles/

Adbot
ADBOT LOVES YOU

The Insect Court
Nov 22, 2012

by FactsAreUseless

Vanadium posted:

On top of that I'd like it not to die if one of the POSTs fails so I can just report what didn't work at the end, but I couldn't really figure out how to go back to a non-error state for the next step in the promise chain once my error callback had been called.

Is there a clever way to avoid deeper and deeper callstacks while chaining asynchronous stuff together like this? I got this particular example to not throw up at me by returning a new Deferred instead of something resulting from calling something on the $.post() object and manually resolving it at the end of this particular set of requests, but that doesn't seem nearly as intuitive or representative of the program flow, and anyway I'm not sure if it really avoids the problem in the general case or if I'm just pushing it down the road a bit.

I'm sure there's cleverer patterns for this but I don't really know where to look. :shobon:

Use promises.

code:
var results =  Array.apply(null, Array(300));
results.forEach(function (x, i, a) { 
    var index = i, arr = a; 
    $.ajax("my/stupid/api")
    .done(function (data) {
        arr[index] =data;
    })
    .fail(function (xhr, status, err) { 
        arr[index] = err;
    });
}); 
 

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