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
The Insect Court
Nov 22, 2012

by FactsAreUseless

Analytic Engine posted:

We use Angular at work and I'm stumped on synchronizing some JS. I have a function that should run after a specific Angular html partial is finished loading, but jQuery's loading functions require URLs of entire html pages.

If you're using ng-include to load the html, it's got an onload attribute that evaluates an expression when the partial is finished loading.

Adbot
ADBOT LOVES YOU

Analytic Engine
May 18, 2009

not the analytical engine

The Insect Court posted:

If you're using ng-include to load the html, it's got an onload attribute that evaluates an expression when the partial is finished loading.

Thanks, I'll try that tomorrow

Karl Sharks
Feb 20, 2008

The Immortal Science of Sharksism-Fininism

e: whoops, just searched for "java", ignore my dumb.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Anyone ever run into random noise being inserted into a jsminified file? I used some random minifier I found in google, and noticed it actually changed my code a little bit.

Nothing devious, just switched out some primitive values for a reason I can't figure.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Raskolnikov2089 posted:

Anyone ever run into random noise being inserted into a jsminified file? I used some random minifier I found in google, and noticed it actually changed my code a little bit.

Nothing devious, just switched out some primitive values for a reason I can't figure.

Did it actually change the behaviour of the code at all? Because the whole point of a minifier is to make the code smaller, and a good one will definitely replace constants with smaller ways of expressing the same thing.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

I want to concat a very large array onto the end of another very large array. Is there something like Array.prototype.concat that modifies the existing array rather than creating a new one? Or should i just write a for loop.

e: I was doing Array.protoype.push.apply(x, y), but I found that if y is too large then you get Maximum call stack size exceeded.

peepsalot fucked around with this message at 03:22 on Feb 2, 2015

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

peepsalot posted:

I want to concat a very large array onto the end of another very large array. Is there something like Array.prototype.concat that modifies the existing array rather than creating a new one? Or should i just write a for loop.

e: I was doing Array.protoype.push.apply(x, y), but I found that if y is too large then you get Maximum call stack size exceeded.

Splice removes and adds elements in place.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Edit: my bad, shows how rarely I use it, it doesn't accept an array. Looking about on stack overflow, the only option looks to be a for loop with push calls, which if you're doing enough may as well create your own function for it.

Maluco Marinero fucked around with this message at 03:30 on Feb 2, 2015

Munkeymon
Aug 14, 2003

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



peepsalot posted:

I want to concat a very large array onto the end of another very large array. Is there something like Array.prototype.concat that modifies the existing array rather than creating a new one? Or should i just write a for loop.

e: I was doing Array.protoype.push.apply(x, y), but I found that if y is too large then you get Maximum call stack size exceeded.

It might be quicker to combine that with 1000-or-so sized slices of the second array in a loop:
JavaScript code:
Array.prototype.append = function(otherArray) {
  for (var i = 0; i < otherArray.length; i += 1000) {
    Array.prototype.push.apply(this, otherArray.slice(i, Math.min(i + 1000, otherArray.length)));
  }
  return this;
}

function makeArray(howBig) { 
  var acc = [];
  acc.length = howBig;
  for(var i = 0; i < howBig; ++i) {
    acc[i] = Math.random()
  }
  return acc;
}

var asd = makeArray(10005);
var zxc = makeArray(10000);
var qwe = asd.append(zxc);
qwe.length; //20005
And you could play with that size constant to get the speed you're looking for.

Munkeymon
Aug 14, 2003

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



I'm trying to nail down detection of localStorage being disabled by poo poo-stupid implementations of privacy features
JavaScript code:
//Chrome throws an exception if you mention it at all eg if (localStorage)
try {
	//IE nulls it
	localStorageAvailable = !!localStorage;
	//Safari throws errors on access
	localStorage['test'];
} catch(eatIt) {
	localStorageAvailable = false;
}//another fantastic browser feature that's not super annoying to deal with at all
Anyone see anything I'm missing?

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
This is how modernizr does it https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

code:
    var mod = 'modernizr';
    try {
      localStorage.setItem(mod, mod);
      localStorage.removeItem(mod);
      return true;
    } catch(e) {
      return false;
    }
I suggest you follow their approach, or better yet use modernizr itself because it's tested and maintained.

mortarr
Apr 28, 2005

frozen meat at high speed
Not sure if this is the right place, or I should post in the datavis thread:

I have a csv of location data with a few other dimensions like date, event type etc, which I'm trying to group by location using hexagonal bins and display on a map. I can load the data ok and using the leaflet.js and leaflet-d3.js libraries over d3 to do the hexbins of my geojson location/point data, which is working ok too. Converting to jsfiddle for a demo and I can't get the tab-separated string bit working in the jsfiddle - loading from a local file is fine.

Now I want to mouse-over the hexbins and get a summary of the contained points properties, but I can't work out how to hook things up so mouse events can fire a function to prepare and display the info. I think the tools I'm using do not have that feature, which is fine, but I'd like to either add it myself, or pick different libraries that do allow that kind of thing.

Here's my code so far, any pointers appreciated.

Munkeymon
Aug 14, 2003

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



v1nce posted:

I suggest you follow their approach, or better yet use modernizr itself because it's tested and maintained.

Yeah, probably. I think I just wanted to rant about how <HTML 5 THING> is just another inconsistent clusterfuck once you actually use it that'll never really be standardized because ~living standard~ or something

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
It bewilders me that in implementing private mode, some browser vendors went gently caress it just break it, instead of say, just splitting out some temporary storage and clearing it when private mode closes. I mean FFS, you already have cookies in private mode, is it that hard to add a key value store you can throw away on session close.

Is there something I'm not getting here? It seems pretty broke and slack from where I'm looking at it.

ArcticZombie
Sep 15, 2010
I don't know if this belongs here or the web dev thread as I don't know where the problem lies. How do you properly handle keypress events on mobile? I have a grid of inputs representing a Scrabble board, on key press I intercept the event and process it appropriately. Either adding a style to the square to make it look like a tile on valid letters, removing previous tiles on backspace or moving around the board with the arrow keys, changing the square in focus accordingly. On Firefox (desktop) this worked fine, I had to switch to intercepting the keydown event to get it working on webkit browsers (they don't fire keypress events for the arrow keys/backspace). But on Firefox (mobile), I can't get this to work.

This is the expected behaviour:



I type H, it checks if it's a valid character, if so add a class to the input and move the focus either to the right or down depending on the current direction. Instead, what I get is this:



The event doesn't get captured for some reason. I can type any character and as many as I want, despite the input having a maxlength of 1. autocomplete and autocapitalize are also disabled and yet they still function. Stranger still, if I type a letter, press the return button in the lower right, delete the character and THEN type it, it works as intended. How does this work!

Munkeymon
Aug 14, 2003

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



Maluco Marinero posted:

It bewilders me that in implementing private mode, some browser vendors went gently caress it just break it, instead of say, just splitting out some temporary storage and clearing it when private mode closes. I mean FFS, you already have cookies in private mode, is it that hard to add a key value store you can throw away on session close.

Is there something I'm not getting here? It seems pretty broke and slack from where I'm looking at it.

I think the idea is to not lie to you about the fact that the storage really just isn't available. It really is pointless because I'm just doing "if local storage available use local storage else use cookies" so hey at least there's a fig leaf of privacy concern!

Munkeymon
Aug 14, 2003

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



mortarr posted:

Not sure if this is the right place, or I should post in the datavis thread:

I have a csv of location data with a few other dimensions like date, event type etc, which I'm trying to group by location using hexagonal bins and display on a map. I can load the data ok and using the leaflet.js and leaflet-d3.js libraries over d3 to do the hexbins of my geojson location/point data, which is working ok too. Converting to jsfiddle for a demo and I can't get the tab-separated string bit working in the jsfiddle - loading from a local file is fine.

Now I want to mouse-over the hexbins and get a summary of the contained points properties, but I can't work out how to hook things up so mouse events can fire a function to prepare and display the info. I think the tools I'm using do not have that feature, which is fine, but I'd like to either add it myself, or pick different libraries that do allow that kind of thing.

Here's my code so far, any pointers appreciated.

Your example doesn't run
http://stackoverflow.com/questions/17341122/link-and-execute-external-javascript-file-hosted-on-github

D3 can bind to a mouseover event
http://stackoverflow.com/questions/10805184/d3-show-data-on-mouseover-of-circle and http://bl.ocks.org/Caged/6476579

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
I have an object array generated from user input.

code:
function userInput(){
	var myArray = [{type: "Foo", amount:20},{type: "Bar", amount:30}];
	return myArray;	
}

var k = userInput()
I have a function later on that does stuff to the amount if a boolean is met:

code:
(function(){
    $.each(k, function(){
        if(this.type === "Foo"){
            this.amount += 10;
        }
     })
}())
How do I retain both the original array values and the updated ones for later comparison/useage?

The only work around I could come up with is just a new instance of userInput, i.e.

code:
function userInput(){
	var myArray = [{type: "Foo", amount:20},{type: "Bar", amount:30}];
	return myArray;	
}

var k = userInput()
var j = userInput();
It seems inefficient but maybe I'm wrong.


fiddle here:

http://jsfiddle.net/rorrzpn4/2/

Raskolnikov2089 fucked around with this message at 00:00 on Feb 4, 2015

RobertKerans
Aug 25, 2006

There is a heppy lend
Fur, fur aw-a-a-ay.

Don't mutate it, just let k = userInput(); let j = mapUserInput()

↓ or do that

RobertKerans fucked around with this message at 01:05 on Feb 4, 2015

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Add an originalAmount/oldAmount/newAmount property to the object that stores either the old amount or the new amount. Then compare amount with oldAmount.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

You can make a new array:

code:
var newk = k.map(function (item) {
        var newItem = {type: item.type, amount: item.amount};
        if(newItem.type === "Foo") {
            newItem.amount += 10;
        }
        return newItem;
    });

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

MDN posted:

The map() method creates a new array...

Thank you. I knew about map, but the whole "new array" thing just wasn't clicking with me.

Wheany posted:

Add an originalAmount/oldAmount/newAmount property to the object that stores either the old amount or the new amount. Then compare amount with oldAmount.

Huh. Now that's interesting.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
Wrapping my head around the Flux way of doing things - am I right in thinking that the "Store" metaphore can be considered as being equivalent to a data access layer? For example, I could put methods a StudentStore such as "getById(int id)" that would run an AJAX request to grab that student from the backend? Is that the right way to handle things?

Fish Ladder Theory
Jun 7, 2005

The Wizard of Poz posted:

Wrapping my head around the Flux way of doing things - am I right in thinking that the "Store" metaphore can be considered as being equivalent to a data access layer? For example, I could put methods a StudentStore such as "getById(int id)" that would run an AJAX request to grab that student from the backend? Is that the right way to handle things?


Stores should generally be fully synchronous.

Generally, a button will trigger an action (or action creator, depending on your terminology), which 1) dispatches STUDENT_LOADING 2) fires the async call to the server with the ID the UI wants to retrieve 3) when loading is finished, either fires STUDENT_LOADED with the data or STUDENT_LOAD_FAILED with the error.

