Skip to main content

Mobomo webinars-now on demand! | learn more.

 

javascript-graphicJavaScript is a real language and it was during my first job as a Salesforce Developer that I was able to start learning the “language.” I remember adding a script on a visual force page and selecting elements while using classes. Not the best practice... but it was my first encounter with the language and I knew that it would take time to truly understand the fundamentals. At the time I didn't imagine the capabilities of the technology and how it was going to evolve and improve the way that we surf the web.

In the sense of paradigms I would say that I started writing JS code in the Imperative way, just defining functions and encapsulating logic to then use all those gears on a single purpose: fire a function onclick to show a modal window. Wow! Really impressive right? Just kidding.

[javascript]function sayMyName() {
alert(“You’re Heisenberg”);
}
document.getElementById("my_button").onclick = sayMyName;[/javascript]

At the same time during my first job I started attending classes at the university and in one of my classes, “Programming 2” we started to learn the famous: Object Oriented Programming, and then I started to implement this knowledge in my daily front-end work. I was able to think more on the responsibility that an object needs to have and the context where that object is going to hangout.

(function() {
"use strict";
var Heisenberg = function() {
this.name = ‘Heisenberg’;
}
Heisenberg.prototype.sayMyName = function() {
alert(“You’re ” + this.name);
};
document.getElementById("my_button").addEventListener("click", function(e) {
var heisenberg = new Heisenberg();
heisenberg.sayMyName();
});
}());

Of course the object-oriented paradigm is much easier to understand than the imperative one, and it’s also more modular.

But then I discovered a new way of thinking about my JS code: the functional way. This doesn’t mean that object-oriented is better or worse, but it’s another way of tackle situations. Let's see:

 

This solution looks shorter, because I am only using two functions (besides I have added a static return value on the getName function). You don’t need to forget everything you know to take advantage of the functional paradigm. I would say think more on the dependencies of the functions in the context in which they are called in order to know how to structure all the code.

Categories
Author

unnamed-4

 

 

By nature, tables of data have a rigid structure and capitalize on screen width. When screen size is limited, table data will often not fit on the screen at once. This has been an interesting challenge throughout the brief history of responsive design since a key feature with responsive design eliminates the horizontal scroll factor.

 

The simplest way to work with tables that exceed the width of small screens is to place them inside a scrolling container. This generally works and it allows the table structure to be maintained. The only drawback is that it results in horizontal scrolling which we are often trying to avoid in responsive design. With that said, the value of simplicity makes this option a great default setting for tables across a site. This is the method employed by popular frameworks like Bootstrap and Foundation.

 

More complex solutions should be used on a case by case basis for tables that require more attention. You should test the experience of using modified tables at the relevant screen sizes to catch any unexpected issues like text wrapping or overflowing.

 

If you are seeking to eliminate horizontal scrolling but do not mind a potentially enormous increase in vertical scrolling, the following solution may suit your needs. It is an elegant yet fairly simple solution that stacks every item within the table vertically and cleverly places a label next to each item using some css trickery. The downside to this approach is that it is not easy to scan multiple items in common categories at one time.

 

An easily scannable solution that also prevents horizontal scroll will require significantly more complexity to strategically hide and reveal portions of data using javascript. Advanced responsive table plugins such as FooTable and DataTable allow developers to choose which columns are hidden at specific breakpoints. A user can then quickly scan through the existing columns to find an entry and reveal the hidden column data for that entry. Once we reach this level of complexity, we gain access to a variety of features like sorting, filtering, and pagination.

Categories
Author

writing-inner
One of the greatest things about the web industry is the respect and generosity developers have for one another to share knowledge in this ever-changing atmosphere. Whether you're on a small or large team, solo coder or open-source hero, arguably the most important pieces of your code aren't code at all. Commenting and writing readable code can save yourself and teammates valuable time by quickly understanding what your code does without the countless hours you spent carefully crafting the most elegant code imaginable. Even if you're working alone, readable code can avoid those awkward situations of you having to figure out what genius (spoiler: you) wrote this awfully convoluted code. Other benefits include auto-generated documentation and speedier code reviews. So, next time you write the "one function to rule them all", take the time to rename it from doesSomething to addTaxToSubTotal and comment the hell out of it - your teammates and future self will thank you.

What is “Readable” Code?

JavaScript: it was the best of languages, it was the worst of languages. Because of JavaScript’s flexible nature, we can sometimes write code that looks very strange and hard to read. Here are a few guidelines you can follow to ensure you are writing readable code:

  • Describe: Use descriptive variable and function names, even if they take longer to type. In six month from now, you’ll have a much better chance of understanding what a function does if it’s called getAllCustomerNames rather than getData.
  • Simplify: Don’t over-engineer your logic to the point of unreadable complexity. Saving a few lines of code while giving up readability is not worth it in the long-run.
  • Comment: Complex logic is sometimes unavoidable. When it’s not abundantly clear what your code does just by looking at it, comments can lend a helping hand in plain english. Don’t shy away from lots of comments either. Techniques like minification will strip out all comments for production code, so you don’t waste any precious bytes.

Refactoring for Readability

Let’s take a look at some code that could use help to make it more readable. Below we have a function that performs some actions on product information. I will refactor the function so that it performs the same actions, but is much easier to maintain and collaborate on.

function changeData (data) {
  if (data.price > 100) {
    data.label = "expensive";
  } else {
    data.label = "cheap";
  }

  return data;
}

This function is pretty simple, it takes a data object and sets the label property to “expensive” if its price property is greater than 100, otherwise sets it to “cheap”. Although this logic is simple, there are a number of changes that could be made to make this function much easier to read and maintain.

  • Function name: “changeData” is not a very descriptive name. Since this function is changing product data in a very specific way, we can name the function as such. This will also help developers understand what the function does when it is called elsewhere in the application.
  • Function parameters: “data” is obviously not descriptive at all. We should rename this to best reflect what piece of data is being brought into the function.
    Verbose logic: The if statement could be simplified into a ternary statement since there are only two possible outcomes for the label property.
  • Commenting: We are missing comments for this function, which could provide some great context to the maintainer.

Let’s see what the refactored function would look like:

function setProductLabel (product) {
  /**
   * Set the Product label based on its price.
   *
   * @param {object} product The Product object to update
   * @param {int} product.price The total price of the Product
   * @param {string} product.label The current label of the Product
   * @return {object} product
   */
  product.label = (product.price > 100) ? "expensive" : "cheap";

  return product;
}

ProTip: Put the comment block inside the function so that if you print the function in a console log, the comments print with it.

Conclusion

Writing clean, readable and well-commented code is a skill that needs to be honed and valued. Many developers overlook this, but it’s really what can set you apart from others in your field. And remember any little bit helps, so use the guidelines above to gradually improve your code today!

Any questions, thoughts, ideas? Let us know!

Categories
Author

Javascript

There's been a tremendous push in recent months to move all of the components used for building anything for the web in to JavaScript, and only JavaScript (abandoning the use of HTML for templates and CSS for styling). While I can understand how we've gotten to this point, I think we're at risk of ignoring potentially more robust solutions. Rather than build up your application (or site) using a single monolithic JavaScript framework, I implore you to consider something that's a bit more open-web and future friendly: continuing to build with component-based architecture using all of the current tools available to you, and looking forward to use web components.

Before we get into why I think component-based architecture is the correct way for now, and web components are the way of the future, let's explore how we've gotten to where we are today.

It starts out innocently enough: you apply an ng-click attribute to a link or a button in your template. Then you add a couple of additional lines of markup to handle an if/else pattern to that template (<span ng-if="truthy"></span><span ng-if="falsy"></span> seem familiar?). Before you know it, you're applying ng-mouseover and writing custom directives to handle events specific to your markup.

Others might be looking at this and decide that it's lunacy to have all of that written by you, in-line in your template (and they're probably right -- if you're adding a lot of logic to your template, you probably need to reconsider what you're doing and approach the problem from a different angle). It's difficult to maintain, tightly couples your template to the controller logic behind it, and it's really not the template's job to manage complex logic.

However, rather than refactor to use unobtrusive JavaScript patterns or to extract out difficult logic so it's not present in the template, there's a push (primarily from the React project) to build everything up using JavaScript. Your logic (controllers, models, etc), your templates, and even your CSS. The thinking is, for the most part, that if you are doing these complicated decision trees in the code, then it should be handled by something designed to handle said complicated decision making.

For those who've been building websites and applications for long enough, seeing something that looks like this:

<div   onMouseOver="{() => this.setState({ hover: true })}   onMouseLeave="{() => this.setState({ hover: false })}"   style={{borderColor: this.state.hover ? 'red' : 'transparent' }} /> 

...should remind you of nightmares of years past. This largely disregards the efforts of WASP (Zeldman, Meyer, Holzschlag, et al) and, more recently, the Web Standards Sherpa that lead the charge on making the web more maintainable (proper HTML markup, separation of style, content, and behavior) and future friendly. Additionally, we return to a state where the separation of concerns is being tossed out altogether and we're being asked to ignore years of learning in the favor or writing everything in JavaScript.

A typical React component would look something like this:

var buttonBase = {   padding: 5,   border: "1px solid #aaa",   borderRadius: 5,   backgroundColor: "#eee", };

var buttonBaseHover = _.defaults({ backgroundColor: "cyan", borderColor: "magenta", cursor: "pointer", }, buttonBase);

var BasicButton = React.createClass({ getDefaultProps: function() { return { type: "button", label: "Click me", }; }, getInitialState: function() { return { isHovering: false, }; }, propTypes: { type: React.PropTypes.string.isRequired, label: React.PropTypes.string, }, handleMouseOver: function() { this.setState({isHovering: true }); }, handleMouseOut: function() { this.setState({isHovering: false }); }, render: function() { return ( <button type={this.props.type} style={this.state.isHovering ? buttonBaseHover : buttonBase} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} > {this.props.label} </button> ); } });

React.render(<BasicButton label="Demo Button" />, document.getElementById('container'));

See the Pen React Button Component by Mike Tierney (@miketierney) on CodePen.

While this has the merits of being transportable (one of the better arguments for this style of development), it lends itself to higher maintenance issues. Like the common complaint of CSS, this is the sort of thing that quickly ends up creating bloat - it's easy to envision a scenario where a "BasicButton1" gets added because a developer is uncertain about making changes to it. While conditionals could be added to the render method, you then have added processing impact on whether or how to render the button. Many developers will make the same mistake here that they do with CSS: "I don't know where this is used, so I'll just make a copy of it, modify it, and use that in my implementation." Both are signs of maintenance issues, and both can be addressed with proper processes and practices (like code reviews).

One Tool For All Jobs

If we move towards using One Tool For All Jobs (in this instance, JavaScript), we neglect the fact that the tools we're abandoning are actually quite good at doing what they need to do. CSS does a great many of the things that are related to styles far better than JavaScript and it has the added benefit of being cacheable, leveraging readily available resources (rather than littering your JS scope with event handlers for every element that needs to support interactivity; that can impact performance pretty heavily), and with proper use of the cascade you can more easily create variant styles as needed (site theming as a whole, for example).

To handle that hover effect from earlier in the post, you'd need to do this:

<div class="hover-div"/> 
.hover-div:hover, .hover-div:focus {   border-color: red; } 

