Creating a simple namespace for a jquery plugin

Posted: Tuesday October 8th, 2013 in jQuery

A few days ago I wanted to create some simple plugins that required to use a selector or the jQuery global namespace (without cluttering it), but I did not wanted to use all the jQuery UI widget structure. Then I came up with a nice pattern to do this:

$.app = function( name, fn ) {
	$.app[ name ] = fn;
	$.fn.app = function( plugin ) {
		var args = [].slice.call( arguments, 1 );
		return $.app[ plugin ].apply( this, args );
	};
};
$.app( "plugin", function() {} );

// Result
$.app.plugin; // [Function object]
$.fn.app.plugin; // [Function object]

QUnit & feature detection

Posted: Friday May 17th, 2013 in Javascript, Testing

A few months back someone posted a suggestion on QUnit for the inclusion of a “skip” feature. The idea, as far as I remember, was to highlight a test that wasn’t developed yet and allow the use of conditions to identify a given feature in a browser (and keep highlighting the test).

In the end of discussion the issue was denied for landing into the core and a suggestion was made for the creation of a plugin.

A pending test is really useful because it allows the use of TDD over distinct parts and the easy differentiation of what is being implemented but failing and what is not implemented yet, besides it serves as a flag for non deterministic tests in a production environment. Even every test framework I know implements some “pending” feature for that purpose.

A feature detection API inside QUnit is not a good idea. It encourages the use of complex conditions in an environment that should be clear and precise. Besides it is out of the scope of QUnit.

Still you should take care when developing a test in Javascript. Some times a beginner developer tries to do something more dynamic and ends up turning your suite into a spaggetti.

Some practices could be done to avoid that to happen when working feature detection in Javascript:

Use feature detection as a first statement inside a test

Always check if a browser does not support a given feature to test it, otherwise create a default passing assertion with a simple description.

Always use “expect()” in the beggining of a test declaration

QUnit team is planning to deprecate the use of expected as a second argument of a test. Therefore you should always use the “expect(x)” as a first statement in a text, if feature detection is required you should put just below the condition.

Do not test more than necessary

Do not exaggerate in the assertions. A test should check an specific funcionality and be clear in the description

The result would something like:

test( "Testing key filtering", function() {
    if ( !Object.keys ) {
        ok( true, "Unsupported Browser" );
    }
    expect( 3 );
    ...
});

Of course, you could use Modernizr or extend QUnit to implement similar functionality. But if you want something fast and that have a considerable efficiency this model is something to get started. Maybe even document in the style guide of your company to avoid diversion by the other collaborators.

Coding and Power Metal

Posted: Friday May 17th, 2013 in Misc, Music

They say a developer needs a quiet environment to produce properly, it keeps you focused from external factors.
Of course this is one of the alternatives.

When we are focused in front of the computer usually we find what is a perfect “zone”. It’s a zona of high focus where you concentrate only in what you are doing and do not notice the time passing. Each one has a method to enter into this “zone” and one of the main triggers is a satisfactory, scalable and smart implementation (not that Extreme go Horse, which causes high stress and lack of production for having to reinvent the wheel every time over and over again).

Some like me are able to focus listening music. In that moment you shut down the external world and focus only in what you are doing. The music sound acts like a barrier shutting yourself from external worries and forcing you to concentrate in what is in front of you.

Code listening bands like Avantasia, Rhapsody of Fire or Blind Guardian is something someone should try some day.

(Português) BrazilJS 2012

Posted: Monday September 10th, 2012 in BrazilJS, Eventos
Tags: , ,

Sorry, this entry is only available in Português.

Javascript ReplaceAll

Posted: Tuesday March 27th, 2012 in Javascript, Snippet

I always used to copy a method to simulate a replaceAll with the javascript’s prototype, never thinking about speed. Now I decided to go and create a method by myself that do this and also allows you to ignore the case. The only bad thing (or not) is that you can’t use regex, just regular strings =(.
The example below uses all the possible stuff I could to create a faster and compact replaceAll method:

/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
    var _token;
    var str = this + "";
    var i = -1;
    
    if ( typeof token === "string" ) {
        
        if ( ignoreCase ) {
            
            _token = token.toLowerCase();
            
            while( (
                i = str.toLowerCase().indexOf(
                    token, i >= 0 ? i + newToken.length : 0
                ) ) !== -1
            ) {
                str = str.substring( 0, i ) +
                    newToken +
                    str.substring( i + token.length );
            }
            
        } else {
            return this.split( token ).join( newToken );
        }
        
    }
return str;
};

Read the rest of this entry »

JQuery Table Filter (jQuery 1.7+)

Posted: Saturday March 24th, 2012 in Javascript, jQuery, Project
I’ve created a system to filter the text of a TD within a table and, based in a specific algorythm, show only the desired TRs. It works with the following rules:
  • Given a table with thead and tbody, jQuery Table Filter creates an input below all TDs of theads that automatically filters the content based on the innerHTML of each TD of the tbody
  • The TRs that don’t match with desired filter are hidden and any input inside any TD is disabled (the input is enabled when the TR is visible again)
  • The filter verifies the content splitting each word as it is a different search (“A test” matches with “A – test” and “test A”)
  • The only requirement for the use of this plugin is that it is used ONLY in a table with at least a thead, th and tbody
  • It is created a TR that informs the user when a filter did not return any result. It is positioned below the last TR of the tfoot. If there’s no tfoot, jQuery Table Filter creates it.
Read the rest of this entry »

Javascript Date Format

Posted: Friday February 17th, 2012 in Javascript, Project
Tags: ,

Searching the web I could not find a date formatter in javascript that could suit my needs.

What I wanted was a way to parse / format any time trying not to implement all methods in the prototype of the Date object. Also choose freely the template to be used, allowing to write certain variables rather than replace individual letters. I’m used with the SimpleDateFormat class in Java, which gave me great ideas.

At the end achieved the following results, which works as follows:

//By default it has the week names in portuguese, but it is easly manipulated.
//The only problem is the parse, which currently has the BR date format
//Formatting the current date to String
var currDate = new Date();
var dateFormat = new JSDateFormat("Current Date: %d%d/%M%M/%y%y%y%y. Time: %H%H:%m%m:%s%s. The week day is %WEEK");
dateFormat.format(currDate); //Current Date: 17/02/2012. Time: 21:07:20. The week day is Sexta-Feira

//Parsing
var dateFormat = new JSDateFormat();
dateFormat.getDateObj("15/05/2012 15:33:45"); //return the Date Object with the given time set

The method format() is free for any kind of string (since avoided the use of “%”):

/**
* %d - Day of Month (01, 02...20,21)
* %M - Month of Year (03, 04...11, 12)
* %y - Year (001990, 02008, 2009, 009, 09, 9)
* %h - Time AM/PM (00, 01...11, 12)
* %H - Day Time (00, 01...17, 18)
* %m - Minutes in Hour (05, 06...50, 51...59, 60)
* %s - Seconds in minutes (05, 06...50, 51...59, 60)
* %a - Return the post/ante meridiem (AM, PM)
* %WEEK - Day of week (Domingo, Segunda-Feira...Sexta-Feira, Sábado)
*/

THe only method that is kind of restrict is the getDateObj() which only make the parse of pre-defined strings:

/**
* Date:
* xx/xx/xxxx - day/month/year
* xx-xx-xxxx - day-month-year
* Time:
* xx:xx - hour:minute
* xx:xx:xx - hour:minute:second
* Date/Time:
* xx/xx/xxxx xx:xx:xx
* xx/xx/xxxx xx:xx
* xx-xx-xxxx xx:xx:xx
* xx-xx-xxxx xx:xx
*/

Questions/Sugestions?

To download click here

Hello World!

Posted: Friday February 10th, 2012 in Misc

Hello World, my first post has been thrown!

The purpose of this blog is to share codes and opinions about Javascript or anything related to technology (which include but is not limited to WEB stuff and jQuery plugins)

Let’s see how it goes!


//Testing "code" tag
//Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};