‘$’ selector in Protractor Locators (Selectors) and their references.

This is a nice list to keep for reference somewhere:

Eg: $(‘#some-id’) :

The $ is not a jQuery selector, but a shorthanded version of element(by.css(‘#some-id’)). In this fashion, we’d be able to select elements by id, class and attributes:

$(‘#some-id’) // element(by.id())
$(‘.some-class’) // element(by.className())
$(‘tag-name’) // element(by.tagName())
$(‘[ng-message=required]’) // remember to leave out the double quotes around the value of attribute
$(‘#parent #child’) // select one child inside parent
$(‘ul li’) // select all children inside parent
$(‘ul li’).first() // select first of children
$(‘ul li’).last() // select last of children
$(‘ul li’).get(index) // select index-th of children

Then we get the more interesting ones:

element(by.model(‘data’));
element(by.repeater(‘cat in pets’));
element(by.options(‘c for c in colors’))
element(by.binding(‘value’)); // only look through the elements with ng-binding attribute
element(by.buttonText(‘Save’)); // the whole of button text
element(by.partialButtonText(‘Save’)); // part of button text
element(by.cssContainingText(‘.pet’, ‘Dog’)) // for selecting this: <li class=”pet”>Dog</li>
element(by.deepCss(‘span’)) // for selecting all level of spans <span><span>x</span></span>

Reference : http://www.protractortest.org/#/

Getting Started with Bower Package Manager

Tags

, , ,

Bower is a front-end package manager built by Twitter. Also known as a Package manager for the Web, bower is used in modern open source and closed source projects to solve many recurrent issues.

Bower has many of the benefits of other dependency managers. I’m sure there are others, but the benefits I’ve noticed so far include:

  • Simplify what might be called declarative dependency management; i.e. you declare your dependencies in bower.json so that other things can determine them easily
  • No need to commit dependencies to version control
  • Semantic versioning is used to help define a range of acceptable versions for a dependency, which makes it easy to update to newer versions within the defined range
  • No need to locate various builds (debug, minified, etc)
  • Simple to use different builds of a dependency for dev vs. prod
  • You can distribute the bower.json file and everyone can get up to speed with a simple “bower install”

Read more : https://www.codementor.io/bower/tutorial/beginner-tutorial-getting-started-bower-package-manager

JavaScript unit test tools for TDD

Tags

, ,

Karma or Protractor

Karma is a JavaScript test-runner built with Node.js, and meant for unit testing.

Protractor is for end-to-end testing, and uses Selenium Web Driver to drive tests.

Both have been made by the Angular team. You can use any assertion-library you want with either.

related:

pros:

  • Uses node.js, so compatible with Win/OS X/Linux
  • Run tests from browser or headless with PhantomJS
  • Run on multiple clients at once
  • Option to launch, capture, and automatically shutdown browsers
  • Option to run server/clients on development computer or separately
  • Run tests from command line (can be integrated in ant/maven)
  • Write tests xUnit or BDD style
  • Supports multiple JavaScript test frameworks
  • Auto-run tests on save
  • Proxies requests cross-domain
  • Possible to customize:
    • Extend it to wrap other test-frameworks (Jasmine, Mocha, QUnit built-in)
    • Your own assertions/refutes
    • Reporters
    • Browser Launchers
  • Plugin for WebStorm
  • Supported by Netbeans IDE

cons:

  • Does not support NodeJS testing
  • No plugin for Eclipse (yet)
  • No history of previous test results

TestSwarm

John Resig (jQuery) has created a tool for distributed JavaScript testing, TestSwarm. Mainly for open source JavaScript projects, but TestSwarm is open source, so you can set up a server yourself for corporate testing. Although this might require that you to do some modifications.

pros:

  • Continuous integration server for JavaScript
  • Supports all major browsers/operating systems
  • Run on multiple clients at once
  • Don’t need to run server/clients on development computer (no need for IE)
  • Automatically run tests on all clients when you commit something (or whenever you modify the script to run the tests)
  • Show history of test results pr commit
  • Supports multiple JavaScript test frameworks
  • Have test results for OS and browser versions
  • Crowd source to test in a multitude of browsers

cons:

  • Cannot break your build through ant/maven
  • Don’t notice the test fail before commit
  • No IDEplug-in

http://ejohn.org/blog/javascript-testing-does-not-scale/

Jasmine

This is a client-side test-runner that might interest developers familiar with Ruby or Ruby on Rails. The syntax is based on RSpec that’s used for testing in Rails projects.

Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM.

Project home: http://jasmine.github.io/

 QUnit

QUnit is a powerful, easy-to-use JavaScript unit test suite. It’s used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code

QUnit shares some history with TestSwarm (above):

QUnit was originally developed by John Resig as part of jQuery. In 2008 it got its own home, name and API documentation, allowing others to use it for their unit testing as well. At the time it still depended on jQuery. A rewrite in 2009 fixed that, now QUnit runs completely standalone. QUnit’s assertion methods follow the CommonJS Unit Testing specification, which was to some degree influenced by QUnit.

Project home: http://qunitjs.com/

mocha.js

I’m totally unqualified to comment on mocha.js’s features, strengths, and weaknesses, but it was just recommended to me by someone I trust in the JS community.

List of features, as reported by its web site:

  • browser support
  • simple async support, including promises
  • test coverage reporting
  • string diff support
  • javascript API for running tests
  • proper exit status for CI support etc
  • auto-detects and disables coloring for non-ttys
  • maps uncaught exceptions to the correct test case
  • async test timeout support
  • test-specific timeouts
  • growl notification support
  • reports test durations
  • highlights slow tests
  • file watcher support
  • global variable leak detection
  • optionally run tests that match a regexp
  • auto-exit to prevent “hanging” with an active loop
  • easily meta-generate suites & test-cases
  • opts file support
  • clickable suite titles to filter test execution
  • node debugger support
  • detects multiple calls to done()
  • use any assertion library you want
  • extensible reporting, bundled with 9+ reporters
  • extensible test DSLs or “interfaces”
  • before, after, before each, after each hooks
  • arbitrary transpiler support (coffee-script etc)

All the best 🙂

Difference between META name= title tag and TITLE tag

Tags

Title :

<title> This will be displayed in the title bar of your Browser. </title>

Meta tags:

<meta name=”title” content=”Whatever you type in here will be displayed on search engines.”>


<title> is a required element on any HTML page to be valid markup, and will be what is displayed as the page title in your browser’s tab/window title.

For instance, try inputting the following markup into the W3C Markup Validator (via “Direct Input”):

<!DOCTYPE html>
<html>
    <head></head>
    <body></body>
</html>

This will produce an error that there is no instance of <title> in <head>.

The <meta name="title" content="page-title"> element is just that — metadata about your page, that any client browser or web crawler can use or not use as it wants. Whether it is used or not will depend on the crawler/client in question, as none of them are required to look for or not look for it.

So in short, you should have a <title> element if you want valid markup.

The <meta> tag is going to depend on whether you want to provide for crawlers/clients, and you’d probably have to check documentation for if a particular crawler uses it.

Thanks 🙂

Reading files in JavaScript using the File APIs

Tags

,

HTML5 finally provides a standard way to interact with local files, via the File APIspecification. As example of its capabilities, the File API could be used to create a thumbnail preview of images as they’re being sent to the server, or allow an app to save a file reference while the user is offline. Additionally, you could use client-side logic to verify an upload’s mimetype matches its file extension or restrict the size of an upload.

Here is the test example,

<html>
<title>File Uploading</title>
<style>
#byte_content {
margin: 5px 0;
max-height: 500px;
overflow-y: auto;
overflow-x: hidden;
}
#byte_range { margin-top: 5px; }
</style>

<input type=”file” id=”files” name=”file” />
<span class=”readBytesButtons”>
<button>Click to display</button>
</span>

function readBlob(opt_startByte, opt_stopByte) {

var files = document.getElementById(‘files’).files;
if (!files.length) {
alert(‘Please select a file!’);
return;
}

var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size – 1;

var reader = new FileReader();

// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById(‘byte_content’).textContent = evt.target.result;
//document.getElementById(‘byte_range’).textContent =
// [‘Read bytes: ‘, start + 1, ‘ – ‘, stop + 1,
// ‘ of ‘, file.size, ‘ byte file’].join(”);
}
};

var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}

document.querySelector(‘.readBytesButtons’).addEventListener(‘click’, function(evt) {
if (evt.target.tagName.toLowerCase() == ‘button’) {
var startByte = evt.target.getAttribute(‘data-startbyte’);
var endByte = evt.target.getAttribute(‘data-endbyte’);
readBlob(startByte, endByte);
}
}, false);

</html>

 

More : http://www.html5rocks.com/en/tutorials/file/dndfiles/

 

What is SAPUI5 ?

This is a framework which is having collection of JS libraries useful for developing web application in desktop as well as mobile.

  • These JS libraries are used along with CSS to develop rich and interactive internet applications.
  • SAPUI5 is build upon jQuery open source, SAP has customized and build their own UI components (Controls, Layouts, etc.,). This framework is having extensible feature, so that we can extend, control and define our own custom controls.

Multiple Technology Flavors used in SAPUI5:

HTML 5

Only latest versions of browsers (Chrome 29, Firefox 24, Safari 6.0, IE9 and Opera16) are supporting HTML5. Even Though HTML 5 is not supported by all the browsers, there are various reason web applications are being developed in HTML 5.

  • Future development is going to happen in HTML 5. It has all new set of Meta tags available to improve more interactive user experience.
  • Now more and more users are viewing their applications in mobile devices (Cell Phone, Tablets, etc). There are bunch of Meta tags that support to develop mobile apps.
  • Newly introduced Canvas Element is useful for showing interactive animations on the screen. It can be used to show Interactive Charts, Diagrams, etc.,
  • HTML5 has native API that allows user to have better interaction with the web application like Drag and Drop, Document editing, Timed Media player, etc.,
  • Local Storage of user sessions
  • SVG – Scalable Vector Graphics. Graphical representations can be added to the web pages.
  • Video/Audio is in-build in HTML 5. Flash player is no longer needed.

CSS

Using CSS Layout, Color and Fonts can be separated from Web page UI design. It gives rich appearance for GUI. Along with Java Script contents can be enriched with dynamic and interactive display.

AJAX/JSON

AJAX is used to interact with server. Request is send as GET or POST request via AJAX (XMLHTTPRequest) and asynchronous response can be received. There are several content types that are being used depends upon the response from server. Few content types are shown below:

  • text/html
  • application/json
  • application/pdf

JSON object is used for data transfer. After receiving JSON object response from server, SAPUI 5 is capable of rendering UI control based on JSON object.

jQuery

jQuery is open source java script library, which simplify JS coding. jQuery also simplifies a lot of the complicated things from JavaScript. SAPUI5 is build upon jQuery, SAP has customized and build their own Java Script Libraries.

oData Protocal

The purpose of the Open Data protocol (OData) is to provide a REST-based protocol for CRUD-style operations (Create, Read, Update and Delete) against resources exposed as data services. oData is initially defined by Microsoft. Facebook, Netflix, and eBay all expose some of their information via oData. SAPUI5 application can call Gateway Restful web services using oData protocal.

Why should we pick SAPUI5 for web development ?

Pros and Cons of SAPUI5:

1.  Since SAPUI5 is supporting HTML 5 it has all below advantages discussed earlier

  • It support cross-platform (Desktop & Mobile)
  • Interactive user experience like Drag and Drop, Document editing, Timed Media player, etc.,
  • It has new tag Canvas, SVG which is helpful in animation or graphical representation (Chart, Flow Diagram, etc.,)
  • Audio/Video support

2.  SAPUI5 is extended from HTML 5 and provides several UI controls which is helpful in developing rich and interactive web application. GUI can be designed rapidly as there are SAP customized JS libraries available. Without much of coding UI Controls can be added in the web pages.

3.  SAPUI5 is supporting any data transfer like JSON, XML, oData, etc. Since it is using these web page can be rendered faster.

4.  SAP has released more products which can be used along with SAPUI5 like (SAP HANA, SAP Fiori, SAP Netweaver Gatway, etc.,) This shows clearly that       SAPUI5 is dominating technology.

5.  Most of the users now want their application to be viewed on their mobile devices.

Good Luck 🙂

CSS Snippets for WebDevelopers

These CSS Snippets addresses most common use cases that are must for websites. These snippets includes like centering a div, rounding corners, targeting chrome and firefox, alternate table row, sticky footer, media queries and many more.

1. Center a DIV with CSS

#idOfTheDiv {
width: 400px; /* here you put the width that you need */
height: 200px; /* here you put the height that you need */
position:absolute;
left:50%;
top:50%;
margin-left:-200px; /* this number always to be the width divided two in negative */
margin-top:-100px; /* this number always to be the height divided two in negative */
}

2. Common @media queries

/* Smartphones (portrait and landscape) ———– */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ———– */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ———– */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ———– */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ———– */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ———– */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ———– */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ———– */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ———– */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

3. Print the url after your links

@media print
{
a:after {
content: ” [” attr(href) “] “;
}
}

4. Rounded Corners using CSS

#idOfTheDiv {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}

5. Transparency for ie, firefox and safari

#element {
filter:alpha(opacity=50); //For IE
opacity: 0.5; //Safari
-moz-opacity:0.5; //Mozilla & Firefox
}
6. Sticky Footer

html, body {height: 100%;}

#wrap {min-height: 100%;}

#main {overflow:auto;
padding-bottom: 150px;} /* must be same height as the footer */

#footer {position: relative;
margin-top: -150px; /* negative value of footer height */
height: 150px;
clear:both;}

/*Opera Fix*/
body:before {
content:””;
height:100%;
float:left;
width:0;
margin-top:-32767px;/
}

<!–[if !IE 7]>
<style type=”text/css”>
#wrap {display:table;height:100%}
</style>
<![endif]–>

7. Prevent Long URL’s From Breaking Out with CSS

.break {
-ms-word-break: break-all;
word-break: break-all;
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}

.ellipsis {
width: 250px;
white-space: nowrap;
overflow: hidden;
-ms-text-overflow: ellipsis; /* Required for IE8 */
-o-text-overflow: ellipsis; /* Required for Opera */
text-overflow: ellipsis;
}

8. Removing Arrows From <SELECT> Tag with CSS

SELECT.no_arrows {
width:90px; padding-top:0px; margin:-5px 0 0 5px; border:0px;
background:transparent; -webkit-appearance:none;
text-indent:0.01px; text-overflow:””; color:#444;
}
SELECT.no_arrows:focus {
box-shadow:none;
}
SELECT.no_arrows::-ms-expand{
/* for IE 10+ */
display:none;
}
@-moz-document url-prefix(){
/* for FF */
SELECT.no_arrows {
width:auto; padding-top:2px; margin:0 0 0 5px;
-webkit-appearance: none; -moz-appearance: none;
}
}

9. Targeting Chrome With CSS

@media screen and (-webkit-min-device-pixel-ratio:0) {
H5 { color:red; }
P { margin-left:20px; }
/* other special styles for Chrome here */
}

10. Targeting Firefox With CSS

@-moz-document url-prefix(){
H5 { color:red; }
P { margin-left:20px; }
/* other special styles for FireFox here */
}

11. Center Website Content with CSS

<style type=”text/css”>
/* Center your website horizontally */
.wrapper{
width:960px;
display:table;
margin:auto;
}

/* Center certain content vertically */
.container{
min-height: 10em;
display: table-cell;
vertical-align: middle;
}
</style>

<div class=”wrapper”>
<div class=”container”>
<p>Content goes here</p>
</div>
</div>

12. Alternating Table Color Rows in CSS

<style type=”text/css”>
/* technique 1 */
tbody tr:nth-child(odd){ background-color:#ccc; }
/* technique 2 */
TBODY TR.odd { background-color:#78a5d1; }
</style>

Source : http://www.jquerybyexample.net/

Good Luck….

Namespacing in JavaScript

JavaScript has a big design flaw, where it is very easy to create global variables that have the potential to interact in negative ways. The practice of namespacing is usually to create an object literal encapsulating your own functions and variables.Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions.

var yourNamespace = {
foo: function() {
},
bar: function() {   }

};

yourNamespace.foo();

Example : namespace in JavaScript

var MYAPPLICATION = {
calculateVat: function (base) {
return base * 1.21;
},

product: function (price) {
this.price = price;
this.getPrice = function(){
return this.price;
};
},

doCalculations: function () {
var p = new MYAPPLICATION.product(100);
alert(this.calculateVat(p.getPrice()));
}
}

var p = new MYAPPLICATION.product(150);
alert(p.getPrice());

Pros

  • Structure
  • Object Oriented Names
  • Easy to Remember
  • Unique Variables and Methods
  • Custom Branding
  • Integration with Future Web 2.0 Sites

Cons

  • Longer Code
  • Loading Time
  • Too Complex

Static Namespacing

I’m using static namespacing as an umbrella term for solutions in which the namespace label is effectively hard coded. It’s true, you could re-assign one namespace to another but the new namespace will reference the same objects as the old one.

  1. By Direct Assignment

The most basic approach. Its verbose and if you ever wanted to rename the namespace you’ve got a job on your hands. However its safe and unambiguous.

var myApp = {}

myApp.id = 0;

myApp.next = function() {

return myApp.id++;

}

myApp.reset = function() {

myApp.id = 0;

}

window.console && console.log(

myApp.next(),

myApp.next(),

myApp.reset(),

myApp.next()

); //0, 1, undefined, 0

You could make future maintenance a little easier by using this to reference sibling properties – but this is a little risky since there is nothing to stop your namespaced functions from being reassigned:

var myApp = {}

myApp.id = 0;

myApp.next = function() {

return this.id++;

}

myApp.reset = function() {

this.id = 0;

}

myApp.next(); //0

myApp.next(); //1

var getNextId = myApp.next;

getNextId(); //NaN whoops!

  1. Using Object Literal Notation

Now we need only refer to the namespace name once, so switching the name later is a little easier (assuming you haven’t already referenced the namespace too often). There is still a danger that the value of this might throw a surprise – but its a little safer to assume that objects defined within an object literal construct will not be reassigned.

var myApp = {

id: 0,

next: function() {

return this.id++;

},

reset: function() {

this.id = 0;

}

}

window.console && console.log(

myApp.next(),

myApp.next(),

myApp.reset(),

myApp.next()

) //0, 1, undefined, 0

  1. The Module Pattern

I find myself using the module pattern more often these days. The logic is shielded from the global scope by a function wrapper (usually self-invoking) which returns an object representing the module’s public interface. By immediately invoking the function and assigning the result to a namespace variable, we lock up the module’s API in the namespace. Additionally any variables not included in the return value will remain forever private, visible only to the public functions that reference them.

var myApp = (function() {

var id= 0;

return {

next: function() {

return id++;

},

reset: function() {

id = 0;

}

};

})();

window.console && console.log(

myApp.next(),

myApp.next(),

myApp.reset(),

myApp.next()

) //0, 1, undefined, 0

Like the object literal example above, the receiving namespace can be easily switched, but there are added advantages: object literal notation is rigid – its all about property assignments, with no room for supporting logic. Moreover all properties must be initialized and property values cannot easily cross reference one another (so, for example, internal closures are not possible). The module pattern suffers none of these constraints and gives us the added benefit of privacy.

4.Dynamic Namespacing

We could also call this section namespace injection. The namespace is represented by a proxy which is directly referenced inside the function wrapper – which means we no longer have to bundle up a return value to assign to the namespace. This makes namespace definition more flexible and makes it very easy to have multiple independent instances of a module existing in separate namespaces (or even in the global context). Dynamic namespacing supports all the features of the module pattern with the added advantage of being intuitive and readable.

  1. Supply a Namespace Argument

Here we simply pass the namespace as an argument to a self-invoking function. The id variable is private because it does not get assigned to the context.

 var myApp = {};

(function(context) {

var id = 0;

context.next = function() {

return id++;

};

context.reset = function() {

id = 0;

}

})(myApp);

window.console && console.log(

myApp.next(),

myApp.next(),

myApp.reset(),

myApp.next()

) //0, 1, undefined, 0

We can even set the context to the global object (with a one word change!). This is a big asset for library vendors – who can wrap their features in a self-invoking function and leave it to the user to decide whether they should be global or not (John Resig was an early adopter of this concept when he wrote JQuery)

var myApp = {};

(function(context) {

var id = 0;

context.next = function() {

return id++;

};

context.reset = function() {

id = 0;

}

})(this);

window.console && console.log(

next(),

next(),

reset(),

next()

) //0, 1, undefined, 0

  1. Use thisas a Namespace Proxy

The beauty of the pattern is that it simply uses the language as designed – nothing more, nothing less, no tricks, no sugar. Moreover because the namespace is injected via the this keyword (which is static within a given execution context) it cannot be accidentally modified.

var myApp = {};

(function() {

var id = 0;

this.next = function() {

return id++;

};

this.reset = function() {

id = 0;

}

}).apply(myApp);

window.console && console.log(

myApp.next(),

myApp.next(),

myApp.reset(),

myApp.next()

); //0, 1, undefined, 0

Even better, the apply (and call) APIs provide natural separation of context and arguments – so passing additional arguments to the module creator is very clean. The following example demonstrates this, and also shows how to run the module independently over multiple namespaces:

var subsys1 = {}, subsys2 = {};

var nextIdMod = function(startId) {

var id = startId || 0;

this.next = function() {

return id++;

};

this.reset = function() {

id = 0;

}

};

nextIdMod.call(subsys1);

nextIdMod.call(subsys2,1000);

window.console && console.log(

subsys1.next(),

subsys1.next(),

subsys2.next(),

subsys1.reset(),

subsys2.next(),

subsys1.next()

) //0, 1, 1000, undefined, 1001, 0

Of course if we wanted a global id generator, its a breeze…

nextIdMod();

window.console && console.log(

next(),

next(),

reset(),

next()

) //0, 1, undefined, 0

The id generator tool we’ve been using as an example does not do justice to the full potential of this pattern. By wrapping an entire library and using the this keyword as a stand in for the namespace we make it easy for the user to run the library in whichever context they choose (including the global context)

//library code

var protoQueryMooJo = function() {

//everything

}

//user code

var thirdParty = {};

protoQueryMooJo.apply(thirdParty);

Nested namespaces

var MYAPPLICATION = {

MODEL: {

product: function (price) {

this.price = price;

this.getPrice = function(){

return this.price;

};

}

},

LOGIC: {

calculateVat: function (base) {

return base * 1.21;

},

doCalculations: function () {

var p = new MYAPPLICATION.MODEL.product(100);

alert(this.calculateVat(p.getPrice()));

}

}

}

References :

http://www.kenneth-truyers.net/

http://javascriptweblog.wordpress.com/

Good Luck…

Creating HTML Templates with Mustache.js

mustache.js is an implementation of the mustache template system in JavaScript.

  • Mustache is a logic-less template syntax. It can be used for HTML, config files, source code – anything. It works by expanding tags in a template using values provided in a hash or object.
  • Mustache is implemented in different languages: Ruby, JavaScript, Python, PHP, Perl, Objective-C, Java, .NET, Android, C++, Go, Lua, Scala, etc
  • We call it “logic-less” because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.

Where to use mustache.js?

You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as node, and CouchDB views.

Below is quick example how to use mustache.js:

var view = {

title: “Rajasekhar”,

calc: function () {

return 2 + 4;

}

};

 

var output = Mustache.render(“{{title}} spends {{calc}}”, view);

In this example, the Mustache.render function takes two parameters: 1) the mustache template and 2) a view object that contains the data and code needed to render the template.

<!doctype html>

<htmllang=”en”>

<head>

<title>Mustache.js Inline Method</title>

<scripttype=”text/javascript”src=”mustache.js”></script>

<script>

var view = {

name : “Rajasekhar”,

company : “united online”

};

function loadtemp(){

var output = Mustache.render(“{{name}} works in {{ company }}”, view);

document.getElementById(‘person’).innerHTML = output;

}

</script>

</head>

<bodyonload=”loadtemp()”>

<pid=”person”></p>

</body>

</html>

Basic Template

var person = {

firstName: “Christophe”,

lastName: “Coenraets”,

blogURL: “http://coenraets.org&#8221;

};

var template = “<h1>{{firstName}} {{lastName}}</h1>Blog: {{blogURL}}”;

var html = Mustache.to_html(template, person);

$(‘#sampleArea’).html(html);

 Basic Template using Ajax data

$.getJSON(‘json/data.json’, function(data) {

var template = “<h1>{{firstName}} {{lastName}}</h1>Blog: {{blogURL}}”;

var html = Mustache.to_html(template, data);

$(‘#sampleArea’).html(html);

});

Enumerable Section

var data = {name: “Rajasekhar”, skills: [‘JavaScript’, ‘PHP’, ‘Java’]};

var tpl = “{{name}} skills:<ul>{{#skills}}<li>{{.}}</li>{{/skills}}</ul>”;

var html = Mustache.to_html(tpl, data);

$(‘#sampleArea’).html(html);

Output :

Rajasekhar skills:

  • JavaScript
  • PHP
  • Java

If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration.

View:

{ “uolhyd”:[   {“firstName”:”Rajasekhar”,”lastName”:”Kantepalli”},   {“firstName”:”Shiva”,”lastName”:”Kondur”},   {“firstName”:”Uday”,”lastName”:”Meduri”},   {“firstName”:”Sravanthi”,”lastName”:”Kakarla”} ], “name”:function(){   returnthis.firstName+” “+this.lastName; }}

Template:

{{# uolhyd }}* {{name}}{{/ uolhyd }}

Output:

* Rajasekhar Kantepalli

* Shiva Kondur

* Uday Meduri

* Sravanthi Kakarla

 Advantages and Disadvantages:

 Mustache:

+ Very popular choice with a large, active community.

+ Server side support in many languages, including Java.

+ Logic-less templates do a great job of forcing you to separate presentation from logic.

+ Clean syntax leads to templates that are easy to build, read, and maintain.

– A little too logic-less: basic tasks (e.g. label alternate rows with different CSS classes) are difficult.

– View logic is often pushed back to the server or implemented as a “lambda” (callable function).

– For lambdas to work on client and server, you must write them in JavaScript.

Handlebars:

+ Logic-less templates do a great job of forcing you to separate presentation from logic.

+ Clean syntax leads to templates that are easy to build, read, and maintain.

+ Compiled rather than interpreted templates.

+ Better support for paths than mustache (ie, reaching deep into a context object).

+ Better support for global helpers than mustache.

– Requires server-side JavaScript to render on the server.

References :

http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/

http://www.sitepoint.com/creating-html-templates-with-mustachejs/

http://code.tutsplus.com/tutorials/an-introduction-to-handlebars–net-27761

Good Luck…:)

AJAX Advantages/Disadvantages…

Tags

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.

Examples of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.

AJAX is Asynchronous JavaScript And XML.

The XmlHttpRequest is an actual object which works behind the scene.

Ajax implementation uses JavaScript functions to call methods from a webservice, webpage request in response to get response.

Response data is parsed using DOM.

Asynchronous data retrieval using XmlHttpRequest

AJAX Advantages

  • AJAX Learn:Ajax is easy to learn and understand.
  • Speed:Reduce the Server Traffic in both side request to or from. also reduce the time consuming on both side response.
  • Interaction:AJAX is much responsive, whole page(small amount) data transfer at a time.
  • XMLHttpRequest:It can be used by Web browser scripting languages, such as JavaScript to transfer XML and other text data to and from a Web server using HTTP. It is used for making requests to the non-Ajax pages.
  • Asynchronous calls:AJAX allows for the ability to make asynchronous calls to a web server. This allows the client browser to avoid waiting for all data to arrive before allowing the user to act once more.
  • Form Validation:This is the biggest advantage. Form validation should be instant and properly. AJAX gives you all of that, and more. form validation is the easiest way to get a proper validation.
  • Bandwidth Usage:No require to completely reload page you are really using less server bandwidth, and when you are in countries or places that charge for your surfing bandwidth, it really is something to think about.
  • Open Standard: Ajax is supported by almost every web browser and platform. Even now it comes in the count of most trusted brands of application platform in the world.
  • Limited processing on the server: As we know that in case of Ajax, the server is not required to process all the form elements, only the necessary data is sent to the user. So there is a limited processing on the server.
  • Bandwidth Reduction: The components of the site which are requested are loaded very fast with the help of Ajax application. Since the web page does not need to reload its complete content, the bandwidth required per request also undergoes a significant reduction.
  • Vast compatibility range: On one side Ajax is browser independent, and on the other, it’s applicable to most of the standard web servers and server-side languages, be it PHP, ASP, ASP.net, Cold Fusion, Perl or any other.
  • Reduce the traffic travels between the client and the server.
  • Response time is faster so increases performance and speed.
  • You can use JSON (JavaScript Object Notation) which is alternative to XML. JSON is key value pair and works like an array.
  • You can use Firefox browser with an add-on called as Firebug to debug all Ajax calls.
  • Ready Open source JavaScript libraries available for use – JQuery, Prototype, Scriptaculous, etc..
  • AJAX communicates over HTTP Protocol.
  • No cross browser pain
  • U can trust that good developer have spent there time and energy making library
  • U can focus more on actual problem and not on side effects
  • API’s are good. If someones tells UI developer that ajax, HTTP, JavaScrtip bla bla bla…….. OFFFF simple function is always great Ajax.call(url, callbackfunction, param). That is all we are looking for most of the times.
  • Great time saving 🙂 and u can enjoy parties no late night work

AJAX Disadvantages

  • AJAX application would be a mistake because search engines would not be able to index an AJAX application.
    2. Open Source: View source is allowed and anyone can view the code source written for AJAX.
    3. AJAX is not well or full integrated with any browser.
    4. ActiveX requests are enabled only in IE5 and IE6 in old version. now this feature is available in latest version few new browsers.
    The last disadvantage lies in the actual XMLHttpRequest object itself. Due to security constraints, you can only use to access information from the host that served the initial page. If you need to display information from another server, it’s is not possible with in the AJAX.
  • It can increase design and development time
  • More complex than building classic web application
  • Security is less in AJAX application as all files are downloaded at client side.
  • Search Engine like Google cannot index AJAX pages.
  • JavaScript disabled browsers cannot use the application.
  • Due to security constraints, you can only use it to access information from the host that served the initial page. If you need to display information from another server, it is not possible within the AJAX.
  • Its long history of battles between browser and specification that end up in real mess. We as developer understand it when we realize that we are spending more time resolving cross browser specific issues instead of solving the programming business logic/problem.
  • U will be playing on smooth surface and saving skin from headaches that are good for we as software engineers
  • If you use some profiler you will find few dozens of call made inside that function for doing the things using library which consumes few of MILLISECONDS. but this is not really a big deal considering time we saved during the development
  • You have to trust on the library regarding what they say. So i will suggest to stick to good ones only. And yes u r using one of the finest

Good luck…