Wednesday, 12 August 2015

How do closures work in Javascript

How do closures work in Javascript


Question: What is closures?
Whenever you defined a the function within another function, the inner function has access to variables in the outer function.


Following are Simple example of closure.
function mainFunction(outerData) {
  var mainFuncData = 3;

  function innerFunction(innerFuncData) {
    console.log(outerData + innerFuncData + (++mainFuncData)); // will alert 16
  }

  innerFunction(10);
}

mainFunction(7); //17


Question: Why it can access to variables in the outer function?
Because It is defined as var , which means it is global variable.

Tuesday, 11 August 2015

How to logout from facebook with javascritp SDK - FB.logout


How to logout from facebook with javascritp SDK - FB.logout

Following are  code snippets to logout from Facebook:
<script>window.fbAsyncInit = function() {
                FB.init({
                    appId      : "FACEBOOK_APPLICATION_ID", 
                    status     : true, 
                    cookie     : true,
                    xfbml      : true,
                    oauth      : true                    
                });
                FB.getLoginStatus(function(response) {
                if (response && response.status === 'connected') {
                    FB.logout(function(response) {
                       /** Afer logout, Refresh the Page **/ 
                       console.log('Logout Successfully.');
                       document.getElementById('currentStatus').innerHTML='Logout from facebook Successfully.';
                       //document.location.href='/';
                       /** Afer logout, Refresh the Page **/                        

                    });
                }else{
                    //document.location.href='/';                    
                    document.getElementById('currentStatus').innerHTML='You are NOT LOGIN in Facebook.';
                    console.log('You are not login in Facebook.')
                }
            });


            }; 

            (function(d){
                var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                d.getElementsByTagName('head')[0].appendChild(js);
            }(document));
        </script>
        <h2 id="currentStatus">
Please wait...</h2>