Thursday, 30 January 2014

JavaScript best practices

1 – Don’t forget var keyword when assigning a variable’s value for the first time.
      Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables.
2- Use strings accumulator-style: Using + operator a new string is created in memory and the concatenated value is assigned to it. Only after this the result is assigned to a variable.
Example:

a='A'+'B';   // slower

Faster :
a+='A';
a+='B';

3- Primitive operations can be faster than function calls: Consider using alternative primitive operation over function calls in performance critical loops and functions.

Slow:
var min = Math.min(a, b);
arr.push(val);

Faster:
var min = a < b ? a : b;
arr[arr.length] = val;

4-Maximize object resolution speed and minimize scope chain:
Inefficient way:
var url = location.href;

Efficient one:
var url = window.location.href;

5-use === instead of == : The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==.

[10] === 10    // is false
[10]  == 10    // is true
'10' == 10     // is true
'10' === 10    // is false


6-Use Semicolons for line termination: It is a best practice to use semi-colons for line termination.You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser.

7- Create a Self-calling Function: 
(function(){
    // some private code that will be executed automatically
})(); 

(function(a,b){
    var result = a+b;
    return result;
})(10,20)

this function is self called function and the code will execute automatically.

8-Get a random number in a specific range:

var x = Math.floor(Math.random() * (max - min + 1)) + min;

9-Generate an array of numbers with numbers from 0 to maxvar numbersArray = [] , max = 100;

10-Append an array to another array:
var arr = [1 , "foo" , {name "Joe"} , -28];

var arr2 = ["Dog" , 5 , 100];
Array.prototype.push.apply(arr, arr2);
/* array1 will be equal to  [1 , "foo" , {name "Joe"} , -28 , "Dog" , 5 , 100] */

11-Verify that a given argument is a number:

function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}

12-Verify that a given argument is an array:

Array.isArray(obj);

13-Get the max or the min in an array of numbers:

var  numbers = [5, 4 , 12 , -21 , 28 , 400 , 122205, -8511];
var maximum = Math.max.apply(Math, numbers); // 122205
var minimum = Math.min.apply(Math, numbers);  // -8511

14-Empty an array:
var myArray = [13 , 22 , 100 ]; 
myArray.length = 0; // myArray will be equal to [].

15-Don’t use delete to remove an item from array: Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.

16-Truncate an array using length:
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ]; 
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.

myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined

17-Use the map() function method to loop through an array’s items:
var squares = [1,2,3,4].map(function (val) { 
    return val * val; 
});
// squares will be equal to [1, 4, 9, 16]

18-Rounding number to N decimal place:

var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432

NOTE : the toFixed() function returns a string and not a number.

19-Floating point problems:
0.1 + 0.2 === 0.3 // is false

Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit.

20-Avoid negative indexes in arrays:
var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf("foo") ;  // from is equal to -1
numbersArray.splice(from,2);    // will return [5]

if we using splice method with negative index then it will delete last element from the array.

21-Pass functions, not strings, to setTimeout() and setInterval():
If you pass a string into setTimeout() or setInterval(), the string will be evaluated the same way as with eval, which is slow.

Instead of using…

setInterval('doSomethingPeriodically()', 1000); 
setTimeout('doSomethingAfterFiveSeconds()', 5000);

…use…

setInterval(doSomethingPeriodically, 1000); 
setTimeout(doSomethingAfterFiveSeconds, 5000);



for more detail  Click Here





Thursday, 23 January 2014

Techniques to Increase Performance of PhoneGap Applications

1-> Dont create the UI on server.
     Dont create UI on server,it makes the application slow.

2-> Dont wait for the data to display UI.
    Dont wait for data to display UI.display UI first and then update data.

3-> Cache Everything
     cache everything as much you can and display the existing data first in UI then update the UI by the updated data.don't wait for updated data to display all data in UI.but caching much is also make application slow.

3-> avoid click event
     Click event is very slow as compare to touchStart event. so use touchStart in place of click.

4-> Optimize image.
5-> Limit shadow and gradients.
6-> minimize browser re-flows.

Thursday, 16 January 2014

How to Build and Test Blackberry Phonegap application on simulator in Windows

