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
Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
So I have an express server and then several webservice node.js files.

In my express server I instanitiate a socket:

code:
var io = require('socket.io')(myServer);
Also in my expressServer.js I have lots of routes:
code:
app.get('/public/getNames', require('/dir/getNames.js').getNames);
I want to make my route getNames emit an event on the socket, but I have no idea how to pass my socket I create in express server to my route file. I know this is probably an obvious solution but how would I pass this to my route file appropriately. I imagine I only want one instance of my socket created (in my main server file) correct?

Adbot
ADBOT LOVES YOU

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Has anyone used task.js or js-csp before? They look like pretty interesting approaches to handling async behaviour. I've been playing around with ember-concurrency which is very similar to those but ember specific. Aside from relying on generators, they seem like very neat little constructs.

LP0 ON FIRE
Jan 25, 2006

beep boop
Never mind I'm an idiot.

LP0 ON FIRE fucked around with this message at 20:35 on Mar 3, 2016

DholmbladRU
May 4, 2006
Trying to implement some zoom functionality with a plugin someone made for jquery.

https://github.com/timmywil/jquery.panzoom

If I call:
code:
$panzoom.panzoom('zoom', 2,5);
The zoom works, however I need to use the transitions available in this framework to add a duration. So I am doing something like the following. However what I am not sure of is how I can call zoom in a .on('click') event handler with the transition. Anyone have any idea?


code:
<html>
  <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://timmywil.github.io/jquery.panzoom/dist/jquery.panzoom.js"></script>
  </head>
  <body>
    <section id="contain">
      <h1>Containment within the parent element</h1>
      <div class="panzoom-parent" style="overflow: hidden; position: relative;">
        <img class="panzoom" src="http://blog.millermedeiros.com/wp-content/uploads/2010/04/awesome_tiger.svg" width="900" height="900" style="transform: matrix(0.9, 0, 0, 0.9, -46, 44); backface-visibility: hidden; transform-origin: 50% 50% 0px; cursor: move; transition: transform 200ms ease-in-out;">
      </div>
      
      <div class="buttons">
        <button class="zoom-in">Zoom In</button>
        <button class="zoom-out">Zoom Out</button>
        <input type="range" class="zoom-range" step="0.05" min="0.4" max="0.9">
        <button class="reset">Reset</button>
      </div>
      <script>
        (function() {
          var $section = $('#contain');
          var $panzoom = $section.find('.panzoom').panzoom({
            $zoomIn: $section.find(".zoom-in"),
            $zoomOut: $section.find(".zoom-out"),
            $zoomRange: $section.find(".zoom-range"),
            $reset: $section.find(".reset"),
            startTransform: 'scale(0.9)',
            maxScale: 0.9,
            increment: 0.1,
            contain: true,
            duration:2500
          }).panzoom('zoom', true);
        })();
      </script>
    </section>
  </body>
</html>


Boosh!
Apr 12, 2002
Oven Wrangler
I'm grabbing data from my WordPress JSON feed and it's working except the last bit where I'm assigning the image path. Specifically:

