Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Saturday, October 5, 2013

Slide and github for Code Camp 13



Thank you for attending this afternoon session, hopefully you guys at least get some basic knowledge on Backbone and how each component interact with each others.

I hope we could have internet access today, so we all can get some hands on experience by going through the github code together. So please feel to checkout the code, follow the instruction and set it up in your local environment.   Feel free to poke around. 


I will update the slide later, you should get the slide on the code camp official website later as well.


Update
======
There is a question about if there is a user preference concept for an application, and what the user preference will do is adding some filtering for a screen ( Let say stock quote view ).

There are plenty of ways to do that, but one of them I would see is
1) assume you have a user/ api
2) assume you have a stock-quote/ api

What usually is done should be in this sequence
1) You will fetch the user/ api first, because your other view or section has dependency on it
2) Grab what you need from the user api response, let's say your user has a preference of showing top 10 stock for each day
3) Now you can fetch the stock-quote/ api by passing some filter parameter that your user set earlier, for example,  /stock-quote/?display_top_transaction=10




Thursday, April 18, 2013

Just Another Frontend Boilerplate

Recently put together a frontend boilerplate with some latest 3rd party libraries makes into a checkout-and-ready-to-use boilerplate.  It has a configured built tool which you can use right away.  Also, it comes with a customize micro framework which you can take advantage of, but you can replace it with your own easily.

For more information, go to https://github.com/iroy2000/frontend-boilerplate

Frontend Boilerplate

This frontend boilerplate includes a customized mirco framework that combines some of the latest frontend library in the market. It comes with Jasmine as testing framework, plus build tool and build config.

Libraries Included

  • Backbone ( amd )
  • Backbone Localstorage
  • Underscore ( amd )
  • Twitter Bootstrap
  • Require-jQuery
  • Text ( RequireJS Plugin )
  • Modernizr
  • HTML5 Bolierplate ( partial )

Tuesday, October 9, 2012

Web Platform Docs

If you guys didn't know, the W3C has started a project called Web Platform Docs ( currently in alpha release ) aimed at being the centralized resources for web developer.  This project has been and will continue be contributed by the main (and big) players in the web development industry.

http://docs.webplatform.org/wiki/Main_Page

If you haven't heard of that before, you can visit their "Getting Started" link,

http://docs.webplatform.org/wiki/WPD:Getting_Started

Tuesday, April 3, 2012

DOM Introduction Slides

Today we covered javascript DOM in the class, here is the slide we used today.

Monday, April 2, 2012

jQuery how to scroll to particular line in textarea

Recently I was working with outputting formatted source code in a textarea, and the requirement is you have a control "sidebar", which is a list, that allow user to click on and the textarea will scroll to particular line accordingly.

In jQuery, when you use the below. the textarea will scroll to the top

$('.my_class_for_this_textarea').animate({ scrollTop: 0 });

However, in my case, the sidebar list only tells you the code is in line 100 for example.  How to make sure you tell jQuery to scroll to the correct line every time??

scrollTop  takes "pixels", and you need to find out your pixel of each line is. And the following is the formular.

$('.my_class_for_this_textarea').animate({
  scrollTop: my_relative_line_number * LINE_PIXEL
}); 

The correct way to get mouse coordinates

I still saw some developers try to use different formular / ways to find out the mouse coordinates.  Well, according to the documentation, there is always only one correct cross-browser way to find out the real mouse coordinates   relative to the browser.   (  Note: mouse coordinates relative to your computer screen is not very useful for most of our cases, so the below is mouse coordinates relative to browser. )

Here is how the recommended implementation looks like :)
function myCallBack(e) {
 var posx = 0;
 var posy = 0;
 if (!e) var e = window.event;
 if (e.pageX || e.pageY)  {
  posx = e.pageX;
  posy = e.pageY;
 }
 else if (e.clientX || e.clientY)  {
  posx = e.clientX + document.body.scrollLeft
   + document.documentElement.scrollLeft;
  posy = e.clientY + document.body.scrollTop
   + document.documentElement.scrollTop;
 }
 // posx and posy contain the mouse position relative to the document
}