Your studentstore will handle STUDENT_LOADED by picking out/organizing the data from the response that it cares about (the details of the student), then triggering a 'change' event, which is listened to by the view component, which re-renders to reflect the new data.

you might also have a studentLoadingStore which keeps track of which students are currently being retrieved, so you can show loading spinners and load error indicators in the UI.

Fish Ladder Theory fucked around with this message at 05:51 on Feb 4, 2015

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

The Wizard of Poz posted:

Wrapping my head around the Flux way of doing things - am I right in thinking that the "Store" metaphore can be considered as being equivalent to a data access layer? For example, I could put methods a StudentStore such as "getById(int id)" that would run an AJAX request to grab that student from the backend? Is that the right way to handle things?

If I'm not using a Backbone collection as my store, which does ajax via sync, I usually put my AJAX stuff in my ActionCreator as mentioned by Fish Ladder Theory. Ripped from the project I'm working on now:
JavaScript code:
var AuthActions = {
  retrieveTokenFromServer: function (username, password) {
    AppDispatcher.handleViewAction({
      actionType: ActionTypes.LOAD_TOKEN
    });


    AuthDAO.doAuth(username, password)
        .then(
        // success
        function (token) {
          console.info("succesful login", LOG_TAG);
          AppDispatcher.handleServerAction({
            actionType: ActionTypes.TOKEN_RECEIVED,
            token: token
          });
        },

        // fail
        function (oops) {
          console.info("login failure", LOG_TAG);
          AppDispatcher.handleServerAction({
            actionType: ActionTypes.LOAD_TOKEN_FAIL,
            error: oops
          })
        });
  }
}
The AuthDAO object is just a simple wrapper around jquery ajax calls which returns ES6-style Promises.

Sepist
Dec 26, 2005

FUCK BITCHES, ROUTE PACKETS

Gravy Boat 2k
Ahh I cannot figure out how to do this one, maybe one of you guys can help me out. If a particular table cell is > 0 then this array is built:

code:
 
		 var playerid = new Array();
		 	$('#cacheid tr').each(function(row, tr){
							playerid = playerid 
					+ $(tr).find('td:eq(0)').text().trim();
					+ $(tr).find('td:eq(1)').text().trim();
					+ $(tr).find('td:eq(2)').text().trim();
					+ $(tr).find('td:eq(3)').text().trim();
					+ $(tr).find('td:eq(4)').text().trim();
					+ $(tr).find('td:eq(5)').text().trim();
					+ $(tr).find('td:eq(6)').text().trim();
					+ $(tr).find('td:eq(7)').text().trim();
					+ $(tr).find('td:eq(8)').text().trim();
					+ $(tr).find('td:eq(9)').text().trim();
													});
I want to make a loop that for each item in the array, it searches a particular table by class and finds the TD of the TR it is contained in using
code:
$(this).parent().parent();
I can' figure out how to code that one particular part. I'm not that great at coding to begin with so this is a struggle for me. Once I get past this hurdle I'll be fine.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
:psyduck: What is going on with that code? I can't even tell what you're trying to do.

A few notes:
- All those lines end with a semicolon. That ends the statement, so you aren't adding together all those elements. I think only the first line after "playerid = playerid" does anything.
- You can't concatenate arrays with "+". As best as I can tell, even without the semicolons, using a + between arrays will convert them to strings and then concatenate the strings. This isn't what you want (probably? Hopefully.)
- If you're doing the same operation repeatedly then use a for loop.

Sepist
Dec 26, 2005

FUCK BITCHES, ROUTE PACKETS

Gravy Boat 2k
Hmm, I've ran console.log on the array and it shows up in the console. Ultimately what I'm trying to do is find the table row each array string exists in and hide it

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
You'll need to supply some HTML with that so we know what you're trying to do, exactly. I can't really make heads of what you've said so far and your jQuery snippet really doesn't do what you think it does.

PleasureKevin
Jan 2, 2011

is there anything wrong with this module, and should it return the user._id? this is a node.js module BTW.

code:
var User = require( '../models/userModel' ),
	Q = require( 'q' )

module.exports = function getUser ( token ) {
	var deferred = Q.defer()
	
	User.findOne( { token: token }, function ( err, data ) {
		deferred.resolve( data )
	})
	
	return deferred.promise
}
for some reason this returns some type of weird object when i call it like this

code:
getUser = require( '../sweet-mods/get-user' )

getUser( req.token )
.then( someHell )
but calling it this way seems to "work"

code:
getUser = require( '../sweet-mods/get-user' )

var userId = getUser( req.token )

Q.all( [ userId ] ).then( function ( result ) {
	...
})

Sepist
Dec 26, 2005

FUCK BITCHES, ROUTE PACKETS

Gravy Boat 2k

v1nce posted:

You'll need to supply some HTML with that so we know what you're trying to do, exactly. I can't really make heads of what you've said so far and your jQuery snippet really doesn't do what you think it does.

Fair enough. I've worked on it a little anyway so here's an update. I have a table populated from a sql table

code:
<?php
                        foreach($playerlist as $row2){
                            ?>

    <table class="cacheid" id="cacheid">
        <tr>
            <td class="cacheplayer"><?php echo $row2->Player1?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player2?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player3?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player4?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player5?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player6?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player7?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player8?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player9?></td>
        </tr>

        <tr>
            <td class="cacheplayer"><?php echo $row2->Player10?></td>
        </tr>

        <tr>
            <td id="contestid"><?php echo $uniquecontestid ?></td>
        </tr>
    </table><?php } ?>