code:
imgPath: data.posts[g].attachments.url
code:
$.ajax({
	url: 'http://mysite.com/?json=1&count=8',
	dataType: 'jsonp',
	async : false,
	success: function (data) {
		var entryArr = [];
		for (g = 0; g < sequenceArr.length; g++) {
                	entryArr.push({
                        title: data.posts[g].title,
                        link: data.posts[g].url,
                        caption: data.posts[g].content,
                        imgPath: data.posts[g].attachments.url
		 });
	}
});
The only difference is that value is nested one extra level.


EDIT:

Got it.

code:
imgPath: data.posts[g].attachments[0].url

Boosh! fucked around with this message at 17:30 on Mar 7, 2016

Geno
Apr 26, 2004
STUPID
DICK
I have a page built using Angular/Bootstrap and a cards UI called BootCards.

On page load, a bunch of cards are loaded via AJAX. Inside each card is a bunch of AJAX calls to fill out the card (let's call it card info). So for example, the user sees 3 cards get loaded and then sees the card info load individually.

I'm trying to figure out a way for the AJAX calls for the card info to only be created after the previous card's AJAX is fully done. For example, card 1 and 2 load but not the card info yet. I don't want the AJAX for card info 2 to be created until the AJAX for card info 1 to be fully done.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Geno posted:

I have a page built using Angular/Bootstrap and a cards UI called BootCards.

On page load, a bunch of cards are loaded via AJAX. Inside each card is a bunch of AJAX calls to fill out the card (let's call it card info). So for example, the user sees 3 cards get loaded and then sees the card info load individually.

I'm trying to figure out a way for the AJAX calls for the card info to only be created after the previous card's AJAX is fully done. For example, card 1 and 2 load but not the card info yet. I don't want the AJAX for card info 2 to be created until the AJAX for card info 1 to be fully done.

You want to use some sort of promise.all() function. Angular's $q service should work fine for this. Basically, take all the individual promises for each card AJAX call, add them to an array, then pass the array to $q.all(). This will give you a promise that is only resolved when all individual promises are resolved, and you get a result array that corresponds to each promise you passed in.

code:
	var promises = [ card1.get(), card2.get() ];
	$q.all(promises).then( function(results) {
		// do get card info ajax calls, either with info from the results array or the original promises array.
	}

Skandranon fucked around with this message at 04:01 on Mar 8, 2016

necrotic
Aug 2, 2005
I owe my brother big time for this!
Promise.all still runs everything asynchronously doesn't it? It sounds like he wants one to complete before another starts, if I'm understanding his post.

Sedro
Dec 31, 2008
In that case you can chain them
JavaScript code:
card1().then(c1 => card2()).then(c2 => card3())
Though I can't imagine why this is desirable

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

necrotic posted:

Promise.all still runs everything asynchronously doesn't it? It sounds like he wants one to complete before another starts, if I'm understanding his post.

Yes, it does. That is usually how you would want to do things. You'll get your cards, then once all cards come back, you'll get your card details. Why would you want to get card1, then card2, then card3, etc? Are you wanting to simulate properly drawing cards from a deck? If so, I'd create a route that lets you "draw 3 cards", which will let the server properly handle pulling 3 cards from the deck, and then return all 3 at once.

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Help, React is trying to kill me




For some reason, my default pageload sets these weird data-reactid's. Switching to other routes gives me normal looking reactids, but the components that should persist (header/footer) keep reloading with the rest, getting new page id's.

After hours of googling Im at a complete loss. I'm using a rendering engine (swig) on the server for these views but Im thinking it must be somethign with the app itself

other relevant code:

code:
//app.js
import React from 'react';
import Header from './Header';
import Footer from './Footer';

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
          {this.props.children}
        <Footer />
      </div>
    );
  }
}

export default App;
code:
//header.js
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header
code:
//header.js  -- footer is the same
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header

Has anyone ever seen reactids like that?

Raskolnikov2089 fucked around with this message at 06:42 on Mar 8, 2016

Kekekela
Oct 28, 2004

Raskolnikov2089 posted:

Help, React is trying to kill me




For some reason, my default pageload sets these weird data-reactid's. Switching to other routes gives me normal looking reactids, but the components that should persist (header/footer) keep reloading with the rest, getting new page id's.

After hours of googling Im at a complete loss. I'm using a rendering engine (swig) on the server for these views but Im thinking it must be somethign with the app itself

other relevant code:

code:
//app.js
import React from 'react';
import Header from './Header';
import Footer from './Footer';

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
          {this.props.children}
        <Footer />
      </div>
    );
  }
}

export default App;
code:
//header.js
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header
code:
//header.js  -- footer is the same
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header

Has anyone ever seen reactids like that?

Could swig be using a different version of react? react-id's got axed recently is one reason I'm thinking that

Mahatma Goonsay
Jun 6, 2007
Yum

Raskolnikov2089 posted:

Help, React is trying to kill me




For some reason, my default pageload sets these weird data-reactid's. Switching to other routes gives me normal looking reactids, but the components that should persist (header/footer) keep reloading with the rest, getting new page id's.

After hours of googling Im at a complete loss. I'm using a rendering engine (swig) on the server for these views but Im thinking it must be somethign with the app itself

other relevant code:

code:

//app.js
import React from 'react';
import Header from './Header';
import Footer from './Footer';

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
          {this.props.children}
        <Footer />
      </div>
    );
  }
}

export default App;


code:

//header.js
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header

code:

//header.js  -- footer is the same
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header

Has anyone ever seen reactids like that?

Raskolnikov2089 posted:

Help, React is trying to kill me




For some reason, my default pageload sets these weird data-reactid's. Switching to other routes gives me normal looking reactids, but the components that should persist (header/footer) keep reloading with the rest, getting new page id's.

After hours of googling Im at a complete loss. I'm using a rendering engine (swig) on the server for these views but Im thinking it must be somethign with the app itself

other relevant code:

code:

//app.js
import React from 'react';
import Header from './Header';
import Footer from './Footer';

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
          {this.props.children}
        <Footer />
      </div>
    );
  }
}

export default App;


code:

//header.js
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header

code:

//header.js  -- footer is the same
import React from 'react'

class Header extends React.Component{
  render() {
    return(
      <div className='header'>
        <div>Header stuff</div>
      </div>
    )
  }
}

export default Header

Has anyone ever seen reactids like that?

If you turn off sever side rendering does it still happen?

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
Funny story, my public assets folder was the cause of it. I'm not sure why, because it was exactly the same, contents, name and all, as the public folder from the tutorial I was using as a boilerplate. The only difference I can think of was that I once renamed it before changing the name to its final form.

Out of anything else to try, and not thinking copying an empty file folder over would make any difference, I deleted my non-working version anyway, and dragged and dropped the folder from the tutorial.

And it started working. Nothing was different, structure, contents, all exactly the same.

I don't understand computers...

Cuntpunch
Oct 3, 2003

A monkey in a long line of kings
Angular 1.4 talk:

A new architecture has been proposed moving forward and it's setting off my something-isn't-right-here sense, but I can't quite place my finger on it.

The idea appears to be that every page/application will stand up 1 or more services(in the angular sense) whose responsibility it is to hold the data model for that application. Then this service will be injected into each controller, such that they all can effectively use the service as a means to bind into the same shared data & state.

An example page for this would be one where the main controller('for the page') is responsible for doing the data-access and populating that model. We'd have a data-grid controller responsible for showing all of these things from that model, and then populating the model with selected rows. We'd have a selected-row detail view, which would bind to the service to display the details of the selected item. Etc.

Am I crazy to find this to be the 'bad' kind of Singleton? The one everyone learns about then abuses wildly when they're learning OO principles because it lets them avoid being concerned about scoping and separation of concerns?

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Cuntpunch posted:

Angular 1.4 talk:

A new architecture has been proposed moving forward and it's setting off my something-isn't-right-here sense, but I can't quite place my finger on it.

The idea appears to be that every page/application will stand up 1 or more services(in the angular sense) whose responsibility it is to hold the data model for that application. Then this service will be injected into each controller, such that they all can effectively use the service as a means to bind into the same shared data & state.

An example page for this would be one where the main controller('for the page') is responsible for doing the data-access and populating that model. We'd have a data-grid controller responsible for showing all of these things from that model, and then populating the model with selected rows. We'd have a selected-row detail view, which would bind to the service to display the details of the selected item. Etc.

Am I crazy to find this to be the 'bad' kind of Singleton? The one everyone learns about then abuses wildly when they're learning OO principles because it lets them avoid being concerned about scoping and separation of concerns?

This isn't as bad as you think. Mainly because there can be no concurrency issues in JavaScript, so the only issue with global variables / singletons in this case is purely an organizational one. That being said, your data services should probably have an actual theme, not just "Page1Service", "Page2Service" in some 1-1 mapping with your main controllers. If you have a data grid of users, you should store the backing data in a service, but in a meaningful way, like an array of User objects. The Controller would then fetch the data, and do the required transformations for representing it in the data grid. You should not store display-centric data in services.

Cuntpunch
Oct 3, 2003

A monkey in a long line of kings

Skandranon posted:

This isn't as bad as you think. Mainly because there can be no concurrency issues in JavaScript, so the only issue with global variables / singletons in this case is purely an organizational one. That being said, your data services should probably have an actual theme, not just "Page1Service", "Page2Service" in some 1-1 mapping with your main controllers. If you have a data grid of users, you should store the backing data in a service, but in a meaningful way, like an array of User objects. The Controller would then fetch the data, and do the required transformations for representing it in the data grid. You should not store display-centric data in services.

What's the harm in letting the inheritence take care of it? PageController does it's data access from service, then the, say, SelectedItemController's template just binds through to PageController's property holding that object. It seems like this would end up removing the complexity of having a service whose entire job is to just exist and hold state.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Ember literally has that by default (well maybe not by default, you have to use ember-data which is heavily promoted so it might as well be default) in the data store service. It's basically a front-end database that's only purpose is to hold on to data, anything that asks for that data or does transformations on that data should be a separate object that only communicates with the store via common interfaces (pushing data, asking for data, creating a new record, etc.). We use a very similar thing at work and it works pretty well. That is, if I'm reading you right, I'm always bad at reading technical object speak.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Cuntpunch posted:

What's the harm in letting the inheritence take care of it? PageController does it's data access from service, then the, say, SelectedItemController's template just binds through to PageController's property holding that object. It seems like this would end up removing the complexity of having a service whose entire job is to just exist and hold state.

Services ARE pretty much there to either hold state, or manage it, or both. I don't see how it's simpler to have SelectedItemController inherit from PageController... either way you're injecting the service into both Controller objects, but in the inheritance case you now have to worry about changes to PageController messing up SelectedItemController. This is also going to make any unit testing you do harder.

Also, if you are passing objects via isolate scope: { thing:"="}, you are not actually passing an object by reference. You are getting a shallow copy and then a $watch set up on both scopes to mirror changes bi-directionally. However, this will probably not work as you expect it to, since watches are looking for memory reference changes on objects, and will fail to notice thing.x changing. You can then use "=*" to have a watchCollection, but this will potentially make your digest cycles very expensive. Fetching the data from a service is probably the best way to ensure you're talking to the same objects, and seems to me the simplest. If PageController & SelectedItemController both need ThingData, why shouldn't they just get it from ThingSource?

necrotic
Aug 2, 2005
I owe my brother big time for this!

Skandranon posted:

Yes, it does. That is usually how you would want to do things. You'll get your cards, then once all cards come back, you'll get your card details. Why would you want to get card1, then card2, then card3, etc? Are you wanting to simulate properly drawing cards from a deck? If so, I'd create a route that lets you "draw 3 cards", which will let the server properly handle pulling 3 cards from the deck, and then return all 3 at once.

I'm not trying to do anything outside of read that guys post, which said

Geno posted:

I'm trying to figure out a way for the AJAX calls for the card info to only be created after the previous card's AJAX is fully done. For example, card 1 and 2 load but not the card info yet. I don't want the AJAX for card info 2 to be created until the AJAX for card info 1 to be fully done.

