buy proscar online

jQuery Conference jotting

Jul 31 2015 Published by under Uncategorized

jQuery Conference (July 24- July 25)

Grunt JS

Use it to Automate the Tasks as much as possible.

example: 1) JsHint

                  2)  Minification process

                 3)  Execute the test cases

Key Notes Observed: Always run the tests on the dist (production) javascript code, not on your source code.

Comparison with Gulp: 

Gulp can also a good task runner. However, Its not necessary to migrate Gulp.

 

 

Test driving jQuery Plugin Development

Techstack used: Karma, jQuery, jasmine

  example: 1) created the plugin of the jquery. example link (https://github.com/nashjain/jQComment/commits?author=nashjain)

Key Notes Observed: Karma is the only good test runner for javascript available. Behavior driven development is possible in jQuery (writing test first, code next, passing the test and iterating the process). We can refactor the code later and with help of tests, we will be more confident about the refactored code. when all the tests are passed.

 

React JS

Techstack used: React JS

example: Created a booklist component using reactjs

   https://github.com/prathamesh-sonpatki/openlib-react/branches/active

   https://speakerdeck.com/chaitanya/sip-of-reactjs

KeyNotes Observed: 1) Its one way data binding

                                          2) It comes up with component funda (unconventional idea). child data is immutable and always data flows from parent to child. However there are hacks to flow data from child to parent

                                         3) Think of reactjs component  as view always getting refreshed with latest data (for any data change). Think of it as a clean slate being update each time again and again

                                         4) It comes up with the idea of jsx templates (which has some additional features over html. example class has to specified using className), which has to be inside the javascript file (we cannot separate out jsx template code from javascript code)

                                         5) It uses Virtual Dom and creates the diff between what is changed and updates the component. (Diff algorithm is the awesome feature of the react js)

                                        6) React JS is a small library provides view updation. However for entire architecture using Flux.

Mistakes to be avoided (especially plugin authors), while using jQuery

  1. Don’t use Ajax.setup(), As it makes changes of all the ajax calls. Use a command function which does ajax call with custom parameters (instead of using $.Ajax straight away)
  2. Use $.text() method to add data into DOM. (For security, to prevent XSS)
  3. Don’t go with the approach of adding CSS class names to the body and using them as flags for the logic in code. Always do the logic with Javascript. Adding classname at the body will cause reflow process in entire page
  4. Don’t overrelay on jquery for small changes.
  5. Event name spaces are the best practice, However to aviod the namespace collision. use the _.random method with a random number as the event name. (Make sure event namespace is unique)
  6. Use chrome dev tools to identify the problem.
  7. In jquery 3.0 will have the latest implementation in adherece to promise spec.
  8. Don’t overrely on jquery migration plugin. Fix the errors thrown by the plugin and move on
  9. Some methods like $.get, $.post,$.load are not good ones to use. But they are not removed since many people use it and they helped in jquery evolution.

 

Key Take aways from the conference:

1)As a team, we have to write same style of code. This is what  jquery team follows. An example of this is

Spaces Vs Tabs → Tabs

Commas at the starting → no

Only one Var → no

Single Quotes vs Double quotes → Double quotes

Semicolon → yes

2) Code review has to be strict.

   Automate as much as the code review process initially. (example as using jsHint)

   Review the logic as strictly as possible.

3) It’s not necessary to integrate the latest libraries, without evaluation

  Its not necessary for us to use React JS, Do a POC on it. identify the pros and cons

4)Spend time on educating the developers

   To have a common style of development, Invest time on educating the developers

5) TypeScript, @Coffeescript usage

 Typescript is preferable, If we are facing more issues with types, then definitely go for Typescript. But it is a good to invest time on this. As it going to be converged with Javascript in the coming versions and also it has a Good IDE support. It is good to try it.

6) Documentation

Use Document.js, Docco. jsDoc3 is also fine. However some speakers were against documentation, they believe method names should convey the meaning.

7) Shadow Dom

Shadow Dom sucks! . Some how all the speakers disagreed with shadow dom. Don’t use polymer in the project, Its going to die

8) Future of JS is Isomorphic Javascript

Isomorphic Javascript is the feature of javascript, where some amount of javascript is executed in the server side and passed on the client with a state. client continues execution of remaining part of javascript from that state

Metor.js is one good library provides this capability, However its tied with Mongo database. We can evaluate on ShareJS