code:
<table border="0" cellpadding="1" cellspacing="1" class="playerTable" id="playTable">
    <tr>
        <td>Player</td>

        <td>Pos</td>

        <td>Game</td>

        <td>Salary</td>

        <td>FPPG</td>

        <td>Played</td>
    </tr><?php
                            foreach($NBAplayerResults as $row){
                                ?>

    <tr>
        <td id="playerName"><?php echo $row->playerName?></td>

        <td id="position"><?php echo $row->position?></td>

        <td id="game"><?php echo $row->game?></td>

        <td id="salary"><?php echo $row->salary?></td>

        <td id="fppg"><?php echo $row->fppg?></td>

        <td id="gp"><?php echo $row->gamesplayed?></td>

        <td id="addbtn"><img class="add-button" src="http://%3C?php%20echo%20base_url();%20?%3E/images/icon-add.png"></td>

        <td id="playerid" style="display:none;"><?php echo $row->playerID?></td>
    </tr><?php
                            }
                            ?>
</table>
When the contestid td has data in it it fetches this script, this is the part I'm concerned with:

code:

	 if ($('#contestid').length > 0) {
	     $('#cacheid tr td').each(function() {
	                 var cachedplayer = $(this).html();
	                 //get the row
	                 var rowA = $('#playerTable tr td').filter(cachedplayer).parent().parent().trim();

For each td in the cacheid table, I want to match that td cell wit h a td cell in playerTable, and grab that table row and store it as rowA variable.

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
For those playing at home, here's a fiddle of the above: http://jsfiddle.net/kctvkmay/

Let's look at the PHP first.
You may have very good reasons for the way you're handling $playerlist, but personally I wouldn't store something that's enumerated (Player1, Player2, Player3) as object properties. Why? If you add another player to the game (Player 11) then there's like a gazillion places you'll need to update in order to crowbar in that extra player. An added bonus is less code, and less repetition. Remember DRY (Don't repeat yourself).

I'd personally rewrite that to:
php:
<?
foreach($playerlist as $players):
?>
    <table class="cacheid" id="cacheid">
<?php
    foreach($players as $player):
?>
        <tr>
            <td class="cacheplayer"><?php echo $player->id?></td>
        </tr>
<?php
    endforeach;
?>
        <tr>
            <td id="contestid"><?php echo $uniquecontestid?></td>
        </tr>
    </table>
<?php
endforeach;
?>
I've used the foreach: endforeach; notation because it's a little easier on the eyes when doing templates, but that's personal taste.
This also pumps out a list of what i am assuming are Player IDs, because that's what your lookup needs, right? If it's supposed to output player names, then you might want something like this:
php:
<?
<td class="cacheplayer" data-player-id="<?php echo $player->id?>"><?php echo $player->name?></td>
?>
You'll want to have each player backed up by an ID, because if you use names and you have two players with the same name, all sorts of terrible might happen.
These IDs don't need to be stored in a DB or anything, you could literally just make them with a for loop or whatever, so long as they're unique.

Secondly, your NBAPlayerResults table is going to generate something like this:
code:
<table class="playerTable" id="playTable">
    <tr>
        <td>Player</td>
        <td>Position</td>
    </tr>
    <tr>
        <td id="playerName">A</td>
        <td id="position">B</td>
	<td id="playerid" style="display:none;">2</td>
    </tr>
    <tr>
        <td id="playerName">A</td>
        <td id="position">B</td>
	<td id="playerid" style="display:none;">2</td>
    </tr>
</table>
What's wrong here? You can't (shouldn't) use the same ID attribute on multiple elements. You're repeating your use of playerName on multiple rows, and this isn't what IDs are for. IDs are supposed to look up a single element reference.
Instead you can enumerate your properties like this, to enable easy finding in java script:
code:
<table class="playerTable" id="playTable">
    <tr>
        <th>Player</th>
        <th>Position</th>
    </tr>
    <tr data-player-id="1">
        <td data-container="player-name">A</td>
        <td data-container="position">B</td>
    </tr>
    <tr data-player-id="2">
        <td data-container="player-name">A</td>
        <td data-container="position">B</td>
    </tr>
</table>
Notice we're using the repeatable data-* attribute for everything; javascript can look these up super duper easy.
We're also using TH instead of TD for that first row, because TH is TableHeader whereas TD is TableData. You could also add tbody and thead elements, but eh.
We're also using data-player-id in the <tr> in order to avoid the need for that hidden (awful) playerid TD from before. This is much cleaner code that makes the urge to hurt myself go away.

JavaScript!

I still wasn't completely able to understand what it was you wanted to do, but here's what I came up with: http://jsfiddle.net/kctvkmay/1/ Hit the button and view the console for some informative output.

The first portion hits up $cacheTable and creates a "cachedPlayers" array of objects, which are the list of players. This just makes things easier to work with.
The following portion loops over that cachedPlayers array and looks up the associated row in $playerTable, and this enabled us to look at a specific value held in that table.

There's a console.log at the end which outputs the player ID, name, and salary. Notice that Jeff is reported as having an "undefined" salary, because he doesn't feature in the results table.

v1nce fucked around with this message at 04:39 on Feb 5, 2015

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.

PleasureKevin posted:

for some reason this returns some type of weird object when i call it like this

code:
getUser = require( '../sweet-mods/get-user' )
getUser( req.token ).then( someHell )
but calling it this way seems to "work"

code:
getUser = require( '../sweet-mods/get-user' )
var userId = getUser( req.token )
Q.all( [ userId ] ).then( function ( result ) {
	...
})

I'm no node expert, but I'm assuming the promises work the same way as in Angular.

In the second example "userId" is a promise, and the .then() function's "result" should contain your resolved object. Q.all waits for all promises to be resolved before calling .then().
In the first example, it should still work, but "someHell" will be called as a function the same way the second example uses an anonymous function.

Technically speaking, I would expect both of the following to work:
code:
getUser = require( '../sweet-mods/get-user' )

var userPromise = getUser( req.token )
Q.all( [ userPromise ] ).then(function(result) {
    console.log(result);
});

getUser( req.token ).then(function(result) {
    console.log(result);
});
Provided someHell was a function accepting one argument, I would have expected your original code to work just fine, but I am no node expert.

PleasureKevin
Jan 2, 2011

i changed this poo poo and it worked :shrug: . hate it though for some reason

code:

// get-user.js

... 
deferred.resolve( data.id ) //removed underscore in "date._id"
...

// hellController.js

...
Q.all( [ userId ] ).then( function ( result ) {
			Song.find( { $query: { user: result[0] }, $oderby: { added: -1 } // changed "result" to "results[0]"
..

Chas McGill
Oct 29, 2010

loves Fat Philippe
I want to learn how to make interactive infographics, charts etc. An example would be something like this



The top image is what's shown at the start, the user then clicks on one of the bars and the image turns into one of the three below (with a button to return to the top image). It doesn't have to be super fancy, just smooth. I have Edge Animate along with my adobe cloud subscription, but I'm guessing there's a better way to make this kind of thing. I've got a basic understanding of html and css, but Javascript is alien to me. A quick google seems to indicate that I should probably figure out d3.js?

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
Yep, to my mind d3.js is your best bet for something that's interactive , animated and pleasant. The only real limit to d3.js that I'm aware of is, because it uses SVG, it won't work in IE8 and below. You may or may not care about this.

This is from 2012, but here's a nice starter tutorial on d3.js that should give you lots of hints on how to get some of the way to where you want to be.
http://code.hazzens.com/d3tut/lesson_0.html

Once you've got the basics down, you should be able to fudge it together with a cross between these two:
http://bl.ocks.org/mbostock/4061502
http://bl.ocks.org/mbostock/3885304

If you don't know JavaScript, it can be a bit of a dick. A good syntax highlighting editor will go a long way towards saving you from yourself. If you get stuck, come ask questions - sometimes it will be the stupid mistakes that you get stuck on, rather than the technical hurdles.

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.

PleasureKevin posted:

i changed this poo poo and it worked :shrug: . hate it though for some reason

code:
getUser = require( '../sweet-mods/get-user' )
var userId = getUser( req.token );
Q.all( [ userId ] ).then( function ( result ) {
			Song.find( { $query: { user: result[0] }, $oderby: { added: -1 } // changed "result" to "results[0]"
}

Are you just talking aesthetically or what? I tend to break this kind of code up because I love having solid demarcation lines in my code. For instance:

code:
getUser = require( '../sweet-mods/get-user' )

var myThingie = {

    // Resolve all the requirements
    prepareMyStuff: function(req) {
        // Fetch user data
        var userPromise = getUser( req.token );

        // Execute init when resolve complete
        var self = this;
        Q.all( [ userPromise ] ).then(function ( result ) {
            self.initAllTheThings(result);
        });
        // TODO: Add failure catch for resolve being rejected
        // TODO: Add a loader between this and initAllTheThings?
    },

    // Perform init once all items are resolved
    initAllTheThings: function(resolveItems) {
        var user = resolveItems[0];
        Song.find( { $query: { user: user }, $oderby: { added: -1 }
    }
};
You had to use resolve[0] because Q.all will return an array (or object?) of all the items that were resolved. If you only passed one item, you get an array with just one entry.
With the above you can stuff more resolve requests into prepareMyStuff and they'll be passed in to the argument of initAllTheThings. This separates all the required loading/resolving from the actual leg work of your class.

And, while I love doing this, notice how I've managed to write about 5x the amount of code you did. It's entirely personal preference stuff, depending on how much you want to spell out exactly what the code is up to.

Sepist
Dec 26, 2005

FUCK BITCHES, ROUTE PACKETS

Gravy Boat 2k

Hey thanks for this, really appreciate it. It's not quite what I'm looking for but that's totally my fault for not putting in enough data in this post. Player Id's are all unique, it's why I'm using them them to look up players name (referencing cached player id's with player id's in the playertable. Using your code, I would say what I'm trying to store is the row of the playerid found in the player table. Something like this:

code:
var rowA = $playerTable.find("[data-player-id='"+player.id+"']").parent();
Unfortunately when I modify the code to the above (tried adding a second parent) I can't seem to capture the row. I have a working script that captures the row by clicking on a button in the table row, I was trying to duplicate this using player id lookups:

code:
    $(document).on('click', '#playerTable .add-button', function() {
        //get the row
        var rowA = $(this).parent().parent();


Of course after I post this I find the problem with the edited code and now it works, thanks a ton!

Sepist fucked around with this message at 15:00 on Feb 5, 2015

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Chas McGill posted:

I want to learn how to make interactive infographics, charts etc. An example would be something like this



The top image is what's shown at the start, the user then clicks on one of the bars and the image turns into one of the three below (with a button to return to the top image). It doesn't have to be super fancy, just smooth. I have Edge Animate along with my adobe cloud subscription, but I'm guessing there's a better way to make this kind of thing. I've got a basic understanding of html and css, but Javascript is alien to me. A quick google seems to indicate that I should probably figure out d3.js?

In addition to the good advice by v1nce, there is a Data Visualization Thread that might be helpful to you.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I've got a HATEOAS API and I'm using Backbone. What's the right way, or at least a way, to handle an API end point that returns an object that has related objects like:
JavaScript code:
[
    {
        "id": 15,
        "name": "Your Mom",
        "address1": "345 Fucker Lane",
        "address2": "",
        "city": "Sucks",
        "zipcode": "55555",
        "state": "CA",
        "units": [
            "http://0.0.0.0:8100/api/unit/13/",
            "http://0.0.0.0:8100/api/unit/14/",
            "http://0.0.0.0:8100/api/unit/15/",
            "http://0.0.0.0:8100/api/unit/16/"
        ]
    }
]
A backbone collection backed by this endpoint has a bunch of models where the "units" is an array of strings. I guess units should be a collection? Is there a way to make it automatically create a collection from that when I fetch?

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Thermopyle posted:

I've got a HATEOAS API and I'm using Backbone. What's the right way, or at least a way, to handle an API end point that returns an object that has related objects like:
JavaScript code:
[
    {
        "id": 15,
        "name": "Your Mom",
        "address1": "345 Fucker Lane",
        "address2": "",
        "city": "Sucks",
        "zipcode": "55555",
        "state": "CA",
        "units": [
            "http://0.0.0.0:8100/api/unit/13/",
            "http://0.0.0.0:8100/api/unit/14/",
            "http://0.0.0.0:8100/api/unit/15/",
            "http://0.0.0.0:8100/api/unit/16/"
        ]
    }
]
A backbone collection backed by this endpoint has a bunch of models where the "units" is an array of strings. I guess units should be a collection? Is there a way to make it automatically create a collection from that when I fetch?

Something like so in the object Model:

JavaScript code:
 parse: function (response) {
        response.units = new UnitCollection(response.units);
        return response;
    }
will automagically do that for you.

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