Wednesday, March 28, 2012

Javascript Date return NaN in IE 8

Well, UTC suppose to be universal date-time format, but when I do Date.parse() or new Date() with UTC string in IE8, it returns null / NaN  ( while all the browser, including IE9, works ).  Well, it turns out that IE 6 - 8 doesn't understand UTC date-time format :)  Not surprise though, it is IE after-all.

This website has a metrics of javascript Date support for all browsers, pretty handy.
http://dygraphs.com/date-formats.html

One of the solutions is to override Date.parse() when the browser is an IE.

Tuesday, March 27, 2012

Javascript Constructor return rules

Tonight we have a student asked about what if we return a primitive types in a constructor function, like the below:

function Person() {
   this.name = "Roy";
   return "abc";
}

What would be the return if we instantiate this constructor?

var me = new Person();
console.log(me); // what would you expect to see??

The result is you will get an instance of "Person".  Some people may question "the return was a string, how come it still return an instance of Person?"   Well, it is all related to the "new" keyword.

Whenever you instantiate a constructor ( or a Class ) using "new" keyword.  The javascript interpreter will enforce you to return an object.  If you do not return an object ( just like the above ), the javascript interpreter will enforce this rule by returning an instance of a current constructor.

So it will be similar to the following:

function Person() {
   this.name = "Roy";
   return this;
   //return "abc";
}

However, if you define an object at the return, the javascript interpreter won't care about it.

function Person() {
   this.name = "Roy";
   return { name: "Joyce" };
}

The above code works because it is returning an object, but it won't be an instance of Person.

So, remember, if you return a "primitive types" in a constructor, when you instantiate the constructor with a "new" keyword, you will always get the instance of the Constructor back.  However, if you return an object, you won't have any issue.

Wednesday, March 21, 2012

Javascript Garbage Collection

There's a student yesterday asking about garbage collection in Javascript.  And here it is how it works from  a high level perspective.

Memory is allocated to objects when they created and reclaimed by the browser when there are no more reference to it.  A garbage collection is a mechanism that saved developer time or effort from explicitly performing memory management task and its main duty is to  determine when it is safe to reclaim the memory.   Of course, if an item is still being referenced or being used, it won't collect those memory.   It only collects the memory from objects that are no longer reachable or referenced.

But how does that works?  Well, most garbage collection is using different variants of "Mark-and-Sweep" method/algorithm.  In Javascript, it travsed periodically all the variables and objects and mark items that are still being used or referenced. And it follows with the "sweep" step, it sweep any "unmark" items and reclaim the memory back by deallocating those.

Ok, so how does those information help us?  

In Javascript, global scope variables are not garbage collectable and presenting opportunity for a memory leak, and it explains why we need to limit the usage of global variables in our program.  ( There are many reasons why you should limit the use of global variables, this is just one of the reasons ).

Whenever you create an object using a "new" statement, use a delete statement to explicitly destroy it when it is no longer needed.  This step ensures the memory of that object will be available to the garbage collection.

There is a blog post more on this topic:
http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53038.aspx

Tuesday, March 20, 2012

HTML5 Community Night


5:00 - 6:00 pm      Registration, Demo showcase, Social, food, drink
6:00 - 6:30 pm      Kick off  (Doris Chen, Ann Burkett, Kevin Nilson)
6:30 - 7:10 pm      The Graphical Web - Fostering Creativity (Adobe: Vincent Hardy)
7:10 – 7:50 pm      Dart (Google: Seth Ladd)
7:50 – 8:00 pm      break
8:00 - 8:20  pm     WebFWD (Mozilla: Diane Bisgeier)
8:20 - 9:00  pm     Behind The Scenes of Cut The Rope (Microsoft: Giorgio Sardo)
9:00 - 9:30 pm      Panel Discussion & Q&A (Kevin Neilson, Vincent, Seth, Giorgio)
9:30 - 9:40  pm     Give Away and Wrap

