Skip to content

Instantly share code, notes, and snippets.

@richistron
Last active March 30, 2016 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richistron/b7ceec6707c33c30f9807108c0cdce2a to your computer and use it in GitHub Desktop.
Save richistron/b7ceec6707c33c30f9807108c0cdce2a to your computer and use it in GitHub Desktop.
This was a presentation

Javascript FAQS

js

How can I create a function which only runs just one time?

I have a method that is running multiple times and I'm not sure why. Since this method does a ajax call, I don't want to fetch the same data twice.

Closure

'use strict';

var myMethod = (function() {
  var lock = false;
  return function(){
    if (!lock) {
      lock = true;
      console.log('this code only runs one time');
    }
    console.log('myMethod doing stuff');
  };
})();

myMethod();
myMethod();

Singleton

'use strict';

var myObjectConstructor = function() {
  var myObject,
  constructor = function(){
    console.log('this stuff only runs one time');
    var foo = true,
    bar = 'yay';
    return {
      foo: foo,
      bar: bar
    };
  };
  myObject = myObject || constructor();
  return myObject;
};

console.log(new myObjectConstructor());
console.log(new myObjectConstructor());

How can a bind a click event one time a remove it when it has been clicked?

I'm using jQuery and I want to know how to attach a click event listener and remove it when it's done.

jQuery Bind/Unbind

'use strict';

var $el =  $('body'),
eventHandler = function() {
  console.log('click');
  $el.unbind('click', eventHandler);
};
$el.bind('click', eventHandler);

How can wait for multiple promises to run some code?

I'm using angular and I have to do 3 $http calls but I'm not sure how can I make it work.

Promises.all

'use strict';

var promises = [];

promises.push($http.get('url1'));
promises.push($http.get('url2'));
promises.push($http.get('url3'));

Promises.all(promises).then(function(){
  console.log('yay');
}, function(){
  console.log('awwww man');
});

How can I prevent hoisting?

Is there a way to prevent hoisting from happening and what it is.

Hoisting

var holi = 'holi :D';

function sayHoli(){
  console.log(holi);
  var holi = 'jelou :v';
  console.log(holi);
}

sayHoli();

Prevent Hoisting

Scope A local variable can have the same name as a global variable, but it is entirely separate; changing the value of one variable has no effect on the other. Only the local version has meaning inside the function in which it is declared.

'use strict';

var holi = 'holi :D';

function sayHoli(){
  console.log(holi);
  holi = 'jelou :v';
  console.log(holi);
}

sayHoli();

Thanks!!

  • Join us at the #javascript channel for support.
  • Asking is better than failling.
  • You are not alone!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment