Creating classes in JavaScript

Goal:
Creating class instances in JavaScript is not available since you define "classes" in js with object literals. In order to create classical classes like you would in c#, ruby, java, etc, with inheritance and instances.

Rather than typical class definitions using object literals, js has a constructor function and the NEW operator that will allow you to new-up a class and optionally provide initial properties to initialize the new object with.

The new operator changes the function's context and behavior of the return statement.

var Person = function(name) {
   this.name = name;
};   

//Init the person
var dude= new Person("renso");

//Validate the instance
assert(dude instanceof Person);

When a constructor function is called with the new keyword, the context changes from global window to a new and empty context specific to the instance; "this" will refer in this case to the "dude" context.

Here is class pattern that you will need to define your own CLASS emulation library:

var Class = function() {
   var _class = function() {
      this.init.apply(this, arguments);
   };
   _class.prototype.init = function(){};
   return _class;
}

var Person a new Class();

Person.prototype.init = function() {
};

var person = new Person;

In order for the class emulator to support adding functions and properties to static classes as well as object instances of People, change the emulator:

var Class = function() {
   var _class = function() {
      this.init.apply(this, arguments);
   };
   _class.prototype.init = function(){};

   _class.fn = _class.prototype;

   _class.fn.parent = _class;

   //adding class properties
   _class.extend = function(obj) {
      var extended = obj.extended;
      for(var i in obj) {
         _class[i] = obj[i];
      };
      if(extended) extended(_class);
   };

   //adding new instances
   _class.include = function(obj) {
      var included = obj.included;
      for(var i in obj) {
         _class.fn[i] = obj[i];
      };
      if(included) included(_class);
   };
   return _class;
}

Now you can use it to create and extend your own object instances:

//adding static functions to the class Person
var Person = new Class();

Person.extend({
   find: function(name) {/*....*/},   
   delete: function(id) {/*....*/},
});

//calling static function find
var person = Person.find('renso');
   
//adding properties and functions to the class' prototype so that they are available on instances of the class Person
var Person = new Class;

Person.extend({
   save: function(name) {/*....*/},
   delete: function(id) {/*....*/}
});

var dude = new Person;

//calling instance function
dude.save('renso');

CSS hack for Google Chrome and Safari

When wanting to hack css in an external stylesheet just for Google Chrome and Safari. Here is an example of where I override the margin-top for Chrome and Safari.

Normal:

#AccountMaintenanceWrapper #callDetailsPreviewWrapper
{
    border: none;
    padding: 0px;
    width: 209px;
    position: fixed;
    margin-top: 84px;
    z-index: 1;
}


Google Chrome and Safari:
@media screen and (-webkit-min-device-pixel-ratio:0)
{

    #AccountMaintenanceWrapper #callDetailsPreviewWrapper
    {
        margin-top: 12px;
    }
}

Why CoffeeScript is an issue

Other than some obvious concerns, my main concern is support in the open source community. "anon" from the CoffeeScript team sent this to me after I requested input from the team to concerns I raised and wanted to get others' take on it:

"Thanks for confirming that only idiots willingly program in Java and C#"

or the following from the same person:

"Oh and finally, you should definitely create jShort. Even though I know you will fail before you even start, I would love to laugh at your attempts and it would be perfect for you since you ride the short bus. "

This kind of comment reflects badly on the CoffeeScript team and hence not an option for us as a company to consider. Another example of why some open-source community projects get no traction.

Twitter Bootstrap with jQuery-ui fixes for jqGrid

Issue:
Using Twitter Bootstrap with jQuery-ui causes all kinds of issues with jqGrid.

Goal:
Provide css to fix jqGrid display issues. This document is a work in progress and will continue to add. Please reply to me if you found this useful or have any suggestions.

Solutions:

Create a css (scss SASS style) file and include it after jQuery-ui stylesheet.

1. Issue with the grid lines looking faded
.ui-jqgrid {
    .ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary {
        opacity: 1;
    }
}

2. Pager textbox and number of rows drop down box text issues
.ui-jqgrid {
    .ui-pg-selbox, .ui-pg-input {
        width: inherit;
        border: none;
        padding: 1px;
    }
}


CoffeeScript - inability to support progressive adoption

First if, what is CoffeeScript?
Web definitions
  • CoffeeScript is a programming language that compiles statement-by-statement to JavaScript. The language adds syntactic sugar inspired by Ruby and Python to enhance JavaScript's brevity and readability, as well as adding more sophisticated features like array comprehension and pattern matching.
The issue with CoffeeScript is that it eliminates any progressive adoption. It is a purist approach, kind of like the Amish, if you're not borne Amish, tough luck. So for folks with thousands of lines of JavaScript code will have a tough time to convert it to CoffeeScript. You can use the js2coffee API to convert the JavaScript file to CoffeeScript but in my experience that had trouble converting the files. It would convert the file to CoffeeScript without any complaints, but then when trying to generate the CoffeeScript file got errors with guess what: INDENTATION!

Tried to convince the CoffeeScript community on github but got lots of push-back to progressive adoption with comments like "stupid", "crap", "child's comportment", "it's like Ruby, Python", "legacy code" etc. As a matter of interest one of the first comments were that the code needs to be re-designed before converted to CoffeeScript. Well I rest my case then :-)

So far the community on github has been very reluctant to even consider introducing some way to define code-blocks, obviously curly braces is not an option as they use it for json object definitions. They also have no consideration for a progressive adoption where some, if not all, JavaScript syntax will be allowed which means all of us in the real world that have thousands of lines of JavaScript will have a real issue converting it over. Worst, I for one lack the confidence that tools like js2coffee will provide the correct indentation that will determine the flow of control in your code!!! Actually it is hard for me to find enough justification for using spaces or tabs to control the flow of code. It is no wonder that C#, C, C++, Java, all enterprise-scale frameworks still use curly braces. Have never seen an enterprise app built with Ruby or PhP.

Let me know what your concerns are with CoffeeScript and how you dealt with large scale JavaScript conversions to CoffeeScript.




Why CoffeeScript is tough to maintain

I recently started trying out CoffeeScript only to find out that it caused more headaches. The abstraction level of jQuery was perfect, it did not dictate to coders how to design their code, it just works. However, I recently posted a request to the CoffeeScript team to consider introducing curly braces to help with more complex code to control the flow of logic. For example a if-then-else with many nested levels can be near impossible to debug without tracing through it when using CoffeeScript. Also with IDEs like Visual Studio, regular JavaScript intellicense and auto-formatting make it easy to appropriate indent nested levels without any work on the part of the developer and reading it is not that hard, especially with some extensions that show vertical lines in the code editor to help see what is nested within what part of the code.

However with CoffeeScript that is not the case. The samples given in the CoffeeScript web site are of course just simple examples to explain the features and one gets excited pretty quick over the powerful shortcuts. I tried to convert a piece of JavaScript over to CoffeeScript and gave up since you need to first of all remove ALL non CoffeeScript coding constructs for it to even compile. However js2coffee can help with that. However to keep track of nested levels became something that was simply not manageable using CoffeeScript.

Furthermore, any coding language that controls the flow of logic by indentation is extremely dangerous for obvious reasons. I liked CoffeeScript a lot, but the fact that the logical flow of the code is controlled by how much you indent code, spaces or tabs, is not reliable as there is no way the programmer has an easy way of knowing what parts of the code will get hit when the code spans a page.

When I suggested introducing curly braces in CoffeeScript the team, one contributor advised me that my code needs to be re-designed! Needless to say that is absurd. When I included a piece of the code he asked my if it was legacy code. It's like saying to a Java programmer, sorry you cannot use Java because we don't agree with how you write your code.

jashkenas from the CoffeeScript blog gave some great suggestions and made the point that introducing curly braces would be very problematic for them as they use them to denote objects. Makes sense, but I would still love to see some way to replace code flow control with spaces and indentation to something more concrete and human readable.

Updated: 10/18/2012
After running into some more issues with logic errors, try and debug using Firefox's Firebug. Guess what, now that I found the code that needs to be corrected, I have to find that corresponding code in my CoffeeScript file! You guessed it, you cannot debug CoffeeScript, only the generated code and have to work backwards to find the issue in your CoffeeScript file.

Castle Windsor Dependency Injection with MVC4: No component for supporting the service

Problem:
Installed MVC4 on my local and ran a MVC3 app and got an error where Castle Windsor was unable to resolve any controllers' constructor injections. It failed with "No component for supporting the service....".

As soon as I uninstall MVC4 beta, the problem vanishes like magic?!

I also tried to upgrade to NHibernate 3 and Castle and Castle Windsor to version 3 (from version 2), but since I use Rhino Commons, that is not possible as the Rhino Commons project looks like is no longer supported and requests to upgrade it to work with NHibernate version 3 two years ago has gone unanswered. The problem is that Rhino Commons (the older version) references a method in Castle version 2 that has been depreciated in version 3: "CreateContainer("windsor.boo")' threw an exception of type 'System.MissingMethodException."

Hope this helps anyone else who runs into this issue. Btw I used NuGet package manager to install the correct packages so I know that is not the issue.

Restoring windows path on Windows 7

Issue:
You changed the windows path and made a mistake and now want to reset it.

Solution:
In short, you can't. If you restore to the system default, you will loose any paths that were appended when you or the manufacturer installed software and drivers. Each time you install some sort of software or driver, MS Office, Turbotax, etc., it creates/appends to the path so that it points to it's start-up program.

Too late now, but you should create a restore point BEFORE you touch the windows path if you are not sure what you are doing:


At a minimum you need the following:

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\

AT worst you can reset it to the above, and go through each application as you use them and run into problems to fix the path. The REPAIR option when you select to change/uninstall a program can help with that.

Sass vs Less

I know there are afew places where you can check out the differences between Sass or Less, but I thought it may be helpful for others to know why I chose one over the other.

Here are some of my sources:
  • http://sass-lang.com/
  • http://www.dotlesscss.org/
  • http://stackoverflow.com/questions/8411066/less-vs-sass-vs
  • http://coding.smashingmagazine.com/2011/09/09/an-introduction-to-less-and-comparison-to-sass/


Since my main decision was affected by my IDE I need to mention my development environment:
Visual Studio 2010 with Mindscape's Web Workbench

In short I chose Sass (Syntactically Awesome Style Sheet). My main reason was that when you save the file in VS, it automatically regenerates the CSS file for SCSS on the fly, so you are able to see right away what CSS is being generated and can run your app right away. I am not in the favor of Less in this regard, as although you can specify set of handlers etc to interpret the less file on the fly, I would never use it to interpret on the fly, especially not on production servers.

Also the Ruby team now ships officially with CoffeeScript and Sass by default and will be included by default in the gems when you deploy your Ruby app. Maybe another reason to use it if you're in the Rails framework.

Any comments very welcome as I am am not sure if my assumptions and assertions are true.

Searching for multiple files in Windows 7 Search

Goal:

Searching for more than one file in the windows search feature in windows explorer. For example I want to search for different types of images, tif, gif, jpg, etc or file names that contain different content, like ".net", or "asp", or "c#".

Solution:

Open windows explorer, hit function key F3, or ctrl+f.

In the search box that now appears at the top right hand corner of the screen type in your search criteria. If you now want to search for different file types for example use the "OR" operator:

*.jpg OR *.tif OR *.gif OR *.png

This will search for any file with those extensions. be sure to use an UPPERCASE "OR".
Twitter