Cordova for BlackBerry makes use of the BlackBerry WebWorks framework. BlackBerry WebWorks tooling is available for Windows or Mac environments.

WebWorks applications can ONLY be deployed to the following BlackBerry platforms:

BlackBerry OS 5.0 and higher
BlackBerry PlayBook
BlackBerry 10 (QNX)

============================

Requirements
============================
windows 64 or 32 bit
Java Development Kit (JDK)(32 bit)
Apache Ant
Windows: Apache Ant.

=========================
Install sdk for the above
=========================
[BlackBerry 10 (QNX) SDK] (https://developer.blackberry.com/html5/download/#blackberry10)
[BlackBerry PlayBook SDK] (https://developer.blackberry.com/html5/download/#playbook) & Adobe Air SDK
[BlackBerry Smartphones SDK] (https://developer.blackberry.com/html5/download/#smartphones)

=========================
Install simulators
=========================
install simulators for the apropriate version

for blackberry 10 and playbook adobe air sdk require before installation and VMplayer is required to run the simulators.

=========================
Register for Signing Keys
=========================
for registering signing key Click Here

========================
Install Cordova
========================
1- npm install -g phonegap

2-  npm install cordova

====================

Edit the project property file
===========================
blackberry.bbwp.dir=
playbook.bbwp.dir=
qnx.bbwp.dir=

to 

blackberry.bbwp.dir=C:\\Program Files (x86)\\Research In Motion\\BlackBerry WebWorks SDK 2.3.1.5
playbook.bbwp.dir=C:\\Program Files (x86)\\Research In Motion\\BlackBerry WebWorks SDK for TabletOS 2.2.0.5\\bbwp
qnx.bbwp.dir=C:\\Program Files (x86)\\Research In Motion\\BlackBerry 10 WebWorks SDK 1.0.4.11

=========================



Build project
====================
go to project directory and build by following command

ant qnx buil // for blackberry 10
ant playbook build // for playbook
ant blackberry build // for blackberry smartphones





If error loading jvm.dll occurs then set java path to  C:\Program Files (x86)\Research In Motion\BlackBerry WebWorks SDK for TabletOS 2.2.0.5\jre\bin

===================
load to simulator
==================

ant qnx load-simulator
ant playbook load-simulator
ant blackberry load-simulator 

for qnx and playbook simulators must be enable/on before the load-simulator command.

Thursday, 9 January 2014

Why we use ActiveSupport::Concern

The Concern provides a mechanism for composing modules.Concerns are pieces of code that allow you to better organize the code that you write. This feature has actually been around for a long time prior to Rails 4, Rails 4 merely creates the folders for you and sets up the environment.

Included
==================================================
Module defines the callback included which is called when a module is included into another class or module.  For example see the following code:
==================================================

module Named
  def self.included(base)
    base.validates_presence_of :first_name, :last_name
  end

  def full_name
    "#{first_name} #{last_name}"
  end
end

..........................
class Person
  include Named
end



When Person includes Named, the included method is called on Named with a reference to Person. Now, what if you want a module that builds upon Named?
=================================================

module Mailable
  include Named

  def self.included(base)
    email_regexp = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/
    base.validates_format_of :email, with: email_regexp
  end

  def send_greeting
    mail = WelcomeMailer.greet(email, first_name, last_name)
    mail.deliver
  end
end

.................................................................................................................................
if we do
require 'mailable'

then it will gives
# => NoMethodError: undefined method `validates_presence_of' for Mailable:Module

This will fail when Named is included into Mailable. The Name.included callback will be executed with Mailable as the base, but Mailable doesn't define validates_presence_of:

==================================================

We really want these modules to wait until they are included in your model before the included callback is invoked. Concern works around this issue for us:

module Named
  extend ActiveSupport::Concern

  included do
    base.validates_presence_of :first_name, :last_name
  end 
end

module Mailable
  extend ActiveSupport::Concern
  include Named

  included do
    email_regexp = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/
    base.validates_format_of :email, with: email_regexp
  end
end

First a module extends Concern, and then instead of defining def self.included it calls included with a block. Concern delays calling these blocks until your module is included in something that is not a Concern.