9) Good Libraries and tools for CSS

stylus, JSS, CSSSCSS, DSS, CSSdoc, JSCSS, CSSlint, interm, bem

10) looks like EmberJS is awesome compared to Angular JS

11) Don’t spend too much time on Offline support of the webapp. Since the Internet is growing, definitely not a good idea on spending so much time on offline support of webapp.

No responses yet

Backbone JS Tutorial

Jan 01 2013 Published by under Backbone, Uncategorized

Backbone JS (Stop tying your data to DOM)

Backbone.js is not a full fledged mvc or mvp or mvvm framework, Basically it provides the event bindings between the model and view, so that changes in the view will update the attributes of model and corresponding views listening to the model will get updated.

But there are many backbone js plugins, which help us to create a web application using backbone depending on the requirement. So we can implement mvc, mvp, mvvm or anything using these plugins.

What is a backbone model ? (State)

Backbone model maintains state of the application. Following things can be done in the model.

Responsibilities:

1)Getting the data from server
2)Save data to the server
3)Validation of data
4)Syncing of the data from server to client
5)Destroying the model (data,if no longer needed )

Usage:

A model has attributes to store the data, on change of any of the attribute a change event will be triggered by the model
However, this change event can also be suppressed by passing {silent:true}. views should listen to this events and display the data

Gotchas:

1)If the attribute is again a model, then the change in the attribute of the submodel will not be triggered in parent model. Use the deepModelbinderplugin.
2)Even while instantiating a model with an object, the attributes will be set and validation if exist on any attribute will trigger.
3)Becareful in specifying the initial values, if initial value is not set, then the value is treated as undefined

What is a backbone collection?

A collection is just a list of models.

Responsibilities:

1)Fetch data from server
2)Sync data to the server

Usage:

On addition or removal of model to a collection the change event will be triggered. Views should listen to this events and display the data

Gotchas:

1)While creating the collection from a model, if the validate method fails then the model will not get added into the collection

What is a backbone view ?

A view is basically UI component that displays the data to the user intutively. it interacts with the template for markup

Responsibilities:

1)listen to the model and display data when data is changed.

Gotchas:

1)Beware of zombie views, they should be destroyed and all their events should be undelegated otherwise they will become zombies

What is a backbone router?

A router allows us to configure url corresponding to the view. It should be used only to provide views as a bookmarkable url. Don’t use it as a controller.

Responsibilties:

1)It provides route and callback method corresponding to the creation of view

Usage:

Use router.navigate or Backbone.history.navigate to route to a different url. Pass {trigger:true} to trigger the callback method corresponding to the view

Gotachs:

1)By default callback corresponding to the empty route will be called.
2)This is not a controller and never should be used a controller. it should not be passed to the views. use Backbone.history.navigate() method for such cases.

P.S: This post is for developers, who are new to backbone. Shortly, Continue Reading »

No responses yet

Preventing Xss Attack in Client Side

Jun 05 2012 Published by under jQuery, Uncategorized

If users are allowed to enter html content via a textfield or any other UI element,Chances are that your application might be prone to XSS Attack. Let us see,How we can Prevent XSS Attack in Such Scenarios

1)Html Encode(a.k.a Html Escape) the content entered by the user in the text field.Following function will come in handy,if you are using jQuery

function htmlEncode(value){
return $(‘<div/>’).text(value).html();
}

Here,Value is set as innerText and encoded innerHtml is retrieved

2)While displaying the user entered content,then decode the encoded content.Following function will come in handy,if you are using jQuery

function htmlDecode(value){
return $(‘<div/>’).html(value).text();
}

Here,Value is set as innerHtml and the innerText is retrieved

P.S:The above functions have really worked well for me till now.

No responses yet

JavaScript Concepts that every UI Engineer should be aware off

Mar 21 2012 Published by under Uncategorized

Following are some of the Javascript Concepts, Which every engineer should be aware off.

1)why Functions are called first class objects in javascript?

Explanation:

a) Functions can be assigned as a variables
b) Stored in data structures
c) Passed into functions as arguments
d) Returned from functions

 

2)What is a Closure in JavaScript ?

Explanation:

A closure is a function with access to variables in its containing scope..(the function closes over the variables).This is due to the lexical scoping. the inner function can access variables of outer function.

Example:
function attachListeners() {
for (var i = 0; i < 10; i++) {
$(‘#id-’ + i).click(
function () { alert(“I am element number ” + i); }); } }

 

There are 10 DOM elements in the page with id’s as follows “id-1″,”id-2″ …..etc. onclick of the element with “id-1″ will show the value of the i as 10 !!!!.

To solve the above issue,place the click callback in a separate function.

No responses yet

jQuery Introduction

Dec 12 2011 Published by under jQuery

No responses yet

jQuery’s $.animate() API ‘s drawbacks

Sep 18 2011 Published by under jQuery, Uncategorized

While working with jQuery animate() API, Following are the issues,I faced.

1) CSS ClassName cannot be added.

$.animate(className,1000);

I feel this is a biggest draw back of the animate() api. because we need to add css properties in the following tricky way,instead of adding ClassName straight away

Usage:

$(“#foo”).animate({  ”margin-left” : “40px”,  ”width” : “300px” }, 1000);

Solution:

Use the following plugin,which goes by the name as Animate to Class plugin.

http://plugins.jquery.com/project/animate-to-class

 

2)Limited CSS properties supported by $.animate() API.

Some CSS properties like “background-color,color..” cannot be used in this $.animate() API.

$.animate({“background-color”:”#b0d2f1″},1000);

This is the biggest drawback,Even though it is mentioned in the documentation.Developers mostly like to animate background-color in 50% of the use cases.

Solution

Following is the plugin,goes by the name “color” plugin has to be included,If you plan to use animate API to animate background color.

https://github.com/jquery/jquery-color

 

 

 

 

No responses yet

Testing Javascript code Using Qunits (jQuery Testing Framework)

Jul 18 2011 Published by under jQuery

In My Personal Experience,If you develop a feature in Javascript, you must add Unit Test cases for your code.Having Unit Test Cases will really helpful in the following scenarios.

1)While Refactoring the code for improving the code
2)While Updating the code, To introduce an Enhancement

Comprehensively,If you are going to change your code,Unit test cases will really give you confidence,The changes added by you did not break the existing implementation.

In-Browser Testing:

Basically,In-Browser Testing Frameworks allows you to run your test cases by loading the html page in the browser.Following are some of the popular In-Browser testing frame works available

1)Qunit.js
2)jsUnit

I prefer Qunit.js,because it is very easy to integrate (doesn’t need any dependencies) and most popularly used now.If you want to start writing Unit Test cases using Qunit.js.Here is my help for you.Please Follow these steps

Step1:

Create an Html File and include the Qunit.js and Qunit.css ,Which will be used for running the test suites created via In-Browser Testing.

Example:

<script type=”text/javascript” src=”http://code.jquery.com/jquery-latest.js”></script>
<script type=”text/javascript” src=”http://code.jquery.com/qunit/git/qunit.js”></script>
<h1 id=”qunit-header”>QUnit example</h1>
<h2 id=”qunit-banner”></h2>
<h2 id=”qunit-userAgent”></h2>
<div id=”qunit-fixture”>test markup, will be hidden</div>

 

Step2:

Create javascript file, To write the unit test cases needed to test  javascript code. Include this file in your test html page .

Example:

If your javascript file name is dragdrop.js, then your new javascript test file will be dragdrop.test.js.Include both the dragdrop.js and dragdrop.test.js in the above said html file.

 

Step3:

Create a module to test a Feature / Function.In Setup and Tear down methods initialize and destroy the variables needed for testing.

 

 module(“Module Name”,
{
setup:function()
{
setup logic should be written is done here,called before each test case (test() method)
this        — – refers to the module.
this.variableName   —  to  add a variable,which can be accessed inside the test case
Add Html elements,if needed for testing
},
teardown:function()
{
clean up is done here, called after each test case execution (test()  method)
this.variableName = null  —  to remove the variables,added during the setup method
Remove Html elements added while setup
}
});

 

Step4:

Create Test Cases,To test the javascript code using assertions

Example:

Test Case: Test Case Should be written after a module

test(“Name of the test case”,
function(){
1)call the function to be tested
2)assert the results

Assertions:
equal(actualResult,expectedResult,message);
notEqual(actualResult,expectedResult,message);
}
});

 

Following is the sample code(Template), which will be useful for writing a testcase using Qunits

module(“test”,
{
setup:function(){},
teardown=function(){}
}
);

test(“Name”,function(){ equal(A,E,M); notEqual(A,E,M);
});

A — actual result
E — expected Result
M — Message

No responses yet

Use document.getElementById instead of $(‘#Id’)

Jul 12 2011 Published by under jQuery

Three years back,I used prototype.js extensively. In prototype.js ‘$’ is used instead of document.getElementById(“”).But In these three years,I moved from prototype to jQuery,due to its awesomeness. I will write a separate post about “Why I love jQuery than Prototype.js”.

When I started using jQuery,Due to my Prototype.js background, I used $(‘#id’) extensively.But when i looked at the source code of jQuery,I came to know that $(‘#id’) does two things

1)It parses the selector passed inside $(‘selector’)

2)Uses the document.getElementById(‘id’) , Native DOM API supported across all the browsers

This will be costly,Because it does the costly operation of the regex parsing to identify the selector,Before using document.getElementById(). So I suggest Javascript Programmars to use document.getElementById instead of $(‘#id’) , Please take a look at the performance test made at following link

http://jsperf.com/id-vs-document-getelementbyid/20

Following are the Situations, where $(#id) API doesn’t return the element,where as document.getElementById(id) does return the element

1)If the Id contains spaces

$(‘#div id’) will not work (Even though having space in Id is not a preferred way, but if the id is generated dynamically based on some strings.this issue will arise.)

document.getElementById(div id) will return the element

2)Using remove() or any other jQuery API,if the $(”#id) does not return any element will cost you a lot.

$(‘#div id’).remove() will lead you to the drastic performance issues.

Instead Use :
var element = document.getElementById(div id);
if(element){$(element).remove();}

Please do share, If you have faced few more issues with $(‘#id’)

No responses yet

jQuery.attr() Issues in jQuery 1.6

Jul 08 2011 Published by under jQuery

When I Upgraded my jQuery Version from  1.4.2 to 1.6 . Suddenly, My Custom implementation of  Table Row Reordering Via Drag n Drop Plugin , which was working before, started breaking. After a close Inspection into the issue.Issue is raised due to the API Change made by jQuery in version 1.6

Following is the big Change made by jQuery in 1.6.

jQuery introduced a method called jQuery.prop(). To segregate the API used for getting DOM properties of an element.Since ‘rowIndex’ is an table row property added by the DOM.jQuery.attr(‘rowIndex’) stopped returning the rowIndex Value.

To get the attributes value of an Html Element,Use the Following API

   $(element).attr(‘attributeName’);

The above code is equivalent to

 element.getAttribute(‘attribute’);

Following are Some of the attributes supported by the above jQuery API

1) src

2) href

3) customAttributes such as data-[customName]

……etc

To get the attribute property of an Element Provided by DOM,Use the Following API

 $(element).prop(‘propertyName’);

The above code is equivalent to

 element.propertyName;

Following are Some of the properties supported by the above jQuery API

1) rowIndex

2) checked

…etc

So Folks,Before Upgrading to any new Version of jQuery.Please Go through their Change Log.So that you can avoid the mistake i made.

 

 

 

 

 

No responses yet

Bind First jQuery plugin

Jul 08 2011 Published by under jQuery, Uncategorized

While working with my co developers,I had a Following Use case

1)An Inline On Click Event Handler is attached to a button,which is created from the back-end Java Code

 <input onclick=”executeInlineFunction()” type=”button” />

2)A CallBack Function,Which has to be executed before inline Callback function on click event of the button.

Solution:

Following is the jQuery Plugin,Which helps you to add a function at the top of event handlers array

 $.fn.bindFirst = function(name, fn)
 this.bind(name, fn);    
 var handlers = this.data('events')[name.split('.')[0]];     
 var handler = handlers.pop();     
 handlers.splice(0, 0, handler); 
};

Copy the above code and below is the example to use it.

$(element).bindFirst(“click”,NthEventHandlerFunction);

$(element).bindFirst(“click”,N-1thEventHandlerFunction);

.

.

.

$(element).bindFirst(“click”,FirstEventHandlerFunction);

When the onclick event is triggerred then the event handlers are executed in the stacked order.

Here is how i have solved the problem:

I added the existing inline onclick handler into the data events and added my “customFunction” using bindFirst plugin with the following code

 

$(button).bindFirst(‘click’,$(inputelement).attr(‘onclick’));

$(button).bindFirst(‘click’,customFunction);

$(button).attr(‘onclick’) = ”;

Please share your thoughts,if you have any other solution.

No responses yet