Refactoring javascript : managing existing js code

As an web developer we always have so many problems regarding Javascript as our lines of codes in our app grow. The root cause of these problems are

  • There are so many files. In any of the files you might have missing semicolons, or used undefined variables
  • You often forget to put var before variable declaration, and this put the variable in the global scope
    • This variable might conflict with same variable name you used in other part of your code.

Solution

  $(function () {
    if ($('body.shares').length == 0 && $('body.pact_profile_page').length == 0)  return false;
    ...
  });

  // Basic syntax would be
  $(document).ready(function () {
    var target_element_is_not_loaded = ($('.your-target-selector').length > 0);
    if (target_element_is_not_loaded) return false;
    
    ...
  });

The basic idea is, you only execute your code if your targeted page is loaded. Means if your JS code is meant for posts page then you do not need to load this code else where.

 

Other Links

http://jyaasa.com/blog/refactoring-javascript-managing-existing-js-code

Getting Started with Google Analytics

First of all I assume you know why you are interested in Google Analytics Service.

Usage Guide:

Adding analytics.js to Your Site

The analytics.js library is a JavaScript library for measuring how users interact with your website. This document explains how to add analytics.js to your site.

 

Now put the following js code snippet in the <head> section of your pages. Continue reading

Rails : Capybara Webkit : Issue : Multiple JS events in single example

I recently moved from Selenium Web Driver to Thoughtbot’s Capybara Webkit as JS Driver for Capybara. The main reason is, webkit is super fast in running the test suite and its headless (no browser pops up ) .

Problem I faced

I was changing the option in select box and expecting the change in span’s content. Actually some sort of calculation should have been triggered. Webkit was not triggering the ‘change‘ event properly.

Continue reading

Codeclimate : JSLint : Expected ‘===’ and instead saw ‘==’, How to pass analyzer

If you check your JS code using JSLint then it generally shows warning messages like

Expected '!==' and instead saw '!='.
Expected '===' and instead saw '=='

It is found that every suggestions it make are subject to risks. These suggestions are not considered to be followed exactly.

  • Expected ‘===’ and instead saw ‘==’. (Line 64)
    if ($('#referers_cell_number').val == '') {
    
  • Missing semicolon. (Line 75)
    })
    
  • Expected ‘!==’ and instead saw ‘!=’. (Line 83)
    if (addressid != '') {
    
  • Expected ‘!==’ and instead saw ‘!=’. (Line 90)
    if (data != null) {
    
  • Expected ‘===’ and instead saw ‘==’. (Line 93)
    if (refId == '' || typeof(refId) == "undefined") {
    

However, there is a different way to follow these suggestions… like this

The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.

When comparing to any of the following values, use the === or !== operators (which do not do type coercion): 0 '' undefined null false true

If you only care that a value is truthy or falsy, then use the short form. Instead of

(foo != 0)

just say

(foo)

and instead of

(foo == 0)

say

(!foo)

The === and !== operators are preferred.

importance of not writing parenthesis ‘( )’ after function name in callbacks

Suppose you want to assign an event handler function to an click event of any element

$(document).on('click', '.disable-user', disableUserConfirmation());

when you run the app the function disableUserConfirmation()  gets executed any way, however the event handler function expected to run when the event is triggered wont work. You can see the error in the console.

Uncaught TypeError: undefined is not a function

What happens in callbacks is, when the jQuery’s function ‘on’ want to execute the function object it just appends the parenthesis after the function name and executes it.

jQuery: .delegate() vs .live() vs .on() vs .bind() vs .click/.mouseover/.mouseenter

The event binding functions like .click, .mouseover eventually trigger .bind() method and .bind eventually trigger .on() method, so .on() is most fastest however .on() doesnot work for dynamically added elements. SO for dynamically added elements use .live() or .delegate()

However, .live() searches the element within whole document and .delegate() searches the element within the area you specify so, .delegate() is the most efficient method to bind an event.

Slowest ----> Faster
.click() --> .bind() --> .on()

.live() --> .delegate()
element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });
element.on('selector', 'click', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });