MVC & backbone.js

I recently talked about (JavaScript) MVC (not JavaScriptMVC framework itself) in detail at work.

If some of you are really interested about the Architectural Design Pattern then MVC is the way to go to separate the web application into multiple parts.

In the past MVC has been heavily used for structuring desktop and server-side applications, but it’s only been in recent years that come to being applied to JavaScript.

As the majority of JavaScript developers currently using these patterns opt to utilize libraries such as backbone.js for implementing an MVC/MV*-like structure.

So why do you need MVC at first place?
  • If you do a lot of JavaScript, things tend to get messy!
  • Backbone provides a way to organize your code, by using the MVC pattern
  • Only the View accesses the DOM (e.g. with jQuery, Dojo,…)
MVC Advantages:
  • Clean separation of content/style
  • Improved decoupling
  • Easier testing
  • Allow multiple people to work on different parts
What is backbone.js?

Backbone.js is one of a number of JavaScript frameworks for creating MVC-like web applications, it’s relatively lightweight and can be easily tested using third-party toolkits such as Jasmine or QUnit.

Why backbone?
  • Organize the structure to your application
  • Simplify server-side persistence
  • Decouple the DOM from your page’s data
  • Model data, views and routers in a succinct manner
  • Provide DOM, model and collection synchronization

You can find some more detail on the same page in the slides shown below.

Facebook Like, YouTube Video Feed and AJAX using jQuery

Initially thought of just to write a small article on Facebook XFBML Like Widget but when I started writing with the demo part then realize that other things also needs explanation so now divided into 3 parts and would try to explain them individually.

This article is going to cover following topics with the final demo in the last with all the integration in ones.

  • Facebook XFBML Like Widget
  • YouTube JavaScript API
  • jQuery AJAX

One of the problems comes when you try to make dynamic facebook like button to show the count based upon the particular URL and parse it.

Facebook Like Widget:

The Like button lets a user share your content with friends on Facebook. When the user clicks the Like button on your site, a story appears in the user’s friends’ News Feed with a link back to your website

There are two Like button implementations: XFBML and Iframe. The XFBML version is more versatile, but requires use of the JavaScript SDK. The XFBML dynamically re-sizes its height according to whether there are profile pictures to display, gives you the ability (through the JavaScript library) to listen for like events so that you know in real time when a user clicks the Like button, and it always gives the user the ability to add an optional comment to the like

It has multiple attributes like href, layout, width, action etc. you can get the complete list at http://developers.facebook.com/docs/reference/plugins/like

Of course you should always try to use XFBML button only because it gives you more options and control over Iframe facebook like but again it requires Facebook JavaScript SDK in order to make it work.

Facebook JavaScript SDK:

It is open source and available on GitHub [http://github.com/facebook/connect-js]

JavaScript SDK is also necessary to use the XFBML version of facebook like.

There are 2 ways to call JavaScript SDK

  1. Just write this line in your page head section and use it
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
  1. Another way is to load asynchronously so it does not block loading other elements of your page:
    <div id="fb-root"></div><script>window.fbAsyncInit = function() {
    
    FB.init({appId: 'your app id', status: true, cookie: true,
    
    xfbml: true});
    
    };
    
    (function() {
    
    var e = document.createElement('script'); e.async = true;
    
    e.src = document.location.protocol +
    
    '//connect.facebook.net/en_US/all.js';
    
    document.getElementById('fb-root').appendChild(e);
    
    }());
    
    </script>
    
    

    Anyway there is already enough information about the SDK, you always can go and check at http://developers.facebook.com/docs/reference/javascript/

    YouTube JavaScript API:

    The JavaScript API allows users to control the YouTube chromeless or embedded video players via JavaScript. Calls can be made to play, pause, seek to a certain time in a video, set the volume, mute the player, and other useful functions.

    You can find more detail at http://code.google.com/apis/youtube/js_api_reference.html

    Not going to explain it further otherwise it will eat up the entire article if I start writing it here :)

    jQuery API:

    No need to explain this wonderful API on the planet, jQuery has all the things which you require for any website/portal starting from traversing, event handling, animation and AJAX though there are other robust frameworks too to compete jQuery like Dojo, ExtJS, Prototype, YUI etc.

    We will use the jQuery $.ajax wrapper which will serve our purpose to get the JSONP data from the YouTube to make video gallery and then we push the Facebook XFBML Like in the picture to get the set the like count.

    So now let’s start coding and see all things working together, have got the code snippets from YouTube API [http://code.google.com/apis/youtube/2.0/developers_guide_json.html] and converted to jQuery code.

    < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
    <title>My Videos</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
    <script type="text/javascript">
    function loadVideo(playerUrl, autoplay) {
    	swfobject.embedSWF(
    		playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
    		(autoplay?1:0)+'&version=3', 'player', '585', '355', '9.0.0', false, 
    		false, {allowfullscreen: 'true'});
    
    		/*Parse the facebook like button*/
    		$('#like').html('<fb:like href="'+playerUrl+'" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />')
    		if (typeof FB  != "undefined"){
    			FB.XFBML.parse(document.getElementById('like'))
    		}
    }
    
    function showMyVideos(data) {
    	var feed = data.feed;
    	var entries = feed.entry || [];
    	var html = ['<ul class="videos">'];
    	for (var i = 0; i < entries.length; i++) {
    		var entry = entries[i];
    		var title = entry.title.$t.substr(0, 20);
    		var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
    		var playerUrl = entries[i].media$group.media$content[0].url;
    		var videoId = playerUrl.substr(playerUrl.indexOf('v/')+2, 11);			
    		playerUrl = "http://www.youtube.com/v/" + videoId;	
    		html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
    				  '<img src="', 
    				  thumbnailUrl, '" width="94" height="58"/>', '</ul></script></head></html></li>');
    	}
    	html.push('');
    	document.getElementById('videos').innerHTML = html.join('');
    	if (entries.length > 0) {
    		loadVideo(entries[0].media$group.media$content[0].url, false);
    	}
    }
    
    $(function(){
          $.ajax({
                type: "GET",
    			url: "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_week&alt=json-in-script&max-results=5&format=5",
                cache: false,
                dataType:'jsonp',
                success: function(data){
                    showMyVideos(data);
              },
    		  	error: function(XMLHttpRequest, textStatus, errorThrown, data){
    				alert("Not able to fetch the data due to feed unavailability!!!");
    			}
            });
    })
    
    
    
    <style>
    
    body{
    	background:#1d1d1d;
    	color:#c0c0c0;
    	font-family:Arial, Helvetica, sans-serif;
    	font-size:100%; 
    	line-height:1.125em;
    	}
    
    #videoContainer {
    	background:#1d1d1d;
    	border-bottom:2px solid #2a2a2a;
    	font-size:.75em;
    	height:625px;
    	overflow:hidden;
    	position:relative;
    	}
    
    #playerContainer {
    	margin:150px auto;
    	width:625px;
    	}
    
    #like {
    	height: 15px;
    	margin-top: 10px;
    	text-align: right;
    	
    	}
    
    ul.videos {
    	list-style: none;
    	margin-bottom: 1em;
    	margin-left: 0em;
    	padding-left : 0em;
    	}
    	ul.videos li {
    		cursor: pointer;
    		display: inline;
    		margin-bottom: 1em;
    		padding-right: 28px;
    	}
    
    #content{
    	backgroud:#0F0;
    	margin:0px auto;
    	width:625px;;
    	}
    	#content h1{
    		display:inline;
    		font-style:italic;
    		font-weight:normal;
    		font-size:1.2em;
    		letter-spacing:-0.7px;;
    	}
    
    </style>
    
    
    <body>
    <div id="videoContainer">
        
        <div id="playerContainer">
            <div id="player"></div>
        
    		<div id="like"></div>
       		<div id="videos"></div>
    	
    	</div>
    		</div>
    
    <div id="content">
    <h1>Mohammed Arif Blog Facebook Likes</h1>
    <fb:like href="www.mohammedarif.com" layout="button_count"></fb:like>
    </div>
    </body>
    
    

    So what we doing here is fetching YouTube data based upon some filter criteria like most_viewed, max-results and format etc in the jQuery URL parameter, there are number of criteria available in gdata feed and the dataType is JSONP which works cross domain and of course using GET method to fetch video feed.

    $(function(){
          $.ajax({
                type: "GET",
    			url: "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_week&alt=json-in-script&max-results=5&format=5",
                cache: false,
                dataType:'jsonp',
                success: function(data){
                    showMyVideos(data);
              },
    		  	error: function(XMLHttpRequest, textStatus, errorThrown, data){
    				alert("Not able to fetch the data due to feed unavailability!!!");
    			}
            });
    })
    

    Then we hit the success method when the request succeeds then we send the data to the next method showMyVideos(data) to parse and build the DOM.

    function showMyVideos(data) {
    	var feed = data.feed;
    	var entries = feed.entry || [];
    	var html = ['<ul class="videos">'];
    	for (var i = 0; i < entries.length; i++) {
    		var entry = entries[i];
    		var title = entry.title.$t.substr(0, 20);
    		var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
    		var playerUrl = entries[i].media$group.media$content[0].url;
    		var videoId = playerUrl.substr(playerUrl.indexOf('v/')+2, 11);			
    		playerUrl = "http://www.youtube.com/v/" + videoId;	
    		html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
    				  '<img src="', 
    				  thumbnailUrl, '" width="94" height="58"/>', '');
    	}
    	html.push('</ul>');
    	document.getElementById('videos').innerHTML = html.join('');
    	if (entries.length > 0) {
    		loadVideo(entries[0].media$group.media$content[0].url, false);
    	}
    }
    
    

    Now we just need to read the data and manipulate the DOM and attach loadVideo() method with the specified URLs and also load the first video using our loadVideo(playerUrl, autoplay) method which takes 2 parameters which takes playerUrl and autoplay which we need to send to the SWFObject embedSWF() to build and run the videos.

    function loadVideo(playerUrl, autoplay) {
    	swfobject.embedSWF(
    		playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
    		(autoplay?1:0)+'&version=3', 'player', '585', '355', '9.0.0', false, 
    		false, {allowfullscreen: 'true'});
    
    		/*Parse the facebook like button*/
    		$('#like').html('<fb:like href="'+playerUrl+'" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />')
    		if (typeof FB  != "undefined"){
    			FB.XFBML.parse(document.getElementById('like'))
    		}
    }
    

    loadVideo() is the main method to do all things including build the dynamic Facebook like widget, this is the key to write this article because making dynamic Facebook Like widget may create some problems.

    Anyway now we have the solution with us, so we already have DIV id=”like” in our HTML, we just writing XFBML on run time to parse the Facebook Like button and get and set the video count based upon the particular video.

    		/*Parse the facebook like button*/
    		$('#like').html('<fb:like href="'+playerUrl+'" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />')
    		if (typeof FB  != "undefined"){
    			FB.XFBML.parse(document.getElementById('like'))
    		}
    

    And then we check whether FB object exist or not and if it does then parse the XFBML tag and show the count if you like it.

    Here you go to see the complete code and demo

iPhone 4 will be available in India soon!

The first iPhone was launched in June of 2007. The second iPhone 3G, launched in July 2008. And now Apple iPhone 4G is available in the market from June 24th 2010 in Europe and US.

iPhone 4 is going to be launched in India in coming September. The gadget has been very successful in western markets and is selling like a hot cake. Indian gadget freaks are desperately waiting for the gadget to arrive in the country.

Though there were several issues reported to Apple but there is no confirmation from Apple site yet.

The Apple iPhone 4 features FaceTime, which supports video calling, and Apple’s new Retina 960×640 pixels display, the highest resolution display ever built into a phone, according to the company, multitasking. In addition, HD video recording, Apple’s A4 processor, a 3-axis gyro and up to 40% longer talk time – in an all-new design of glass and stainless steel. Apple added that the new iPhone is the thinnest smartphone in the world, at 9.3 millimeters. The iPhone 4 features the new LG LCD Display technology called In-Plane Switching technology (IPS) for enhanced viewing experience.

iPhone 4 operates its functionality on iOS4, the latest software developed by Apple for its mobiles. The software enables the device to run more than one program simultaneously.

The cost of this new device in western markets is set at $199 and $299 for 16GB and 32GB respectively. For Indian users, the 16GB version of the device is expected to cost around Rs. 35,500 while the 32GB version will be priced at around Rs. 40,000.

Vodafone already announced that it is all set to bring the iPhone 4 to the Indian market in the coming months.

Read More

Just updated to WordPress 2.8.4 from 2.6

Just updated to WordPress 2.8.4 from 2.6

Read More

Build your first jQuery plugin

First and far most, we should say thanks to John Resig and his team to make our life so easier then before by making jQuery, most demanding and powerful JavaScript framework and it’s expanding phenomenally that gives the proof of dominancy of jQuery framework.

So why do I need to extend jQuery?

Here we go; no library is full filling all the requirements so does jQuery, so there should be some mechanism to add sets of useful methods called as plugins for your specific requirement, which we can say in the basic terminology calling your external methods into your structure but it doesn’t give you the power of leverage existing code base.

Let’s say, by creating a new jQuery commands, we automatically inherit the use of powerful selector mechanism and can use all the jQuery methods and indeed it’s a good practice to make reusable code.

There is a pretty good documentation and guidelines available on jQuery Plugins/Authoring page.

Let’s start making our first jQuery plugin; we call our plugin as “disable”, we make our plugin to disable the form elements and then we will extend our default options using $.extend utility method to enable the required once.

We will follow the guidelines as provided on jQuery.com so we will save our plugin as jquery.disable.js

[sourcecode language=’js’]
// plugin definition
$.fn.disable = function() {
// plugin implementation code goes here.
};
[/sourcecode]

Read More

FLOCK – Another browser in the market!

The Browser For The Modern Web

Flock is a social networking browser based on Mozilla Firefox; flock was founded in 2005 based in Redwood City, CA. Flock is an open source company. Flock is available for Windows, Linux, and Mac OSX in 12 languages, looks impressive on the first instance.

Flock 2.0 beta has been released on June 16, 2008, based on Firefox 3.0.

“Now our users can experience the best of both worlds with all of the performance and security improvements of Firefox 3, combined with Flock’s unique social browsing experience” as said by Shawn Hardin, CEO of Flock.

So what does social networking browser mean?

Let’s analyze the features and services of Flock; it supports web services like bookmarking, photo sharing, social networking, Read More

Who is better TypePad or WordPress?

WordPress vs. TypePad

After investigating for 15 days, need to get the better blogging platform for our client who wins lastly? Guess guys!

Professionally TypePad, due to the client demand because they are not willing to spend money creating new infrastructure like setting up Apache/MySQL for WordPress on their environment.

TypePad doesn’t need all that, they host on their own, and you just need to map your domain in the last to give the pointing URL, sounds better.

There is another Six Apart product called MovableType, based on the same technology, you can configure it on your own server but comparing WordPress its bit tricky to install and relatively larger file size (4MB), MovableType is good for web developers who knows XHTML/CSS etc, MovableType supports plugins too as does WordPress. Anyway TypePad is far better then MovableType due to ease in configuration and their built in support system

TypePad:

Let’s come to the point now, it’s been a month or so using TypePad to me, getting lot more things day by day, might not be aware all the features of TypePad but Read More

Google Chrome: the Google Browser

Google Chrome: the Google Browser

Google Chrome Logo

Google announced today that they will release their own browser tomorrow, code named Google Chrome. Beta version will be launched tomorrow morning only, initially available only for Windows.

Google Chrome is open source and based on WebKit, which is the same engine used by Safari and Adobe AIR. This is really good news because just the thought of yet another browser with different JavaScript and CSS engines to test every site and web app is really Read More

JavaScript outside the browser

http://javascript.weblogsinc.com/2006/08/06/javascript-outside-of-the-browser/

After reading the above article, questions comes in mind, why JavaScript outside the browser?

So let’s go through on some points which strongly recommend the future of “the world’s most misunderstood programming language”.

1. JavaScript will be treated as a significant programming language in the upcoming days
2. JavaScript speed and performance, of course would be increasing in the future of ECMAScript 4th edition
3. Increasing popularity of HELMA* using Rhino, it’s not as popular yet as it should be, would be hearing soon in the future about HELMA
4. Major enhancement of some JavaScript Engines like Rhino*, SpiderMonkey*
5. Popularity of Tamarin*

*Helma: It is an open source web application framework for fast and efficient scripting and serving of your websites and Internet applications.
Read More

Show Love to the Object Literal | Core JavaScript 1.5 Guide:Literals

Defining an object is via literal notation. Supported in JavaScript1.2 and above, it’s a more robust form of creating an object on the fly.
Neat and clean approach to write reusable, readable and maintainable JavaScript code.

Show Love to the Object Literal:
http://ajaxian.com/archives/show-love-to-the-object-literal

Object literals beauty lies in Namespaces, which reduces the number of global variables in your pages. It uses a technique known as branching, which allows you to use common utility
functions without worrying about browser sniffing. Read More

Loading...
X