I've also added the :focus pseudo-class so we also have keyboard support. It'd take more than that to add that same support into that inline sample, and you're providing better support for your users. :focus is a relatively small thing by itself, but think about the broader implications. A natural byproduct of this is to rebuild native components. As an example, we're already rebuilding the select menu (because it's too hard to style natively), and that's just the start of a slippery slope. This should not be the norm - rebuilding existing browser components and behaviors in pure JavaScript might seem appealing (because you have total control over what it does, more or less), but the overhead of creating it in the first place is inevitably going to be greater than anticipated, and then you have to take into consideration the fact that you now have to maintain that. Furthermore, you now have to accommodate all current and future interaction patterns, UX experiences, and many other OS-level features that users are already familiar with in order to make your fancy widget not seem out of place. Is it really worth that? Do you really need (or have) that level of control? Why would you want to abandon future improvements that will roll out as browsers and standards improve? Finally, on this particular point, you'll also need to factor in support for assistive technologies. Just because you're building a "web app" doesn't mean you get a free pass to just ignore those users.

Many of the proponents of using this all-in-javascript approach are focused solely on making sure that everything is managed locally (as opposed to globally, which is how CSS operates). They neatly solve this "pollution" of the global space by injecting all of the styles directly on the element being styled, which is truly the only way to avoid that issue. However, this comes at a cost -- more complex elements can potentially have a significant number of style selectors (and let's be honest here, we're still using CSS whether it's in the DOM or in a dedicated stylesheet). This leads to greater DOM bloat, and more re-draws of elements within a page when states change, content is updated, or the initial view is rendered. While these things may not impact the immediate load time of the page, there's an overall impact on page rendering because of this. CSS isn't free of this, certainly, but one advantage of loading those files once is that this is minimized. Additionally, for things like layout and global styles, you want to have a more global take on things. For re-usable components (buttons, form elements, links) - why make the browser evaluate and render style for every element one at a time when you can pre-load the styles into memory and when a node appears that matches the selector, the styles will be applied.

Component-based Architecture

My counter-proposal would be to use one of the better trends we've seen lately: component based architecture. Build small to large - much like the members of the React team who are advocating for using CSS in the JavaScript application want to do. This can be done with traditional techniques, however, and diligence to fending off entropy and bad practices. With tools like Sass and Less, we have the ability to create small files that are focused purely on building out a single component, which can then be stitched into the larger application as whole. When building a single page application, we can even start using an approach where our JS, HTML, and CSS all live together in the same directory, to later be concatenated,minified, and then moved into the appropriate locations. With a reasonable application of namespacing in CSS (pick your poison; I'm partial to SMACSS), we can accomplish the same goals - re-usable, easy to maintain, components - without jamming everything in to JavaScript.

Right now, I think a compromise is a mix of global and local styling. I still think styles added directly to DOM nodes is a mistake (with some exceptions -- an argument can be made for inlining styles on canvas/svg-based charts, for example, and I'm sure there are other situations, but those should be the exception and not the rule). We should think about making our components themable as much as possible, re-using tools that are available to us (the Cascade naturally supports this sort of behavior), and embrace the fact that we never have 100% control over the way our web-based application will look and behave. There are simply too many variables that are out of our control.

If you're concerned that your team is too large and you cannot communicate some of these practices widely, there are plenty of tools available to look for unused CSS, duplicate CSS, "bad" CSS, and inefficient selectors. These can be integrated in to your build process or development flow, depending on your preference.

One final point to make here is that we need to ensure that we are optimizing for our users. When we make the browser do all of the work for us because it makes maintaining a code-base easier, that's fine up to a point, but we need to be mindful of the overall impact that that has on the experience of the end-user. This also means, rather uncomfortably, that we (as developers) need to embrace that there are a great many things that are out of our control, and we should build our solutions to be as flexible as possible. Otherwise, we'd still just be building it all using Flash.

Additional recommended reading:

Categories
Author

shink
If you’re reasonably up-to-date with front-end app development then there’s a good chance you’ve heard the buzz flying around about ECMAScript 6. For those unfamiliar, ECMAScript 6, also known as Harmony, is the next major version of JavaScript programming language. In this post, I’ll utilize new ECMAScript 6 features to reduce and improve readability of code in a sample AngularJS application.

Our sample application is a simple baseball card auction app that serves as a platform for users to sell rather valuable baseball cards and consists of three Controllers (BaseballCardsCtrl, BaseModalCtrl, and ConfirmModalCtrl) and three Services (UserService, CardService, and NotificationService).

Block-scoped bindings and arrow functions

The very first thing our application needs to do is fetch the current user’s profile, so we’ll start by taking a look at the getUserInfo function of our UserService which is responsible for retrieving the user’s information.

function getUserInfo() {     if (user) {         return $q.when(user);     } else {         let handleSuccess = (response) => {             user = response.data;              return user;         };          let handleError = (error) => {             NotificationService.logError('Unable to retrieve user info', error);              return null;         };          return $http.get('/dist/data/get_user_info_response.json').then(handleSuccess, handleError);     } } 

This function uses two of the new features of ECMAScript 6, namely block-scoped bindings, and arrow, or lambda functions. The handleSuccess and handleError functions above are declared using the let keyword, which restricts them to only being accessible by code in the same block; in this case, the else block of our if-else statement. This increases the overall readability of our code by moving variable or function declarations and assignments into the block where they’re intended to be used. Both handlers make use of arrow functions which provide a shorthand, expressive syntax for defining functions. In addition to providing a more compact syntax for defining functions, arrow functions also lexically bind the “this” keyword value, eliminating the need to manually bind object context when registering event handlers and such.

Generators and paused execution

Next, let’s take a look at an excerpt from our BaseballCardsCtrl that uses the UserService’s getUserInfo and CardService’s getCards methods to retrieve and store a reference to the user’s profile and baseball card data.

var it;  initialize();  function initialize() {     vm.notifications = NotificationService.getNotifications();      it = fetchData();      it.next(); }  function *fetchData() {     vm.user = yield getUserInfo();      vm.cards = yield getCards(vm.user); }  function getUserInfo() {     UserService.getUserInfo().then((user) => { it.next(user); }); }  function getCards(user) {     CardService.getCards(user).then((cards) => { it.next(cards); }); } 

The most interesting thing to note about the above code is the *fetchData function declaration. The function name is prefixed with an asterisk which is a new, special naming convention that results in the function returning a Generator object, another new feature of ECMAScript 6.

Generators are special Iterators that can pause their execution when the yield keyword is encountered. The ability to pause function execution allows us to control the order of asynchronous operations without need to use a series of nested callbacks. In our initialize function above, we store a reference to the Generator object on which we immediately invoke it’s next method to instruct *fetchData to begin executing its function body. The *fetchData function calls getUserInfo then pauses due to the presence of the yield keyword. The getUserInfo function is responsible for registering a callback function to be executed once the user’s information is retrieved from the server. Once the user’s information is retrieved, the callback invokes the Generator’s next function with the user data, which is returned by the first yield statement in *fetchData. The *fetchData function then releases the pause allowing execution to continue and the getCards function to be invoked with the necessary user data.

Object destructuring and string templates

Now that our application has been wired up to retrieve the necessary user and baseball card data, it needs a way to allow our user to actually sell his cards. The following snippet is from our CardService.

function sellCard(card, index) {     return $http.get('/dist/data/sell_card_response.json').then(handleSuccess, handleError);      function handleError(error) {         NotificationService.logError('Unable to sell card', error);          return null;     }      function handleSuccess() {         var { year, firstName, lastName, value } = card,             dollars = $filter('currency')(value);          cards.splice(index, 1);          UserService.updateBalance(value);          NotificationService.logSuccess(`Sold ${year} ${firstName} ${lastName} for ${dollars}`);          return card;     } } 

The majority of this code looks similar to what you’ve seen in other AngularJS applications with one exception, the first line within the nested handleSuccess method. This particular line uses what’s called Object Destructuring, another one of our new ECMAScript 6 features. Object Destructuring provides a shorthand syntax for declaring one or more variables with their values being initialized as property values of a target object. This is only a very basic example of how one might use Object Destructuring to consolidate multiple variable declarations into a single statement; it does support more complex mappings to nested object properties as well.

Another difference you may have noticed is our use of a string template to build a success message to be used as a “successful sale” notification. Traditionally, this would have been accomplished by concatenating multiple string literals with variables, but now we can achieve the same result using much more concise, readable syntax using variable interpolation with template strings.

Classes and prototypal inheritance

One requirement of our application is to prompt our users to confirm that they would like to proceed, after clicking a button to sell a particular baseball card. For this demo we use the UI-Bootstrap modal for our confirmation prompt. In real world applications there is often the need to utilize many different modals that implement a common subset of functions to handle repetitive tasks such as closing the modal when the user clicks a Cancel button. Implementing these functions for each modal leads to redundant code. Fortunately, ECMAScript 6 introduces a new way to approach prototypal inheritance in JavaScript using a more concise, readable syntax.

function BaseModalCtrl($modalInstance) {     'use strict';      var vm = this;      vm.dismiss = $modalInstance.dismiss;     vm.close = $modalInstance.close; } 

First we define an ordinary constructor function that creates dismiss and close members that reference the $modalInstance service’s dismiss and close methods. Admittedly, there’s nothing new or interesting to see here but in our next code excerpt, we will see how we can easily extend this functionality when we create our ConfirmModalCtrl.

class ConfirmModalCtrl extends BaseModalCtrl {     constructor(data, $modalInstance) {         super($modalInstance);          this.data = data;     } } 

While this feature isn't a new concept in JavaScript language, it does provide syntactic sugar, and achieve prototypal inheritance using a more concise, intuitive syntax. ECMAScript 6 classes and inheritance offer a standardized way to define JavaScript class constructors, public and private members, and make superclass methods calls. Of course, this is all possible today using native ECMAScript 5 code, but the syntax is not as elegant or intuitive. We now have an easy, readable way to extend functionality and eliminate code redundancy in our JavaScript classes.

Structure through modules

Lastly, let’s learn how to import various application components and register them with AngularJS. Historically, JavaScript has lacked a native way to structure applications and manage component dependencies. However while AngularJS does have its own dependency injection mechanism, it does not support importing external dependencies and requires components be available from within the current scope before registering with Angular.

ECMAScript aims to provide a native, standardized way to handle importing external dependencies with the introduction of modules. Lets take a look at how we can utilize the new module syntax to import external file dependencies and register our different components with Angular.

 import BaseballCardsCtrl from './controllers/baseball_cards.ctrl.js';      import ConfirmModalCtrl from './controllers/confirm_modal.ctrl.js';      import UserService from './services/user.service.js';      import CardService from './services/card.service.js';      import NotificationService from './services/notification.service.js';   angular.module('demo', ['ui.bootstrap'])   .controller('ConfirmModalCtrl', ConfirmModalCtrl)   .controller('BaseballCardsCtrl', BaseballCardsCtrl)   .service('UserService', UserService)   .service('CardService', CardService)   .service('NotificationService', NotificationService); 

As you can see in our above example, ECMAScript 6 modules introduce the new import keyword, allowing you to reference application components defined in external files. Here, we import each of our AngularJS application components (BaseballCardsCtrl, ConfirmModalCtrl, UserService, CardService, and NotificationService) and register them with our demo application. Each of our components uses an export statement, another new keyword in ECMAScript 6, to selectively make internal components available for import and use in other files..

 export default NotificationService;    function NotificationService($log, $timeout) {   ...   } 

The import and export statements support different syntax giving you flexibility over how components are referenced throughout your application. Note: We’ve only used the most basic, as it fulfills our application’s current needs.

Conclusion

ECMAScript 6 is still in draft mode and its specification isn’t expected to be officially published until later this year. For this reason, modern browsers currently have varying or incomplete support for many of the new language features. Fortunately though, there are quite a few tools to integrate support for ECMAScript 6 into your workflows and translate the code to ECMAScript 5 compatible syntax. As the release of the new ECMAScript 6 specification approaches, its new features are being integrated into more and more applications.

JavaScript is one of the most popular and widely used programming languages today; it’s not going anywhere any time soon and as it continues to evolve, so should our applications to harness it’s full potential and expressiveness. Our sample application uses one subset of the new features available in ECMAScript 6; there’s a lot more to it than what we’ve seen in this short example. For more complete information on ECMAScript 6 and how to integrate support for it in your workflow, check out the following resources.

Application

 

 

Resources

 

 

Categories
Author

javascript

The tech stack for front-end web development has expanded vastly in recent years. For veterans of the industry, the progression has been gradual, however for folks just starting out, these changes may not be the easiest to digest. Thus, I compiled a list of front-end tools I use on a daily basis along with the steps I’d take as a newbie to the industry.

The Basics

  • Core Tech
  • HTML
  • CSS
  • JavaScript
  • Terminal
  • Chrome DevTools

The foundational technologies that make up any website are HTML, CSS and JavaScript. If you’re just starting out, the Web Platform Docs and the Mozilla Developer Network are good places to look. While there’s a lot to learn with core HTML, CSS and JavaScript, a solid understanding of the basics is required, and as we’ll see in a bit, many modern tools are layered on top of these foundational technologies.

Additionally, many of the modern tools used in front-end development rely on a basic working knowledge of the command line, which on OS X is Terminal. Pluralsight has a great video by Dan Benjamin that introduces the basics of the command line. Again, its not necessary to become a command line pro to be a front-end developer, but a basic understanding of how to move around, create files & folders, and familiarity with the following will get you further than most: grep, ssh, find, curl, git, npm.

Finally, as a front-end developer, you need some way to inspect the generated HTML markup, CSS styles, and JavaScript that make up any web page you’re working on. The standard for modern web developers are the Chrome DevTools, and CodeSchool has a great course covering what you can accomplish. One item to note here: most modern websites modify the HTML markup using JavaScript. This means the text you see in your source HTML file may differ when you inspect it using the “Elements” tab in Chrome DevTools. This is a concept I became very familiar with while working with jQuery Mobile years ago (and playing with jQuery Mobile may still be a very effective tool for this purpose), but its also something you’ll encounter as you start working with some of the additional tools below.

UI (User Interface) Frameworks:

When you build websites every day, you’ll start to notice some patterns emerging in the projects you’re involved with. Components like navigation bars, buttons and labels, and pagination are all common patterns you’ll likely find yourself repeating over and over. UI frameworks are an attempt to abstract the common elements into reusable modules, so web developers can have a base starting point for the various elements used in their sites or apps.

The most popular of these, by far, is Bootstrap. Bootstrap allows you to rapidly build responsive user interfaces, and as a result is very popular both as a prototyping tool and as a production framework. The Bootstrap docs are organized such that you can become familiar with the basic CSS, progress to CSS components, and move on to the more advanced JavaScript components when you’re comfortable. It’s also worth noting that with some Bootstrap components, you’ll see generated markup that I mentioned in the previous section.

There are many more UI frameworks out there (Semantic UI, Foundation, ChocolateChip-UI, Topcoat, etc.), but one that’s really picking up steam currently is Ionic. Ionic is a mobile UI framework, focused on building iOS and Android apps using Cordova to wrap HTML code as a native app, and uses AngularJS (which we’ll get to shortly) as its JavaScript framework. We’re getting a bit ahead of ourselves, but suffice to say that if you want to build an app for iOS or Android using web technology, and learn AngularJS in the process, there’s no better way than spending some time with Ionic.

Version Control (prereq: Terminal):

You’ll want to keep a record of the work you do, and probably collaborate with other developers. Version control, or source control management, is a way you can incrementally save versions of the file or files you’re working on, and leave notes in the process, which, when grouped together, is called a commit. When you commit the code you’ve been working on it creates a version of that code locally which you can then compare at a later time to remind yourself what changes you made and when you made them. Git and Mercurial are two popular command line tools that serve this purpose. If you’re not comfortable on the command line, there are a variety of GUI applications available like GitHub’s, GitX, Git Tower, and SourceTree.

Taking this one step further, if you want to work on the same code with other developers, you can push your commits to a communal server, where everyone can access your changes. Enter GitHub. GitHub allows you to share your code with other developers, and pull down the work other developers have completed, and merge it with your changes. Overall, version control offers a very visual way to compare your work with the work of other developers, and as such is a great collaboration tool. CodeSchool has a great free course called Try Git, if you’re just getting started.

The Next Layer

Once you’ve covered the basics, there’s another layer of tools that sits on top of foundational web tools. Each of these tools requires a prerequisite understanding of the underlying technology.

Templating Languages (prereq: HTML):

HTML templating languages are an abstraction of common HTML. They exist to make writing HTML less repetitive, less error prone, and more rapid. They require an understanding of compiling the code you’re writing, which means the end result will look very different than the source code you’re editing. Both Handlebars and HAML compile to HTML.

Handlebars is most frequently paired with Backbone, and used in place of standard HTML files in Backbone applications. Rather than writing static HTML, web developers write small chunks of markup in standalone Handlebars files, that can be reused in various locations throughout a single application. Handlebars pairs nicely with Backbone as it gives developers access to data directly in the HTML markup, so you end up writing less JavaScript to get the same result.

HAML is frequently found in Ruby on Rails applications, and is a shorthand method of writing HTML that integrates directly with Ruby code. The driving factor behind HAML is that Ruby’s ERB syntax, like PHP, requires the author to “pop” in and out between writing HTML, and writing markup that will be generated by Ruby. This can lead to code that’s very difficult to read. HAML solves this issue by allowing the author to generate HTML markup without any of the repetitive angle brackets seen in both HTML and ERB.

CSS Preprocessors (prereq: CSS):

Like HTML templating languages, CSS preprocessors allow you to both write code that is compiled, and require a healthy understanding of the underlying language you’re writing (in this case, CSS). They’re very powerful, allowing web developers to write less code, reuse portions of code to decrease repetition (something very common in CSS), and modularize your CSS so you can benefit from conditionally loading CSS rules only when needed. The two most popular CSS preprocessors are Sass and Less.

Sass is an incredibly powerful language that allows developers to introduce more complex programming techniques to CSS, like variables, nesting, and mixins. Sass (and Less) have gained in popularity as the backend techniques of writing object-oriented code have migrated to the front-end. You may have heard of object-oriented CSS, and Sass is a great starting point for learning how to do some really powerful things with CSS. CodeSchool has a great introduction to Sass called Assembling Sass.

Less is an alternative to Sass, but is very similar. Basically, if you understand Sass, you’ll understand Less. There are syntactical differences, but the principles remain the same. Less is what’s used in the Twitter Bootstrap project (mentioned earlier), and as the CSS preprocessor of choice for the most popular UI framework on the planet, has become very popular itself.

JavaScript Preprocessors (prereq: JS):

Rounding out our trilogy of front-end preprocessor categories, CoffeeScript is very similar in that you write CoffeeScript, which then compiles to JavaScript. CoffeeScript is the brainchild of Jeremy Ashkenas, the author of Backbone and Underscore. The goal of CoffeeScript is to allow developers to write JavaScript that reads more like natural language, resulting in source code is very easy to read and understand. What’s actually served to the browser is vanilla JavaScript that can be very difficult to read, though more optimized for performance in a browser (also referred to as being “machine readable”).

The CoffeeScript docs are a great place to start, but there are many free and paid resources available to learn the language, like the CoffeeScript Cookbook, The Little Book on CoffeeScript, Smooth CoffeeScript, Meet CoffeeScript, A Sip of CoffeeScript, or the CoffeeScript Basics RailsCast. Of course, they all require a very good understanding of core JavaScript, so make sure you have a good grounding in the foundational language.

JavaScript Frameworks (prereq: JS):

JavaScript frameworks abstract a lot of the functionality typically left to developers to solve on their own. In the case of jQuery, its main purpose is to allow web developers to focus on the functionality they’re building, and not get distracted with browser inconsistencies with regard to JavaScript. jQuery also abstracts common JavaScript patterns, the most common of which is AJAX (short for Asynchronous JavaScript and XML). jQuery probably should be earlier in the learning stack, but an understanding of it is required to some degree in order to use portions of both AngularJS and Backbone, so I grouped it here.

Backbone and AngularJS are two of the more popular MVC or MV* JavaScript frameworks used in production today. A solid understanding of JavaScript is recommended before diving into JavaScript frameworks. They both allow developers to rapidly produce single-page applications (SPAs), albeit in very different manners. Backbone covers a core set of basic functionality and then gets out of your way, while AngularJS is more robust and opinionated.

Taking the example of AJAX, you have to first understand what AJAX is (The best guy at explaining AJAX is Jeremy Keith, hands down), then understand how the jQuery.ajax function works, in order to understand how the implementations in Backbone (Backbone.sync) and AngularJS ($http) work.

Some resources I’ve found very helpful in getting up to speed with Backbone and AngularJS include The Anatomy of Backbone.JS, Backbone.Marionette: A Gentle Introduction, AngularJS: Up and Running, Shaping Up with AngularJS and A Better Way to Learn AngularJS.

Ready to dig deeper?

Check back next Tuesday for an Intro to Advanced Front-End Developer Tools. In the meantime, let us know what you think! Any questions, thoughts, ideas? Send 'em our way!

Can't get enough? Well here you go!

  • Sass Functions: Play and Profit
  • SEO for Single Page Applications
Categories
Author

Pay it Forward

 

Always be a student…

My first official ‘lesson’ in web development was a six week beginner’s Javascript class. It was offered by the Columbus chapter of Girl Develop It or GDI. I didn’t know it when I signed up, but this would be the springboard for my career.

Honestly, I didn’t retain much of the knowledge presented in those six weeks. I was as green as could be to the programming world. Most of the information sailed right over my head but I did gain something incredibly valuable from attending: the spark to learn more. I wanted to understand, why I didn’t understand. I was hooked.

Teach to Learn

After a year of sharpening my skills and making the leap into full-time web development, I was approached by GDI to TA for the beginner/intermediate HTML/CSS courses.

Talk about feeling extremely under qualified! How was I supposed to stand in front of a group of students and tell them how things should be? What if I didn’t have the answers or steered them in the wrong direction?

After several internal debates and a bit of pressuring though, I decided to give it a go. Not only were my fears terribly off, but teaming up with Columbus’ GDI community was one of my best decisions. Getting to ignite, hone, and nurture students is a pretty great feeling. I never thought I was capable of helping folks in such a significant way. Seeing a student go from overwhelmed and confused to confident in their skills is something everyone should experience.

Since my first course, I’ve assisted five additional semesters and its only gotten better. Now, it’s not just about teaching the curriculum, it’s about finding better, more efficient ways to present the information. As a teacher, the planning and prep has not only helped to sharpen my own skills, but its kept me in the student mindset; always looking for ways to make web development approachable and fun.

Give back

Girl Develop It is an international organization providing affordable and accessible programs to women who want to learn software development through mentorship and hands-on instruction. Although their focus is getting women into tech, they also welcome men to attend classes as well. GDI has chapters all across the USA. And, if they don’t already have a chapter in your town, GDI will help you get a chapter started in your area.

GDI holds all types of events throughout the year. Ranging anywhere from the aforementioned beginner HTML/CSS and javascript classes to more advanced classes, meet ups and social events.

Want to give back and hone your skills in web development? Hit them up and see if you can help!

Categories
Author

angularjs

AngularJS and web forms are a match made in heaven. AngularJS version 1.3 has made it easier than ever for developers to build powerful, user-friendly, and maintainable web forms. Users have certain expectations when confronted with web forms and developers should anticipate these expectations. Therefore, removing any and all obstacles between the user and a completed, valid form is of upmost importance!

Validation

Isn’t it annoying when you fill out a form, hit submit, wait, then the page jumps to the top with some cryptic red text telling you how bad you are at filling out forms? Users hate that. Everyone hates that! Let’s empathize with our users and create a form the sets them up for success.

Enter front-end validation. With the 1.3 release, the Angular JS team bestowed onto us the ng-messages module. This is a tremendous improvement in how we build validation into forms. The module allows developers to have a list of generic error messages for common validation errors as well as craft custom messages for those more complex field types.

Here’s how I use the ng-messages module on a form field:

<div class="error-message"   ng-messages="loginForm.email.$error"   ng-if="loginForm.email.$dirty"   ng-messages-include="views/widgets/formErrors.html"> </div> 

Let’s break down the different directives used here. First, the ng-messages directive on the <div> refers to the error object for the field you are validating. The module will detect any properties on the $error object and display the appropriate error template. Next, is the ng-messages-include directive. This references a template for all of my generic error messages (required, min-length, max-length, etc.). Using a template for these common errors allows very easy maintenance and consistency throughout the application.

Example of a generic message in the formErrors.html template:

<div ng-message="required">This field is required.</div> 

For custom validators, just replace the “required” value with the name of the validator (ex: “pattern”).

Also, the ng-if directive set to the field’s $dirty flag allows us to hide the validation messages ‘till the user enters something into the field. Thus, preventing the form from displaying a bunch of “errors” upon first load.

Expectations

Users expect most forms to work the exact same way on the web. If the user has to spend unnecessary time figuring out how to fill out your form, it builds resentment and frustration; damaging the trust between you and your users. Keep the form consistent and make a point to ensure simple tasks are done right! For example, the “submit” button.

Hitting enter should submit the form. This sounds simple enough, but it’s very easy to overlook. Developers often attach the ng-click directive to a button, point it to a function to submit the form data and call it a day. Without using the ng-submit directive on the form tag, hitting enter won’t do anything to your form. This is especially important on small, short forms like search or sign up because the user is just expecting to submit using the enter key.

Here’s what that form might look like:

<form ng-submit="vm.submitForm()">   <label for="name">Username:</label>   <input type="text" name="username" id="username" ng-model="vm.name" />   <label for="password">Password:</label>   <input type="text" name="password" id="password" ng-model="vm.password" />   <button type="submit">Submit</button> </form> 

Maintenance

Coding forms can be very repetitive, especially when we include the markup for validation. Creating templates for commonly used fields and markup can definitely help keep your code DRY (Don’t Repeat Yourself). You could even go so far as to creating directives for each type of field or form component. Well, I have good news for you. Someone has already done just that: https://github.com/formly-js/angular-formly. This module allows you to keep templates for each type of field and dynamically generate forms using a JSON object. If you’re interested in easily generating forms throughout your application and keeping all forms consistent, angular-formly may save you a ton of time.

Empathy

Following these easy patterns will keep your users happy clicking and tapping through your application. Let’s face it, forms aren’t the most exciting feature, but they are necessary. Why not make them quick and easy and move on to those more awesome features you have to offer?

Want to dig deeper? Check out my codepen to see some of the patterns we discussed in action.

Categories
Author

javascript
Coding JS is an art. As we continue in our JS Fundamentals series we’ll unlock layer by layer the basics to working confidently in the land of Javascript.

Mastering the concept of “scope” is an important step towards mastering writing efficient, easily maintained JavaScript. In this installation of the JS Fundamentals series, we’ll take a high-level look at how JavaScript’s scope works.

There are two levels of scope - “global” and “block.” Of the two, the easiest to explain is global. Global scope variables and functions can be accessed by any portion of the environment in which it’s been created. Examples of this are the window Object or the setTimeout Function in the browser, and Node.js’s require Function.

“Block” scope is a little more tricky - a block scope gets created when you write a Function or a try/catch statement. Unlike other C-based languages, blocks that are defined by braces ({ and }) do not create a new scope; at least, not until ECMAScript 6 is adopted.

Let’s look at a few practical examples.

var foo = “Global variable”;  function globalFunc() {   var bar = “Scoped variable”;    function scopedFunc() {     console.log(‘foo is: ‘ + foo);     console.log(‘bar is: ‘ + bar);   };   scopedFunc(); } globalFunc(); scopedFunc(); 

If you run this, the output that you’ll receive from the two function calls would be “foo is: Global variable”, “bar is: scoped variable”, and a ReferenceError because scopedFunc doesn’t exist in the global scope.

This enables us to write functions (and store variables) that are only relevant to the execution of that scope, which is useful for when you’re running repeated tasks that only need to happen when a specific function is being called, but you don’t necessarily need it to be available anywhere else. Additionally, leveraging scope in this way means that any large variables (if you’re doing some intense data processing like manipulating the points of a GeoJSON map, for example) they can be picked up by the garbage collector when the function’s task is complete, and not continue to sit in memory.

Since we have access to global variables inside of a scope, those variables can get reassigned. Take this example:

var reassignable = ‘I am in the global scope’;  function reassigner() {   reassignable = ‘I am in the block scope’; }   console.log(reassignable); // >> “I am in the global scope”  reassigner(); console.log(reassignable); // >> “I am in the block scope” 

This will return the string “I am in the block scope” in the JavaScript console. Of course, the caveat to this is that you need to be careful with naming your variables. If you reuse a global variable, you’ll overwrite it.

Why is this important?

Scope is crucial to understand when working in JavaScript. The examples we’ve seen so far have been simplistic. One of the most challenging aspects of JavaScript for new developers - the this keyword - is heavily impacted by the scope in which it is being called.

However, it’s bigger than just keeping your this keyword context straight (and that particular subject will be focused on in an upcoming post).

If you’re working on a project of any substantial size (more than some basic prototyping, or a very simple static site with a bit of JavaScript thrown in for some enhancements), chances are good that you’re working with external libraries like jQuery or Modernizr (or, perhaps, both). How do you keep these libraries from colliding with one another? If you have both jQuery and Underscore, for example, how do you ensure that their various each methods don’t get overwritten by the other library?

Technically, these libraries use what’s known as “namespacing,” which is the practice of applying a scope to the library that prevents that library’s methods and variables from overriding the methods and variables of the environment to which they’ve been added.

jQuery uses two - one as an alias of the other - names: jQuery and the more familiar $. Underscore, as you might expect, uses the _ character. Therefore the respective each methods would be $.each and _.each. This is possible through what we’ve been discussing with scoping.

If you look at the code for either library, you’ll see that both are wrapped in something that looks like this:

(function (args…) { })() 

This is what’s known as a closure (and, more specifically, an “Immediately Invoked Function Expression” or IIFE). Though we won’t dig in to closures right now, what we know from what’s been covered so far is that any variables defined within a function is constrained to that function. Therefore, the authors of Underscore can implement their each method inside of that closure and not have to worry about whether or not what they write will interfere with a similarly named function that other libraries may introduce.

Finally, it’s important to note that scope and context aren’t the same thing. Context is all about the specific situation where something is being run, and is most easily explored through the use of the this keyword. Scope is what helps define context.

Variables

As we covered already, variables defined in a scope belong to the scope in which they’re defined. If a new scope is defined within the parent scope, they’ll be accessible the same way that global variables are accessible inside of block scopes.

There’s a caveat to this: if you forget to include the var keyword, any variable you create in a scope is automatically added to the global scope:

var globalVar = 1;  function someFunc() {   var scopeVar = 2;   otherVar = globalVar + scopeVar; }  someFunc();  console.log(‘globalVar: ‘ + globalVar); // >> 1 console.log(‘otherVar: ‘ + otherVar); // >> 3 console.log(‘scopeVar: ‘ + scopeVar); // >> ReferenceError: scopeVar is not defined 

Wait, what was that try/catch thing you mentioned earlier?

The one other place that creates scope, at least in ECMAScript 5, is the try/catch block. This is typically used when you know that a portion of your program has potential to throw an error and you want to make sure that it’s properly handled. The catch portion of this is essentially a function that accepts one argument - the error Object - and it allows you to work with that:

try {   undefFunc(); } catch (err) {   console.log('Error:');   console.log(err);   console.log('--------------------'); }  console.log('Error:'); console.log(err); 

This will print out:

“Error:” [object Error] { ... } // depending on your logging environment, this will either be an object you can interact with or just an indication that an object was logged “--------------------" “Error:” ReferenceError: err is not defined 

Note that the err variable isn’t available in the global scope, while it is available in the catch block’s scope.

In Conclusion

Scope is an important concept to grasp when working with JavaScript (really, with any programming language). As Kyle Simpson points out in his You Don’t Know JavaScript: Scopes & Closures, it’s important to remember that JavaScript is actually not a dynamic language - it’s compiled. When a browser loads a JavaScript file, it offloads the contents of that file to its JavaScript engine, where it’s read, compiled, and executed. Because of this process, it’s important to understand how scopes function, Otherwise you’ll likely run in to unexpected behaviors and errors, especially once your application grows in complexity.

A few good resources (in addition to Kyle Simpson’s book) that help with understanding JavaScript Scope are:

Categories
Author

Web App

This article originally appeared on the Divshot blog. Divshot is a developer-focused platform for deploying modern front-end applications. It was also started with Intridea's support by Michael Bleigh!

A few months ago I came across "Rails' Degenerate Front-End Support" taking Rails to task for slipping behind the state of the art when it comes to front-end dependency management. The pain is real, but the problem isn't that Rails does a bad job with front-end dependencies. The problem is that the front-end has no business living in a Rails app at all.

Web applications in 2005 were engines of request and response. You were always interacting with a snapshot of the data, never the data itself. In this era, it made perfect sense for the server to generate the HTML that landed in the browser. After all, browsers were terrible! IE7 had just come out, Firefox had only a tiny sliver of the market, and anything you could do to keep things server-side was a win.

Sure, AJAX existed and could be cajoled into helping out here and there. By and large, however, the server was running the show. What a difference a decade makes.

What has happened since 2005 came about so gradually that many haven't even realized it happened. Browsers got better. Not just a little better. Browsers got magnificently, insanely, unbelievably better. They became faster, they supported more standards and newer standards, they landed on whole new device categories without giving up (too much) ground. Even better, they started releasing much more frequently ensuring they would continue to get better. In the past decade, the browser has evolved from a document viewer that could be hacked into a basic application provider to a full-blown operating system in its own right.

Backbone, Mind Blown

It all started with Backbone, first of the mainstream modern JavaScript frameworks. Like Rails before it and with just around 1,000 lines of code, it had the audacity to challenge the whole way we built applications. Sure, I'd wired up some pretty complex jQuery code by 2010, even dabbled with real-time, but Backbone was the first library that shouted in your face "your front-end is an application." It showed us a map that showed just how far we had come since 2005, and gave us a glimpse of what was to come.

The seed of the idea had been planted. Your front-end is an application. It makes perfect sense and has now for some time. We test the limits. We move from pull to push. We build more and better interaction away from the request/response mindset. And our users love it. The web is more alive today than it's ever been.

So where does that leave Rails?

We're Gonna Need a Bigger Toolbox

Rails has an inherently monolithic mindset. It's a web app in a box. It's a fantastic framework for tying application code to a data store and preparing that data for rendering to the browser. It has thousands of libraries written by thousands of developers to do thousands of things extremely well. You can still build a great modern web application using Rails. You just can't build one only using Rails.

Yes, Rails has the asset pipeline. There are gems that let you use Bower, Angular, Ember, and everything else you might imagine inside your Rails app. But front-ends aren't kids anymore, and it's starting to get embarrassing when they're still living in their parents' basement.

By now, most Rails developers have picked one or more of the modern JS frameworks to use when building apps. Whether it's Backbone, Angular, Ember, or something else. It's not a change in tools that's needed, it's a change in perspective.

The back-end is for persisting and retrieving data. The front-end is for user interaction. And the two should not live in the same repo anymore.

A Modern Approach

I still love Ruby. JavaScript runs in the browser and has better conventions around concurrency, but if I have a choice of language I'm still picking Ruby. But today when I start building a new application, I make two folders: myapp-api and myapp-web.

In my front-end app, I use a variety of tools suited to the purpose like Yeoman, Broccoli, Grunt, or even just bare HTML. In my back-end app, I create a JSON interface to my application logic and data stores using Grape or Sinatra. I deploy the two applications to two separate servers: api.myapp.com for the back-end, and myapp.com or www.myapp.com for the front-end.

The result is a change both much smaller and much bigger than you'd expect. Before I had completely cut the cord between front and back-end, I was already effectively building two separate applications. I just had the artificial constraint that they needed to live in the same repository for some reason.

After the separation, I find that my architecture is much cleaner. I can focus on a single purpose. When I'm working on the back-end, I worry only about a clear and logical representation of application data. When I'm working on the front-end, my only concern is user experience. More than that, it feels right. It feels like I'm building things correctly.

I'm not saying Rails is dead. While I've moved on to lighter frameworks (admittedly, one I designed myself), Rails is still an extremely capable way to implement your web app's back-end. I just think we should stop pretending that there can or should be a single framework that encompasses all the needs of a modern web application.

Keeping front-end and back-end tightly coupled is condemning them to run a three-legged race, awkwardly tied together when both would benefit from separation. Cut the tie. You'll be glad you did.


Categories
Author
Subscribe to Javascript