Sunday, August 7, 2016

Cramming for a Senior JavaScript Interview


I have made JavaScript a major part of my development career for a decade now (since the >shudder<  IE6 days!) so I have had my fair share of JavaScript interviews.  If I have not been in an interview for even a few months I try to cram the important topics that do not come up at work too often.  The simplest way to do that is review all the parts of:

JavaScript: The Good Parts   by Douglas Crockford

that I highlighted and marked the crap out of years ago. 

In the following post, I will summarize the most useful concepts from that book as well as some of the questions I have been asked numerous times. This is intended to help experienced JavaScript developers review important concepts for interview purposes.  This is not an ideal interview prep guide for beginners.

Since Douglas Crockford has spent roughly two decades explaining JavaScript concepts, it’s no surprise he simply says it better than most so the longer quotations are simply direct quotes from his book.

First quick concepts worth knowing but are easily forgotten . .

Data Types
  • Six data types that are primitives (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)
    • Boolean
    • Null
    • Undefined
    • Number
    • String
    • Symbol (new in ECMAScript 6)
  • So there is ONE number type
    • But NaN  . . is also a number
    • Note: isNan() is available
  • For Strings and arrays
    • .length  (note it’s not a function but a property)
What is the difference between Call vs apply vs Bind?
  • Said best here:
    • Call invokes the function and allows you to pass in arguments one by one (listed explicitly).
    • Apply invokes the function and allows you to pass in arguments as an array.
    • Bind returns a new function, allowing you to pass in a this array and any number of arguments.
  • And this might be the best stackoverflow answer ever:
    • The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."
    • Pseudo syntax:
      • theFunction.apply(valueForThis, arrayOfArgs)
      • theFunction.call(valueForThis, arg1, arg2, ...)
What is strict mode?
  • By putting "use strict"; at the top of your code, the interpreter will throw more errors for bad practices that are technically permitted.  The major effect is it forces you to declare your variables properly and avoid using variable names that will someday be keywords.

Conditionals


  • What is the difference between == and ===?
    • === means “equality without type coercion” but == means that the second value will be converted to the data type of the first so that “equivalency” can be determined.
  • True vs False
    • Usually the concept of true and false is referred to as falsy vs truthy because the list of data types you might put in a conditional are a bit sketchy and not exactly in line with math books
    • This is explained well here but in short:
      • falsy: In javascript 6 things are falsy and they are- false, null, undefined, '', 0, NaN
      • truthy: There are only two truthy things- true and everything that is not false
    • all_things_code points out:

null == true; //false

null == false; //false!!

Objects

  • ALL objects are linked to a prototype object.  If you didn’t specify which after creating it, its prototype is pointing to Object.prototype
  • When attempting to find a property in an object, the prototype object will be searched if the object in question is missing said value through a process called delegation.
  • You can for-loop your way through the properties (not methods) of an object[1]:


    for (name in objectInstance) {
               //use name
    }        

Functions

  • “A function encloses a set of statements. Functions are the fundamental modular unit of JavaScript.”
  • “Function objects are linked to Function.prototype (which itself is linked to Object.prototype)."
  • “The Function object created by a function literal contains a link to the outer context.  This is called closure.  This is the source of enormous power.” 

this

  • Is established at invocation of a function
  • The value is determined by the invocation pattern used
    • The method invocation
      • When a function is a member of an object
      • this is bound to that object
    • The function invocation
      • When a function is NOT a member of an object
      • this is bound to global object (see also this)
    • The construction invocation
      • When a function is invoked with the new prefix . . this is bound to that new object.
    • The apply invocation
      • apply simply let’s you control what this is.
  • Return
    • If the function was invoked with the new prefix and the return value is not an object, then this (the new object) is returned instead
  • Modules
    • A module is a function or object that presents an interface but hides its state and implementation
    • See also the “Immediately Invoked Function Expressions (IIFE)
    • Summarized best here
  • Cascading
    • Using a paradigm where some functions do not return values but instead change some kind of state and then return this, we can chain events and enable cascading:
      • Jquery applications use this a lot!
      • $('#bobsDiv').on('mouseup').styleChange('background-color', 'grey')

Arrays

  • Note typeof(anArray) returns “object” so often you will also want to use Array.isArray(arrayInstance) or <Array KeyWord>.isArray(<array variable>)[2]
  • .sort() sorts arrays of numbers improperly:
    • It might return [ 12, 15, 2, 5]
    • So you have to give it a comparison function:


   arrayOfNums.sort(function(a, b) {
       return a-b;
   });        


    • this works bc it needs to return negative num if a should come first, 0 if equal and positive if the two need to be reversed
  • What is the difference between foreach and map?
    • foreach manipulates each member a given list but does not return anything
    • map returns a new list with updated members


Based on my experience this covers a whole lot that will come up in a senior JavaScript interview.  Am I missing anything major?



Much thanks to all_things_code for his input and especially his vital correction!



[1] Note different syntax from Python
[2] G3E9 points out that the Array.isArray is not supported by all browsers so for your IE8 or below users (or FF 3 users, if they exist?) so please note this simple polyfill:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}



JavaScript: Quick thoughts on *this* in inner functions

For insight into function invocation and the global scope, please note following code:


    var scope_example = "global";
    var outerDude1 = function(){
        var that = this;
        var scope_example = "outer Function";
        var scope_example_as_well = "outer Function";
        var innerDude = function() {
            var scope_example = "inner Function";
            console.log("1: " + scope_example);
            console.log("1: " + this.scope_example);
            console.log("1: " + that.scope_example);
            console.log("1: " + scope_example_as_well);
        };
        innerDude();
    };
    outerDude1();


When run, this produces:
1: inner Function
1: global
1: global
1: outer Function

  1. Of course, the first console.log will see the local variable
  2. The second console.log is using this refers to the global scope.  Douglas Crockford calls this a mistake in the design of the language as it is more useful and intuitive to have this include variables just outside this inner function. I could not agree more.
  3. The third console.log also has access to this global variable because we gave that a pointer to the this in the outer scope.
  4. It’s important to remember that by not using this, we still have access to the variables in the function scope just outside of this inner function
But the previous example is not the typical way to use that.  We usually use it to access public properties of the outer function from within the inner function like this:

        
    var scope_example = "global";
    var outerDude2 = function(){
        var that = this;
        this.scope_example = "outer Function Public";  // Very different here
        var scope_example_as_well = "outer Function Private";
        var innerDude = function() {
            var scope_example = "inner Function";
            console.log("2: " + scope_example);
            console.log("2: " + this.scope_example);
            console.log("2: " + that.scope_example);
            console.log("2: " + scope_example_as_well);
        };
        innerDude();
    };
    outerDude2();


When run, this produces:
2: inner Function
2: outer Function Public
2: outer Function Public
2: outer Function Private

The major difference here is that (in line 4) we tie the scope_example variable to this.  In that context, this is the global this and updates the variable defined in the first line.  Therefore both 3rd and 4th console.log(s) are referring to this global variable with the now misleading value of “outer Function Public.”


Another great example is here: JS Fiddle

Thursday, August 4, 2016

CSS Basics: part 1

The Front End Engineering Interview Series

I have over a decade of web application development experience and most of that time has been focused on “front end” (or user interface) development.  I have been accumulating a list of questions to ask candidates so I thought I would share them with the world so that I can dream of a candidate responding with my own words.  See also The Butterfly Effect 

CSS Basics: part 1


What are the 4 positioning options and what do they mean:


static: The default.  All objects positioned in order they are listed within the parent.  Default is left to right for block items.  Often used with float.

relative: Similar to static except that you can move an item “relative” to where it would naturally lie in static.  You could add top: -2px and the object would be 2 pixels higher relative to where it would be in static

absolute: positioned relative to the first parent (meaning climb the DOM until you find a parent that) is relative or static positioned

fixed: Similar to absolute but positioned relative to the browser (view port, specifically).  Remember when Facebook had a lower tray that was “fixed” to the bottom of the browser?  That’s how they did that.

Technically you also have inherit and initial, but I have yet to see a developer use them and I would check for drugs if they did.



And do not read this one because if you are seen at work reading w3schools, you might get demoted on the spot.


What is specificity?

Short answer: 
How you determine which conflicting CSS rule applies to your DOM object.

Longer answer:
If this is our HTML: 


   <div class=”carousel weekly-ads” id=”fred-carousel”> </div>



 General element selector such as:

div {
color: red;
}


      will be overridden by a class selector such as:

.carousel {
color: chartreuse;
}


and a class selector will be over ridden by an id selector

#fred-carousel {
color: blue;
}


    and an id selector will be overridden by in-line styles (Big EWWWwwww)

<div style=”color: yellow”> </div>


Then within each of these tiers in the hierarchy, the more “specific” you are with the definition, the higher it is in the precedence scale. The following will override the single class selector above but will not override the id selector.

.carousel.weekly-ads {
color: blue;
}


Full answer:
And Chris Coyier always skillfully gets to the point: https://css-tricks.com/specifics-on-css-specificity/


What is the box model?

This has been answered quite well many times previously so I will just give my short-short version:
All block elements are effectively rectangles made up of:
  1. content surrounded by padding
  2. padding surrounded by border
  3. border surrounded by margin


And the size of each of these CSS values determines how much space the element takes up and therefore it effects how it interacts with its siblings and parents.  Kind of like puppies.

The bad (don’t read this): http://www.w3schools.com/css/css_boxmodel.asp

I also like how concise this one is: http://learnlayout.com/box-model.html

That’s it for part 1.  If you are interviewing for a developer’s position beyond entry level, you’d better know these three concepts backwards and forwards.  Stay tuned for more advanced CSS posts as well as HTML, JavaScript, and general software engineering questions that I will call “other” for now.




Friday, September 4, 2015

A Plug for the JavaScript Jabber Podcast

By RCPanos

This is a quick plug for a very well-produced podcast on all things Front-end Engineering.  Although its named “JavaScript Jabber”, the team addresses many other topics that are related to producing great code such as testing, agile development, team dynamics, HTML5 and wild concepts like “Working from home.”  (I am a bit of a fan of said concept in moderation)

The format is simply a handful of accomplished software engineers (generally of BYU fame) interviewing an area expert.  Some of the guests are very heavy hitters, particularly their Robin Williams of frequent guests: Yehuda Katz. The key reason I enjoy their model is that the show is a discussion and not a lecture.

The other strength of this show is that the de facto host (Charles Max Wood) is a highly skilled full stack developer that has NOT made JavaScript his focus and his common side-kicks (Jamison Dance and AJ O’Neal) are of similar technological leadership ilk.  I believe this brings a lot of intelligent questions to the show as they all have the expertise to discuss costs and benefits.  They also simply aren’t afraid to look ignorant.  The team occasionally even gives some pushback to the experts.  Effectively, they represent listeners of many different skill levels and get to the key information out quickly.

This excellent podcast also heavily portrays a concept that I think many people overlook in our industry: Opposing viewpoints.  It’s unfortunate, but many intelligent software engineers think in terms of “the right way” or “the wrong way” when in reality there are trade-offs to many acceptable solutions.  I especially loved to hear a demigod of design decisions (Nicholas C. Zakas) assert that in some cases, all sorts of coding practices are acceptable as long as the whole team generally follows the same set of practices.

So when you are commuting or exercising, I appeal to my fellow developers to engage in a form of hyper- multi-tasking by listening to this show.  You will set yourself apart at your work place by learning a lot more than the latest buzzwords.  After listening to an episode, you should be able to speak to the tradeoffs for a given technology so that you can contribute to future design discussions.  As this insight would normally take days (if not months) of your own time to establish, this is 40-50minutes of time well spent.

Monday, August 3, 2015

The Ten Minute Overview of Drawing in HTML5

SVG and Canvas Tags


Due to some very intriguing conversations over potential future projects, I have been very motivated to dive into the world of “drawing” in HTML5 and I would like to share the high-level view.  So the following is not an in depth look at graphics frameworks but rather is a concise yet comprehensive perspective of the two incredibly awesome drawing tools available to front end developers: canvas and SVG (Scalable Vector Graphics). Oh, if only we had these tools ten years ago . .


The Similarities: Drawing


So before we go into all the differences, what do these two “new” tags have in common?  Well they both allow a developer to “draw” programmatically and they both are supported by all modern browsers plus IE 9 and above.  Animation is quite possible in both but there are clear advantages to either choice in different contexts.  The canvas API is directly manipulated using JavaScript while JavaScript can be (and often is) used to manipulate the XML structure that is SVG.  They both also come in pretty colors.  

So basically, the two tags have little in common but that they both “draw.”

The Differences: Many


Core Code Structure 

The most fundamental difference between SVG and Canvas is how they are stored by the browser.  Canvas is simply a bit map and its JavaScript API helps you update all the lovely bits.  This is useful when utilizing complex images (like from a Photo!) and allows you to save the image programmatically using the “toDataURL()” function.  However, this requires a lot of bookkeeping and can be very slow when you are managing a “large” canvas.


In contrast, an SVG graphic is communicated to the browser using a specific XML format describing an object model similar to HTML as it uses hierarchical system of elements with styles and attributes.  This XML could be loaded from the server or there are many libraries that will help you build this XML on the fly.  So unlike Canvas, SVG could be used without JavaScript, but that would eliminate much of its flexibility.

Core API

So really, the difference is not JavaScript (Canvas) vs XML (SVG) because you are probably going to use a JavaScript based library or at least your own scripts to manipulate the SVG XML as well.  However, it’s important to note that the core APIs set out by the W3 consortium are quite different for both.  Please note one reason there are so many SVG JavaScript libraries is that the core API is on crack:


Meanwhile, there is reduced crack usage for Canvas:


Relationship to the DOM

But don’t let me gloss over one of the most important advantages to SVG.  With a graphic drawn in SVG, each element is truly a part of the DOM.  So by simply grabbing reference (ID/Class) to some node within the SVG XML, you can, amongst other things, actually receive user events.  In contrast, a Canvas element is really just a part of the DOM in its totality so you have to use alternative methods to determine if one part of the canvas was clicked vs another such as floating divs over the canvas area.  So, if you need the user to interact with your graphic, there would be many advantages to using SVG.[1]

Resolution Considerations

Another major advantage to SVG is that it will have the same quality at any resolution because it is based on vector graphics.  The arcs, points, lines and other “geometric primitives” will have the same relations to each other no matter how much you “zoom” as they are resolution independent.  Meanwhile, the canvas tag is considered a raster graphic because it is based on a bit map and is therefore resolution dependent.  So if you are going to be adjusting the size of the given area that the graphic tag is rendered in, there might be some serious advantages to SVG.

Animation

The differences between raster and vector graphics also affect the ability to animate.  I have not done enough research to address the topic of animation in totality with these two tags but let’s consider the basics.  In general, canvas is considered better for animation because the “fire and forget” updates to the bitmap require very little processing.  However, that is assuming the actual amount changes to the bit map are relatively isolated.  In contrast, if you are changing a graphic representing half of the full screen, you might be better off using SVG because you would be updating millions of bits otherwise.  Its important to remember that processing requirements of SVG have nothing to do with the actual size (again, it is resolution independent) but instead is a product of the number of elements and their dependencies that would need to be updated.  So some articles refer to SVG having “medium animation” abilities and I am surmising this is because using simpler graphics in certain circumstances provides significantly better performance.  But Canvas is given the label “high animation” abilities because the more common scenarios require little processing time from the raster graphics format and is the much better choice.

All the Rest

The remaining factors you might want to keep in mind is that :

  • Canvas has a 3D “context” (mode) available
  • Text rendering is higher quality in SVG, but there are many reasons to use text in Canvas (see many of the Memes you see online)
  • SVG is properly layered while you’d need two separate canvas tags to have a layered effect

Conclusion


So I hope you agree that both Canvas and SVG tags offer tremendous graphics capabilities to the front-end developer.  Neither one is superior but both have different advantages.  So for your most advanced needs, you might want to consider using both!

See also:





[1] Although some canvas based libraries will help you work around these challenges such as: http://kineticjs.com/

Sunday, February 9, 2014

BackBone vs Angular, an original comparison

The following gives my take on the trade-offs between backbone.js and angular.js using an analogy to early web frameworks.  This includes factors of:

  • Flexibility and the opinionated factor
  • The Infamous Learning Curve
  • The Effects of the Open Source Community
  • Debugging Ability

Please let me know what you think in the comments below. 

I recently spent 6 months on a team implementing a very intense project using backbone.js (and marionette.js) to create  a very elaborate gaming market place.  It involved many of the challenges that a typical backbone project entails such as endless sub-views, animation, and handling click happy user events (gamers need to settle down.)  And now I have spent the last few weeks building sample projects using BackBones greatest rival: angular.  In doing so, I have become quite fascinated with vast differences in the cultures of the two communities.  So in order to articulate my own take on the choice between the two, I would like to suggest a new analogy for those less familiar with both:

BackBone is to early LAMP as Angular is to (rather) early J2EE

If you have been writing web apps for many years so that to you remember what it is like to develop the early Perl/PHP CGI scripts of say ~1997-2002, that will help.  But for those not from the web stone age, please let me explain.

Flexibility and/or Self-imposed Chaos

In the beginning, the libraries for Perl and PHP in this era gave you tools so that you could access the HTTP headers and send the appropriate responses, but to say they were opinionated would be the farthest from the truth.  They were exteeeeeeemely flexible so that you were able to shoot yourself in the foot on an almost hourly basis, thereby making giving your boss (Wad up Tannaz!) a reasonable effort estimate almost impossible.



Similarly, I argue that backbone gives you some solid guidance, but the fact is you can usurp that guidance at any moment with very little effort.  Meanwhile in Angular, with its system of dependency injection, the strict system of scoping, and the separation of services, the paradigm encourages you to think through all forms of abstraction.  So unlike Backbone, this does “force” you into some solid patterns and practices that will help you avoid chaos.

Back to my analogy, PHP (especially then – not so much now) and Perl also let you do almost anything you wanted even though you should show self-respect and follow SOME proper coding practices (can you say,  “code interpolated from variables?[1] “).  So having angular encourage or even force more structure is a lot like what J2EE did for web applications ~2002.

Learning curve

During my IBM internship in 1997, one of the countless Cal Poly alums (SLOTown!) handed me a book and I just started (horribly) cranking on my first Perl CGI script (OW, my foot!).  Meanwhile, learning Java by itself just from a book [2] was not easy, let alone learning J2EE.  Even in 2002, you really did need to learn a huge chunk of the API just to get by but there was no such list for early LAMP. So admittedly, I utilized two company sponsored classes back in 2002 just to get my first “promotion” into the J2EE team.  This is also a very common criticism of Angular, that it will take a lot more effort to learn because it is much more involved offering.

Open Source vs Controlled by the GOOGs

Another similarity here is that ten+ years ago the open source community seemed to strongly prefer the LAMP world to J2EE.  This is probably because it came first and possibly also because Sun Microsystems wisely kept the underlying standard of J2EE under tight control through-out its history because, apparently, they did intend to make money off of it (I never completely understood how).  In contrast, PHP was graciously given over to the open source community by its brilliant creator (Rasmus Lerdorf) very early and this is probably another reason the open source community has built so many frameworks, CMSs, shopping carts, and countless other forms of reusable tools with it.  Similarly, proponents of the BackBone world promote the long list of plugins and extensions available as reason for its superiority.  Meanwhile, the list of reusable components written in angular might never match the backbone list due to the differences in history and culture of the two communities.

Debugging

For reasons related to the above, I also see a similarity in debugging.  Many argue that Backbone projects are easier to debug because it is much easier to trace or console dump the un-minified backbone code itself.  You are free to do this in angular as well, but a common criticism is that the declarative nature of angular’s directives (markers on a DOM element) make this a much greater challenge.  My memory is that diving through all the open source code in LAMP is much easier than, say, diving through the supporting code of JSPs.  Also, I recall one of the great discoveries of switching over to the Java world was that the official error messages were so much more helpful.  I should not speak for the LAMP world over the past ten+ years, but I will declare that Backbone’s error messages are often terrible.  If they tell you anything at all, the information is rarely useful.  Meanwhile, I am adding powerful error messages to the list of reasons that I am grateful to the Angular team at Google.  It’s like these people have been on the app-building side of this equation before.  Crazy!



Conclusion

To sum up, the backbone and angular communities have some cultural contrasts similar to many other long standing debates in the application development communities.  Primarily: How much control does the developer want OR how opinionated do you want your framework to be?  I completely respect the developer that wants to feel a sense of invention and hates the idea of having to work around a paradigm that is restricting his or her creativity.  If that is your primary driver in being a developer, than please take from this analogy that you probably belong with the freedom crew and backbone.  I myself hope to still be a part of that crewe from time to time.  However, from almost my very first angular project, I was astounded as to how much I did not have to build on my own.  Angular, like J2EE years ago, just covers so much of the boilerplate code for me.  Meanwhile, during my backbone project, we were constantly re-factoring our code.  So if you choose angular, in many cases you will quite simply get a whole lot more done.

[1]   Ok Javascript can do that too but why? Really. Why?
[2]   Yup actually, I am that old. I was the last semester at Cal to learn Data Structures with C++.  Wow.  Someone buy me a cane . . .
[3]   But as I mention in my fist post, I encourage you to use a backbone framework (especially Derick Bailey's Marionette or possibly thorax by WalmartLabs).
[4] Pls see my first post for why Backbone is not a framework by itself

Sunday, October 20, 2013

The Ultimate BackBone Crash Course

Part one:  the 30,000 ft view

The following is an extremely simplified and slightly snarky synopsis of the popular Backbone JavaScript “framework.”  I hope to give a high level view of:
  1. What Backbone.js actually is
  2. What is in it
  3. Where to go from here
But in short, this is written for those brand new to the very powerful JavaScript toolkit so that they will have a high level view of what it offers before being tempted to dive into the incredibly joyous dearth of information that is the official backbone documentation.


What is Backbone.js

Backbone is often referred to as a JavaScript "framework" but it is not a framework like the other 3 leading frameworks[1] are in that it will not tell you exactly how to use it.  It is officially a library but that might imply it is as vast as one of the libraries it is built on, Jquery.  So I contend, it is really a toolkit consisting of a handful of powerful classes that might serve as the brains of your of the monster you want to build while also facilitating a pub-sub system to serve as the joyous nerve center of said monster.  In fact, I am pretty sure that is why it was called “backbone.”

That and, if you plan to only use this "framework" and not invent any of your own conventions to properly design your own system, then your evolving beast will likely become a weak and vulnerable beast waiting to be eaten by the evils of long term maintenance.


So farcical analogies aside, what exactly is backbone.js?

Backbone is a JavaScript toolkit that facilitates a type of  MVC(kinda) . .  & R . . with an A&E .. architecture. 

By that, I mean that Backbone provides the base classes you might use to follow the well-known MVC (Model View Controller) architecture  . . . except it does not officially have a controller.  Much of those official roles are often covered in the View classes.  But it does have a Router that serves some of the official Controller functions, thus it is actually an example of the trendy MV* (a.k.a. M-V-Star) architecture.  However, many who use backbone often feel the need to implement their own Application level object(s) and we cannot forget the high speed bus of backbone to organize its pub-sub methodologies, the Event class.  So Backbone.js a little more than a way to facilitate MV*.

Therefore,  I am dubbing backbone an MV*ea (or M-V-Starry) JavaScript Toolkit.

I realize you are now tremendously impressed with my ability to create new terminology, but I dare you to unlearn that mnemonic.  I dare you!


So let’s discuss this short list of powerful classes and the primary purposes they serve.


What is in it

The “Model” of the MV* software architecture pattern within Backbone is made up of model objects and collection objects.  Instances of the model are largely dumb objects that might manage some of your most basic ajax calls and they also initiate themselves in a clever manner.  But they really just hold data.  The collection objects are made up of a list of the same model objects instantiated from the same class.  They are also just a tad bit shrewder than models and are a more likely location to house code that retrieves large amounts of data from the server through the “fetch” or “sync” calls.  This is also usually the best place to abstract any browser side filtering of said data.  As these classes often reflect your data structure on the back-end, they are easily organized and often well contained.  However, in contrast, the View classes are usually a complete mess.

The View classes, of course, manage all the logic of displaying the UI ideally through the use of templates.  As Backbone is built on Underscore (which is built on JQuery) there are a couple standard templating systems easily available.  However, the View objects also must manage the events originating from the user and dynamic updates to these templates.  In plain Backbone (IE: not using a framework like Marionette), some Views often have to manage other sub-Views. This can get very confusing and lead to a lot of repeated “boiler-plate” code.  So to sum up, View classes do a whole lot and it is quite easy to make a complete mess out of said classes.



Fortunately Routers are quite simple.  They map a URL, including any parameters that might be involved, to one specific function often called an action.  These actions often involve creating Models and/or Collections plus initiating the server communications needed to be sure these pieces of data are valid.  These objects are then passed to new View instances.  So in most cases, the routers are the masters of instantiation.

Please note that how you organize the Routers is really up to you.  You could have one massive router for the whole system or you could have one router for every major server interaction in your system or every step in your workflow.  However, it often makes a lot of sense to organize your actions into different routers analogously to how you organize your workflow.  Life is just so much simpler when you know where everything is.



Lastly, Backbone provides a simple class to handle messaging (or pub-sub) within your system based on the Events class.  As long as one corner of the system is “listening” for the same message that another corner “triggers,” then you can manage responses to all sorts of actions at any given time.  This is especially useful when managing asynchronous events such as responses from the server or interactions from the user.

Please note Events are an example of a “use at your own risk” type of tool.  For instance, it is very easy to create two contradictory responses to the same message or to initiate a response to an action long after the context is appropriate but we will save that discussion for some sort of “pitfalls” posting later.  My only suggestion is to have some guidelines set for your application's use of events or Spaghetti may come to bite you.



Where to Go from Here

So despite the fact that this post is rather short, this really does sum up all the major components of Backbone.js.  Obviously there will be many lessons to be learned from your first major project, which is why I hope to post a list of “pitfalls” to avoid at some point.  I should also admit that much of my time as a Backbone developer has been whilst under the protection of Derick Bailey’s Marionnette version of Backbone.  The many reasons that this more structured form of Backbone is completely bad ass will also be saved for another post, but it’s fair to say that those that are using backbone the old fashioned way will have a different perspective than myself.  In fact, I would appreciate any comments on my ramblings in the interest of knowledge sharing.

But most importantly, if you are not going to use someone else's framework, I strongly suggest you come up with at least some standards for how you are going to solve repeated problems.  If you don't know what problems I am referring to, please rethink your decision to not use a backbone framework.

This author would like to thank his Cousin John Cardoza (AKA the Nevada Traveler) for teaching him to be snarky whilst writing on obscure topics.  Rewqls.




[1]Conversations in Silicon Valley generally give BackBone, Ember, Knockout and Angular credit for the top four spots in the charts.  If you disagree, pls comment below.