My intent was to point out that Promise.all does not do what he asked, unless I misread his post (which I didn't).

ModeSix
Mar 14, 2009

I love that people in this thread actually are discussing the very things I learned yesterday. Using common services and factories to handle data instead of fetching it directly from source.

So the next question about that, Skandranon, you mentioned something about = vs =* . This is a new concept for me, so I'll see if I understand it correctly.

Ok, so here's what I have.

In my main app.js I am using the resolve function to pull data from a database, it's named our ever loving dish which I am sure you remember from earlier, and if not, oh well that's it's name.

In my factory/service I have a method to access the data using get or query and returning the data.

In my controller I'm injecting the resolve from app.js into my controller then doing this:

code:
$scope.dish = dish;
Ignoring the fact he's still teaching us to use $scope, are you referring to using $scope.dish =* dish;

What precisely does =* do that = doesn't?

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

ModeSix posted:

I love that people in this thread actually are discussing the very things I learned yesterday. Using common services and factories to handle data instead of fetching it directly from source.

So the next question about that, Skandranon, you mentioned something about = vs =* . This is a new concept for me, so I'll see if I understand it correctly.

Ok, so here's what I have.

In my main app.js I am using the resolve function to pull data from a database, it's named our ever loving dish which I am sure you remember from earlier, and if not, oh well that's it's name.

In my factory/service I have a method to access the data using get or query and returning the data.

In my controller I'm injecting the resolve from app.js into my controller then doing this:

code:
$scope.dish = dish;
Ignoring the fact he's still teaching us to use $scope, are you referring to using $scope.dish =* dish;

What precisely does =* do that = doesn't?

=* is for when you are setting up isolate scope bindings in your directive definition function. See the following function that would define a Directive.

code:
angular.module("DishApp").directive("myDirective",
	function() { return {
		templateUrl: "blah.html",
		controller: "MyController",
		scope: {
			thing1:"=",
			thing2:"=*",
			thing3:"@"
		}
	});	
This would then be used in your html like so <my-directive thing1="x" thing2="y" thing3="z" thing4="a"> </my-directive>

When Angular boots, this would then be replaced with blah.html, a MyController would be created and attached to it, and the scope properties would be filled according to the attributes in my-directive.

scope.thing1 would be copied from the parent scope.x and $watches set up on both sides to synchronize in both directions.

scope.thing2 would be copied from the parent scope.y, but would also apply to all internal properties of y (y.a, y.b, y.c[1]) etc. This requires that for every $digest that is triggered, y is iterated over, the property compared to thing2, and then changed if a change happened. This can get very expensive if y has a lot of properties, or contains a large array.

scope.thing3 would simply be assigned the value of "z"

Edit: Sorry, should have explained that the thing I'm talking about has nothing to do with what you're doing. Your service should just return the promise from your $resource.get() call, and then yes, you would do "$scope.dish = dish". Personally, I would have the Service hold on to the data, and then use $q.when() to EITHER fetch it or return it directly to controllers for use.

Skandranon fucked around with this message at 17:44 on Mar 9, 2016

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
so are there any reasons not to be using es6 and compiling to js? Because it's really just way way better than vanilla JS and aside from the fact that team members are unfamiliar with it (which is a serious consideration) I just can't imagine a reason not to convert.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Yeah, the main thing that gives me pause is tools bullshit. That's the main reason I'm not all Typescript all the time, if the main person you're working with is sometimes JavaScript Front end designer devs, you really need to sort out the toolchain aspect, because JavaScript dev isn't getting any simpler.

As long as the error handling is good and the syntax is documented it's alright, but it's tricky when Babel has lots of different transform options. ES6 is fine but lots of people are opening up forward hoping transforms that are more like 'probably ES7' than 'actually ES7'.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
Yeah, we're a small enough team that the tooling is easy to figure out. We deploy everything as an RPM so it would just be another step in the RPM building process.

And you're right about the ES7 temptation. I am using properties, spread arguments, and whichever one lets you define arrow methods in a class body. I'll probably drop spread attributes because I think they're confusing and I really really hate splats in ruby.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



In terms of toolchain problems, ES6 to ES5 transpilation will probably be the least painful I would think. Almost everything is supporting babel these days.

Or if you aren't developing for the general public you can almost just get away with just writing ES6 in general and not having it transpiled since Chrome supports almost 100% of ES6 natively these days.

Thermopyle
Jul 1, 2003

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

I refuse to not use ES6. It's just so much better. It's weird that I feel that way because it's not like ES6 code is so different its indistinguishable from ES5, but man it sure feels better to write.

I mean, tooling and teams require careful thought, but man if you can work it out, do it.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me
I don't think I could go back to writing pure JS, TypeScript is just too useful, and it really isn't hard to get set up. Investing 1-2 days to set up a good template will pay for itself many times over.

Ghost of Reagan Past
Oct 7, 2003

rock and roll fun
If I'm using ES6 promises, is there a good way to get 'this' into the scope of the promise without something like
code:
var aPointlessVariable = this;
beforehand?

I think Bluebird has a .bind() method that lets you fix the 'this' reference but I'm just using the built-in promises. If it matters this issue comes up in the context of using the fetch API.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Ghost of Reagan Past posted:

If I'm using ES6 promises, is there a good way to get 'this' into the scope of the promise without something like
code:
var aPointlessVariable = this;
beforehand?

I think Bluebird has a .bind() method that lets you fix the 'this' reference but I'm just using the built-in promises. If it matters this issue comes up in the context of using the fetch API.

If you're using ES6 just use an arrow function/lambda, which will automatically 'bind'[1] the function's 'this' to be the 'this' of whatever scope it was created in:

code:
class FartMaker {
    constructor() {
        this.poopy = true;
    }

    makeFart() {
        /* let self = this; */
        return new Promise((resolve, reject) => {
            if (this.poopy) {
                resolve();
            } else {
                reject();
            }
        })
    }
}
[1] It's a bit more pedantic in actuality. The arrow functions don't technically have scopes or something like that. They're not auto-binding the outer this, they just don't have one so they use the one that existed when it was created. This doesn't matter unless you write a JS engine.

piratepilates fucked around with this message at 19:52 on Mar 20, 2016

Thermopyle
Jul 1, 2003

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

Skandranon posted:

I don't think I could go back to writing pure JS, TypeScript is just too useful, and it really isn't hard to get set up. Investing 1-2 days to set up a good template will pay for itself many times over.

While I agree TS is good, it requires a larger buy in from your team than ES6.

Ghost of Reagan Past
Oct 7, 2003

rock and roll fun

piratepilates posted:

If you're using ES6 just use an arrow function/lambda, which will automatically 'bind'[1] the function's 'this' to be the 'this' of whatever scope it was created in:

code:
class FartMaker {
    constructor() {
        this.poopy = true;
    }

    makeFart() {
        /* let self = this; */
        return new Promise((resolve, reject) => {
            if (this.poopy) {
                resolve();
            } else {
                reject();
            }
        })
    }
}
[1] It's a bit more pedantic in actuality. The arrow functions don't technically have scopes or something like that. They're not auto-binding the outer this, they just don't have one so they use the one that existed when it was created. This doesn't matter unless you write a JS engine.
Excellent!

Of course Babel's compiler does the exact same thing I was doing :haw:

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
It's nice that browsers support es6 now, I just used this one-liner in the console to find the magnitude of the biggest earthquake in Finland since 2000:

JavaScript code:
Math.max(...Array.from(document.querySelectorAll("tr > td:nth-child(8)")).map(x => Number.parseFloat(x.textContent)).filter(x => !Number.isNaN(x)))
(I ran it on http://www.helsinki.fi/geo/seismo/maanjaristykset/suomi.html)

The selector I got using the inspector.







It was for an internet slapfight.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Even nicer is that Microsoft decided to jettison old IE and heavily promote new IE, which has autoupdating like Chrome and Firefox. Now the ECMA-262 committee can make changes each year and we won't have to wait 5 years until we can actually use those features.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
If I may code golf a bit, I would replace !Number.isNaN(x) with x === x

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS

Thermopyle posted:

While I agree TS is good, it requires a larger buy in from your team than ES6.

Absolutely this. It's easier to convince your team to write code for the platform rather than inserting a layer of complexity in your build pipeline.

Also, I'm not wild about the way that TypeScript handles modules/namespaces. Really wish it worked a little more like C# where classes that share namespaces get resolved via static analysis rather than having to require everything.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
yeah I like TS but i can't justify it to myself, let alone my team. ES6 is an easier argument to make.

Boz0r
Sep 7, 2006
The Rocketship in action.
Edit: I can't read.

Boz0r fucked around with this message at 10:39 on Mar 23, 2016

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Boz0r posted:

I've been assigned to a Java EE project that noone really knows in-depth. How do I find out if we're using Struts 1 or 2?

Javascript is not Java, you're probably looking for this thread: http://forums.somethingawful.com/showthread.php?threadid=2780384&goto=lastpost

Adbot
ADBOT LOVES YOU

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

Skandranon posted:

scope.thing3 would simply be assigned the value of "z"

My impression is that scope.thing3 would be assigned a function that, when called, returns the value of 'z'. & bindings create a function wrapper according to the documentation.

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