Saturday, February 18, 2012

TSG Javascript Programming - Part I




Title
TSG Javascript Programming - Part I

Prerequisite
This class ( Part I ) does not requires any javascript background, but basic knowledge on HTML and CSS is preferred.

Location
G5 ROLCC -  Please click the logo below for more detail on TSG location.

Cost
$65 Dollars

Date & Time
Time will be 7:30 pm - 9:15 pm
  • 3/06/12 ~ Basic Introduction - Doing Javascript The Right Way
  • 3/13/12 ~ The Building Blocks of Javascript
  • 3/20/12 ~ Array and Functions
  • 3/27/12 ~ Creating Objects 
  • 4/03/12 ~ Document Object Model
  • 4/10/12 ~ Field Trip to HTML5 conference
  • 4/17/12 ~ DOM Interaction Hands on Session / Debugging Javascript






Description
This JavaScript course provides the knowledge necessary to design and develop dynamic Web pages using JavaScript. It introduces participants to JavaScript and how the language can be used to turn static pages into dynamic, interactive Web pages.  Besides learning the syntax of the JavaScript language, other additional topics may include the Document Object Model, form validation, how to create functions, and how to create your own script files.  At the end of this class, participants will have the knowledge necessary to utilize the power of JavaScript to provide dynamic content on their Web sites.  We will reserve 30 minutes each class for hands on session, so please bring your laptop when you come to the class. [Note] Feel free to leave comments or send me email if you have any questions.  Thanks. 


[ Note ]
We don't have an assigned book in this class, but if you are new to javascript, I would recommend this one.
http://www.amazon.com/Simply-JavaScript-Kevin-Yank/dp/0980285801/ref=sr_1_1?ie=UTF8&qid=1331147166&sr=8-1
...
What's Next  (Future Classes)
For Javascript Programming Level II, here is the proposed schedule.
  • Javascript Events
  • Form Handling and Validation
  • Javascript Events II
  • JSON and Ajax
  • Javascript Animation
  • Introduction to JQuery

For Javascript Programming Level III, here is the proposed schedule.
  • Closures
  • Scopes and Prototypes
  • Javascript Object Oriented Programming
  • Javascript Design Pattern - Part I
  • Javascript Design Pattern - Part II
  • Introduction to Events Driven Development
...
There will be one more class as the last of this Javascript Programming Series.  Instead of calling it Javascript Programming Level IV, let's called that "Let's start your Javascript Ninja Road Trip".

Let's start your Javascript Ninja Road Trip, here is the proposed schedule
  • Common mistakes in Javascript development
  • Understand your Javascript Engine
  • Writing high Performance Javascript
  • Dive deeper into Events Driven Development
  • Introduction to Server Side Javascript and Persistent Layer using Javascript
  • Design your custom Javascript Framework

Thursday, January 26, 2012

Twitter bootstrap popover doesn't work with click event

We were playing with the Twitter bootstrap javascript library lately,  and found out the popover doesn't play well with 'click' event in Chrome (FF works though).  I tried to find solution on the web, but didn't find what we want or the solution doesn't work. Hopefully this post might provide a solution that can help others.

The way we get around this is to wrap the popover call inside a callback which listen to click.
        // ... probably in your initialize function
        $('my-selector').bind('click', this.showPopover);

        // ... somewhere inside an object
        showPopover: function(e){
            var $popTrigger = $(e.target),
                $closeBtn = $('.popover .close-btn');

            $closeBtn.trigger("click");

            (function(that){
                $popTrigger.popover({
                    html:true,
                    placement:'below',
                    offset:8,
                    trigger:'manual',
                    title:function () {
                        return "Well, title!"
                    },
                    content:function () {
                        return that.getContent();
                    }
                });
            })(this);

            $popTrigger.popover("show");

            $closeBtn.live('click', function(e){
                $popTrigger.popover("hide");
                e.preventDefault();
            });

            e.preventDefault();
        }


You can enhance the code by checking if the elements already have desired events attached, so you don't need to trigger that twice.  And if you are designing a one page app, you may need to add function to  hide/remove the popover when the page context is changing.

Wednesday, January 4, 2012

Another good javascript interview question

I was debugging some Node.js code recently and found a bug that is so obvious but very easy to get that  to creep in if you are not careful enough. The following code is just a sample, not reflecting the real code that I'm working on.

The buggy version
Do you see the problem??  That could be one of the interview questions for my next candidate.  I can think of  three different ways to solve this scope issue, two of them are pretty standard, the other one is more elegant :)  Can you think of at least one?

(function() {
//...
for ( key in MyModules){
    if(MyModules.hasOwnProperty(key)){
        module = MyModules[key];
        // if you're not coming from Node.js, the code 
        // inside will get execute during runtime
        app.get(module.regEx ,function(req,res,next){
            module.router(req,res,next,module.collection); 
        });
    }
}
//...
}());

As a javascript developer, the basic minimal concepts we should know before going into an interview would be "prototype, scope and closure".  Because from those concepts, one can generate different patterns out from them.


Thursday, December 8, 2011

Useful HTML5 Resources

Collecting links for HTML5 resources, let me know if you found other good links as well. Enjoy!

W3Schools
http://www.w3schools.com/html5/default.asp

W3Fool  ( An anti-W3Schools campaign )
http://w3fools.com/

Dive Into HTML5
http://diveintohtml5.org/

HTML5 Glossary

HTML5 - edition for web developers

Sites using HTML5 markup
http://www.html5arena.com

Accessibility
http://www.html5accessibility.com/

The Expressive Web

HTML5 Canvas Tutorials
http://www.html5canvastutorials.com

Can I use

HTML5 Test / Browsers Compatibility
http://www.html5test.com

HTML5 Security
http://html5sec.org/

How to order you head section

Juude Blog about HTML5
http://juude.info/html5-layout.php

Best CSS3 Resources
http://www.linkedin.com/news?viewArticle=&articleID=784509223&gid=2071438&type=member&item=71538466&articleURL=http%3A%2F%2Fstylishwebdesigner%2Ecom%2F150-excellent-css3-tutorials-to-make-you-a-stylish-web-designer%2F&urlhash=U0xc&goback=%2Egde_2071438_member_71538466

Efficiently Rendering CSS

Best CSS3 Utilities
http://iroylabs.blogspot.com/2011/09/best-css3-utilities.html

10 Tools to simplify HTML5
http://www.catswhocode.com/blog/10-online-tools-to-simplify-html5-coding

Make old IE to understand HTML5 
http://code.google.com/p/html5shiv/

HTML5 Polyfills
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

Thursday, October 13, 2011

jQuery Plugin Patterns

Here are some jQuery Plugin Patterns, the list is still expanding.  This post is mostly for my own reference, but just blog it here in case someone might be helped from this.

One note before you start doing your super fancy plugin.  The 'this' keyword in the immediate scope of the plugin is referring to the jQuery object, so there is no need to do $(this).  


Basic Form


  $.fn.yourPlugin = function(options, callback) {
    // ...
  };



Wrapped in Closure to create namespace

;(function($, window, undefined) {
  $.fn.yourPlugin = function(options, callback) {
    // ...
  };
})(jQuery, window);



Define multiple related functions (or related plugins) in one shot. 

;(function($, window, undefined) {
  $.extend($.fn, {
     yourPlugin: function() {
        // ...
     },
     yourSecondPlugin: function() {
        // ...
     }
  });
})(jQuery, window);


Prototype way

;(function($, window, undefined) {
  var pluginName = 'yourPlugin', pluginDefaultOptions = {};

  function Plugin(el, options) {
    this.element = el;
    this.options = $.extend({}, pluginDefaultOptions, options);
    this._name = pluginName;
    this.init();
  }  

  Plugin.prototype.init = function() {
    // ...
  }

  // make sure only one instance is instantiated
  $.fn[pluginName] = function ( options ) {
    return this.each(function () {
       if (!$.data(this, 'plugin_' + pluginName)) {
           $.data(this, 'plugin_' + pluginName,
           new Plugin( this, options ));
       }
    });
  }

})(jQuery, window);


Object Literal way

;(function($, window, undefined) {

    $.fn.pluginName = function(method) {

        var methods = {
            init : function(options) {
                this.pluginName.settings = $.extend({}, 
                                             this.pluginName.defaults, 
                                             options);
                return this.each(function() {
                    var $element = $(this), 
                         element = this;  
                    // ...
                });
            },

            my_public_method: function() {
                // ...
            }
        }

        var helpers = {
            my_private_method: function() {
                // ...
            }
        }

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method "' +  method + '" does not exist in pluginName plugin!');
        }
    }

    $.fn.pluginName.defaults = {
        foo: 'bar'
    }

    $.fn.pluginName.settings = {}

})(jQuery, window);



Modified Object Literal way

;(function($, window, undefined){
    $.fn.packagename = function(options, callback){
        
        var params = $.extend({},
                        $.fn.packagename.default_options, options), 
                        $that = $(this);
        
        if($.isFunction(options)){
            callback = options;
            options = {};
        } 
        
        var methods = {
            init: function() {
               // ... 
            }
        }
        
        methods.init.apply(this,[]);      
    }
    
    $.fn.packagename.default_options = {
       src: ".data" 
    }
})(jQuery, window);






Monday, October 3, 2011

TSG HTML5 Class for Beginners


Want to learn the current hottest buzz in web development - HMTL5 ??  Yes , it is very hot out there now!!





I will be teaching an HTML5 class for Beginners.  I will cover HTML5 new elements, CSS3 and  javascript API ( e.g, canvas, geo-location and more ).  For more details, please visit their website.  You should see HTML5 in their "Current Classes" section.

Please go to TSG website to register if you are interested.

Date & Place

10/25, 11/1,8,15,22 total 5 meets from 7:30 pm to 9:30pm at G10, ROLCC

Course Detail

  1. HTML5, CSS3 Introduction and Survey
  2. New HTML5 elements and Structuring a page
  3. Dwelling Deeper in CSS3
  4. HTML5 javascript APIs introduction
  5. Projects Demo, and what other thing you should know before going to interview
Each Session will have 30 mins hands on practice lab, so please do bring your laptop. This course is trying to get you understand the basic of HTML5 stack and how the industry is utilizing this hot tech buzz currently. It will be helpful if you have basic experience in HTML and CSS, but not required. See you there!





Thursday, September 29, 2011

Funny Bugs Make Good Interview Questions

I'm currently collecting my set of standard interview questions for future candidates.  The following is one of the those which would be in my list, and it is coming from a bug that I found recently.

I was tracing some bugs few weeks ago and found out the following code snippets ( well, it is a modified version ).

Can you spot any potential problems for the following code?


filterResult: function(query, collection) { 
  var matches = [];
  var resLen = collection ? collection.length : 0;       
  for (var i = 0; i < resLen; i++) {            
    var item = collection[i];
    var itemStr = (item.name + com.search.ResultCache.PIECE_DELIM + item.id).toLowerCase();          
    if (itemStr.indexOf(query) != -1) {
 matches.push(item);
    }
  }
  return matches;
}


And my next question would be asking from performance and best practice points of view, how they could enhance this code.

Actually fixing this bug doesn't take that long, but the process of hunting this bug and tracing the logic is tedious.  The function works 99.9% of time, but it failed on a small number of test cases.  And the process of collecting failed cases and understanding the relationship among those failed test cases took quite some patience.  But seriously, it is fun :)