Filed under

front-end development

See all posts on posterous with this tag »

Patterns for DRY-er JavaScript

Posted

I came across a little code the other day that reminded me I've been meaning to write about JavaScript patterns I take for granted. The code in question was intended to set the value of some fields in a form when a checkbox was selected; when it was deselected, the same fields were to be emptied. It looked not unlike this:

// config is defined outside of this snippet,
// and may contain more than the properties
// we care about 
$('#myCheckbox').click(function() {         
  if (this.checked) {                 
    $('#field_foo').val(config.foo);                 
    $('#field_bar').val(config.bar);                 
    $('#field_baz').val(config.baz);         
  } else {                 
    $('#field_foo').val('');                 
    $('#field_bar').val('');                 
    $('#field_baz').val('');         
  } 
});

This is a wholly readable bit of code -- there's almost no question what's going on here. On the other hand, it's pretty easy to see the rampant repetition; this code isn't interested in "don't repeat yourself" (DRY). We're calling the same method on every selection we make, and our selections are repeated in both the if and else block. When I saw this code, I had an immediate inclination to rewrite it. Here's what I came up with first:

// config is defined outside of this snippet,
// and may contain more than the properties
// we care about

$('#myCheckbox').click(function() {
        // note whether the checkbox is checked
        var checked = this.checked;

        // iterate over the keys we care about
        $.each(['foo', 'bar', 'baz'], function(i,v) {
                // find the field for the given key
                $('#field_' + v)
                        // and set its value either to the string
                        // stored for the key, or to an empty string,
                        // depending on whether the checkbox was checked
                        .val(checked ? config[v] : '');
        });
});

This looks approximately nothing like the initial code, and without the comments, the code itself would be substantially less readable than the original. The idealistic part of me -- the part that believes people who write JavaScript should understand JavaScript -- says this is an acceptable price to pay. And besides, there's something to be said for explaining the code in a comment that can be stripped by a minifier, rather than explaining the code via the code. In this iteration, we've introduced two patterns for DRY-er code: iterating over an array literal (or, alternately, an object) to achieve repetition without repeating ourselves, and using the ternary operator in place of an if/else statement when the simplicity of our logic allows it. The array literal serves as a list of the fields we care about. When our checkbox is clicked, we iterate over this list, build up a selector for each item in the list, make our selection, and then set the field value using a ternary operator. We've gone from 11 lines of code to six, with the added bonus that we have to do a lot less typing if we need our checkbox to affect more fields. (A side note: Is this premature optimization? I'd argue no, if you've learn to see these patterns before you start writing code. Once you learn how to spot these patterns in a requirement, writing code that embraces them can actually be easier than writing code that takes a more "literal" approach to the problem. For example, imagine if the checkbox affected 20 other fields instead of one? You'd undoubtedly find yourself copying and pasting code if you took the more "literal" approach to the problem, and that would be your first clue that you were doing something inefficiently.) The great thing about using a pattern like this is that it rapidly exposes the actual meat of what you're doing, and makes refactoring far less painful. I also find that it helps me see opportunities for reuse that I might not have spotted in the more literal version of the code. Let's say we're feeling all proud of ourselves for DRYing out our code using clever JavaScript that only super-smart people can read. Now there's another checkbox that needs similar behavior, but it's going to use a different config object and a different list of fields. No problem! You've already written this code, so you can just copy and paste it and then change what's different. Sweet. Er ... suddenly you're not looking so DRY after all. This is when another pattern comes into play: creating a function that returns another function with certain variables already baked in (that is, creating a closure). We'll execute this creator function and then use the function it returns in place of the anonymous function we were using previously when we bound to the click event.

// handleClick accepts a config object
// and a makeSelector function; it returns
// a function that can be bound to 
// a click event, using the config object
// and the makeSelector function to react
// appropriately to the click
var handleClick = function(fields, config, makeSelector) {
        return function() {
                var checked = this.checked;

                fields && $.each(fields, function(i, v) {
                        // build the selector using the provided
                        // makeSelector function
                        $(makeSelector(v))
                                // set the value using the
                                // config object, depending
                                // on whether the checkbox
                                // is checked
                                .val(checked ? config[v]: '');
                });
        };
};

$('#myCheckbox').click(
        // use handleClick to create a function
        // that has these variables baked in;
        // pass the created function as the
        // click handling function
        handleClick(
                ['foo','bar','baz'],
                myCheckboxConfig, 
                function(field) {
                        return '#field_' + field;
                }
        )
);

$('#myOtherCheckbox').click(
        handleClick(
                ['bim','bar','bop'],
                myOtherCheckboxConfig, 
                function(field) {
                        return 'input[name="' + field + '"]';
                }
        )
);

By creating a function that returns a function, we can isolate what's different about the two different handlers while centralizing the pieces that are the same. If your event handling function was slightly less trivial than this one, or if you were binding to five different checkboxes instead of two, the benefit of consolidating the code would be even more substantial. JavaScript offers plenty of patterns for writing DRY-er code; it's important to learn to both recognize and use them. It's also important to recognize when you're writing un-DRY code in the first place -- copying and pasting code is one crystal-clear indicator, but others are more subtle and you may not identify them on the first go-round. For example, take these two functions; each receives a list item as its only argument and returns either the next or previous list item, returning to the beginning or end of the list if there is no next or previous item.

var getNextItem = function($item) {
        return $item.next().length ? 
                $item.next() : $items.first();
};

var getPrevItem = function($item) {
        return $item.prev().length ?
                $item.prev() : $items.last();
};

This felt repetitive when I first wrote it, but I couldn't quickly come up with a single function that would work. A little thinking about it, though, led me to this single function which gets a second argument: direction. That argument is used to decide whether to run the item's next or previous method, and then whether to run the item's first or last method. Besides combining two functions into one, it also eliminates calling next or prev twice inside each function.

var getItem = function($item, direction) {
        var $returnItem = $item[direction]();
        return $returnItem.length ? 
                $returnItem : 
                $items[(direction == 'next') ? 'first' : 'last']();
};

Learning about patterns and then discovering opportunities to use them is one of the more pleasing parts of my job. I hope this helps you identify some of those opportunities for yourself :)

Filed under  //  front-end development   howto   javascript  
Comments (24)
Posted

Announcing jQuery Fundamentals: An Open-Source jQuery Training Curriculum

Posted

I've been leading jQuery trainings for more than a year now, from tiny gatherings that I organized myself at the local coworking space, to intensive two-day sessions at local web companies, to whirlwind one-day classes at governmental agencies. Over the course of those trainings, I've developed what I'd like to think is a decent curriculum -- training material that's the size of a small book, exercises that demonstrate core concepts, and solutions to those exercises that students can peek at later or when they get stuck. I decided recently that it was time for all of this material to see the light of day, so I spent the last several days converting it all to DocBook files that allow for easy publication to HTML and PDF (and other formats, if I'm later so inclined). I also fleshed out some topics that I'd given short shrift, and started planning sections covering advanced topics such as plugin authoring, code organization, best practices, and more. There's more to come in the next few days, but I think what I've done so far is worth sharing. I hope you'll agree.


Media_httpgyazocoma21_qfifz


My goals in releasing this are several. First and foremost, I want to see people writing better jQuery. The free resources for learning jQuery are scattered across the internets, and my personal experience of learning the library was haphazard — it was a long time before I learned some things I wish I'd known from the get-go. In addition, I want people who are writing jQuery to understand JavaScript. To that end, the book begins with a survey of JavaScript itself before jumping into jQuery. Finally, I want to enlist the bright minds of the jQuery community to help developing a robust, authoritative, in-depth jQuery curriculum, and in exchange it only seemed fair to make it available to everyone. I should mention that the goal of this material is to serve as a companion to a human instructor. That said, individuals may find it useful for self-study, especially if they're diligent about doing the exercises at the end of each chapter. If you're inclined to help -- by adding a chapter, a section, a paragraph, an exercise, or even just a correction -- fork the repo and send me a pull request. I look forward to seeing how this project might evolve with the community's help. Note: If you comment on this post pointing out an issue with the material, I will do my best to tend to the issue, but I probably won't publish your comment, as this post isn't the right place for reporting issues in the code. You can report issues at the repository, but if it's important to you, please fork the repository, make the change, and send me a pull request.

Filed under  //  front-end development   howto   javascript   jquery   jquery fundamentals   training  
Comments (37)
Posted

Lessons Learned from Taking On a Project in Crisis

Posted

I just got done with an emergency project for an agency developing a public-facing application for a mutinational technology client you've most certainly heard of. I developed the entire front-end -- HTML, CSS, and JavaScript -- for a non-trivial application with a limited spec in just seven days. The experience was so eye-opening that I feel the need to write down some of the things I've learned, in hopes that I can benefit from my experience in the future.

  • Demand all technical source material up front, such as functional specs, mockups, work that's been done to date, etc. Give the client a fixed amount of time to deliver that source material, and don't make a decision about taking on the project until you've seen it. What the client can deliver in that fixed amount of time will shed a lot of light on the state of the project and whether their expectations are realistic.
  • Set clear time expectations. Am I willing to work 16 hours a day? Am I expected to? Are there hours during which I'll be expected to be available? Am I willing to work on the weekend?
  • Find out whether the client expects me to be available after the imminent deadline, and to what extent. The last thing I want is to snatch defeat from the jaws of victory by being unable to support the code I've written.
  • Do not accept responsibility for commitments made on my behalf. The recruiter said I'd be available six hours a day when I told him four? Not my problem. The client committed to having a feature ready for review without consulting me? They probably won't make that mistake again.
  • Ascertain the rest of the team's commitment to the project. If I'm expected to work long hours, will they be there during those long hours to get me what I need? Are there any constraints on their availability?
  • Establish a single point of contact at the client, and make clear I'll be depending on them to get me any information I need and I'll be treating their decisions as final. Insist that they participate in all calls I'm expected to participate in.
  • Limit the amount of work I do before I have access to all client systems I'll need access to: version control, testing environments, ticketing systems, etc.
  • Insist on a ticketing system. I'm new to the project and I have a lot to get up to speed on. I don't want emails flying at me from all directions -- decisions and technical requirements need to be documented in a single place that everyone can see. This is my only insurance when someone wants to know why something isn't done, or why it wasn't done the way they expected.
  • Insist on version control, even if it's something crappy like CVS. I'll need a way to make sure the rest of the team has access to my latest and greatest. FTP blows, especially when I'm FTPing to a server where another developer is constantly deploying a new build, overwriting my work.

What other advice do you have?

Filed under  //  dojo   freelancing   front-end development   thoughts  
Comments (12)
Posted

srchr: Crowdsourcing JavaScript wisdom

Posted

UPDATE: The deadline for completing your submission is April 16, the day before JSConf. If you're at the conference, join others in the hacker lounge to see what they did! I've been working on a blog post about using classes and pub/sub for structuring jQuery applications, and I had in mind a pretty simple demo app that I was going to build. I also wanted to show a version of the app that was built in a more traditional way, and I'd been pondering whether I should write that version myself, or see if I could cajole someone else into doing it. And then, a moment of inspiration: rather than a contrived counter-example, why not get a whole bunch of developers to show how they'd tackle the problem, so we can all gain from the exercise and learn from each other? I tweeted my idea, and five minutes later I had a dozen volunteers and counting, which is downright awesome and in hindsight shouldn't be surprising. It's so rare that we get to see multiple approaches to a moderately complex problem -- it's much more common to see horrendous code and bitch about it :)

The project

I've put together a mock/spec for a small, strictly client-side application that uses YQL to search for content and then displays it to the user. (Click on the image to see it full-size.)
Media_httpblogrebecca_cudcn
Think of this as an exercise in creating a product, not a site that you finish and walk away from -- the goal is to create an extensible, modular application. That said, there are no "right" answers here: the point is for you to demonstrate how you, personally, would approach the problem.

Presenting your solution

I've created a github repository for the project that contains nothing more than some documentation, the mock/spec, and a few stub files and directories. You should fork this repository to get started. If you create some CSS that you'd like to share, I'd encourage you to send a pull request so I can make it available to everyone; this isn't an CSS exercise, so no one should labor over that part if they don't want to. I may very well write some basic CSS myself in the next couple of days, but it's late :) Finally: please comment on this post if you have any questions!

Filed under  //  front-end development   javascript   jquery  
Comments (18)
Posted

On gaining respect as a front-end developer

Posted

Someone wrote me today:

Where I work, design is highly valued with the leader of that group being our Creative Director, back end programmers are also highly valued, but front end ... not so much. Partly I think its that I don't toot my horn but I know there are other reasons. At times, my bosses haven't even understood what it is that I do. Back end programmers look down on front end assuming that its trivial or something that should be relegated to compilers. I was wondering if this is a common thing or more so something that is happening at my particular company, and if you have any advice or pointers on this.
I thought my response might be worth sharing: I do think this attitude is common but not necessarily the rule. In my experience, I've found that by having a proven value proposition, you can gain converts and respect. Front end developers are in a unique position to improve page performance (perceived and actual) by using best practices such as the YSlow tests. Front end developers are also in a unique position to help develop templating systems and to write thoughtful CSS, both of which help enable the rapid prototyping and rollout of new features. A focus on results and best practices -- demonstrating that you aren't just pushing pixels around -- is the key. Back end developers respect people who think like they do. Be mindful of opportunities for abstraction and reuse. Write object-oriented CSS and JavaScript. Craft solutions that are maintainable and documented. Learn and make use of version control systems. Look for opportunities to participate in developer conversations about new features, and understand what the back end developers are up against. They'll appreciate all of this. Take the time to teach and to learn. Be sure you have at least a passing understanding of the code the back end developers are writing, and leap at opportunities to share your knowledge. I've worked with more than one back end developer who was surprised to discover what all they didn't know about the front end, and through our conversations about how we approached problems, we both learned a lot. Finally: identify opportunities for quick victories, execute on them, and make the results known. Benchmark before and after. Can you reduce the number of HTTP requests on a page, decreasing both the perceived and actual rendering time? Are you keeping your JavaScript out of the <head> as much as possible, preventing pages from stalling while rendering? Can you write JavaScript that is primed for reuse, and demonstrate opportunities for that reuse? Has your carefully crafted CSS allowed the rapid rollout of a new feature? Don't be afraid to tell these stories -- they'll tend to strengthen your position by clarifying the important role the front-end developer plays in a site. Good luck :)

Filed under  //  front-end development   thoughts  
Comments (12)
Posted

CSS vs. Tables: Maybe the design is to blame?

Posted

There's been some backlash lately against CSS, and some of it seems so well reasoned that even I find myself wondering if tables are really so bad after all. From giveupandusetables.com, which says the maximum time to spend before abandoning CSS is 47 minutes, to the well-illustrated blog post by Ron Garret, the general argument is that CSS isn't up to the task of faithfully reproducing elaborate designs cross-browser in an acceptable amount of developer time. In his post about Garret's article, Dion Almaer at Ajaxian opines:

CSS purist[s] may poo poo him and say "he is just dumb and doesn't REALLY know CSS." The problem though is that most developers run into exactly the pain that he describes. We’ve all been there. It drives you nuts and when frustrated what do you do? You fluster about and change CSS like a mad man until it kinda looks right. And, you never learn what the real problem was, and thus destined to make the same mistake again.
It seems that while developers are thinking about sacrificing web standards for the perceived simplicity of tables, the viability of the design rarely enters the debate, and that's a shame. In my experience, some of the most difficult designs to produce using CSS were fundamentally flawed from the get-go, created by designers who failed to grasp that the web is not like print. The web is not like print. In print, designers have near-total control over the output, because the number of new "pages" -- items of content -- is limited by the cost of printing. If a print designer wants text vertically centered in a fixed-height column, or two columns that are exactly the same height, or rounded corners with drop shadows on top of gradients, there's no reason they can't have that. The cost of printing is sufficiently high, and print graphics programs are sufficiently sophisticated, that making those design decisions has no impact on the marginal cost of production. On the web, the marginal cost of creating a new page of content can be approximately zero, but to achieve that we must build pages that adapt to unpredictable content and unpredictable users. If we don't, we won't realize the economies of scale that the web has to offer. The tradeoff for that infinitesimally small marginal cost is that the rules have to be different, because the cost of implementing those print-centric design decisions is inordinately high. Instead of sophisticated graphics programs, the web has mere humans to turn PSDs into working pages; instead of content created by experts and pored over by editors, the web has volumes of user-generated content, and the ability to change it on a whim. On the web, equal-height columns will cease to be equal height when the content changes; vertically centered content will outgrow its fixed-height bounds; and rounded corners with drop shadows on gradients can't possibly be worth the cost of producing them. These are not problems with CSS that should be solved with tables. They are, fundamentally, problems with the design. When I talk about this to other developers (and any designers who are willing to give me the time of day after I'm done pointing out how costly their design will be to produce), I make the analogy that it's just as absurd to impose these print-centric design conventions on the web as it would be to use holograms for every picture in a magazine. Sure, you can, but that doesn't mean you should. So what's a web developer to do? When designs reach the desk of the CSS developer, more often than not they've been through so many rounds of review, revision, and approval -- by people far-removed from the realities of the web -- that the developer has little choice but to toil away at reproducing them faithfully. The best defense may be a good offense, which is to say, the burden is on you, dear developer, to educate the misguided designers. Here are some tactics I've used:
  • Impose yourself early in the process, insisting on wireframes and information architecture documents (even if they're just sketches and an outline). Identify potential problems early on, but don't become a naysayer -- make sure you offer ideas, not just criticism.
  • Push back -- gently but firmly -- on design decisions that have the potential to cause problems down the road. Ask lots of "what if" questions and insist on answers.
  • Be honest about how long it will take you to accomplish a design -- with yourself and with your boss or client -- and identify opportunities to make cost-saving changes to the specifics of the design without changing its spirit.
  • Have examples at the ready of similar problems solved in more web-centric ways. The Yahoo! Design Patterns Library can be an excellent resource for this, but look also to other sites in your industry or genre.
The burden's also on you to get better at CSS. I am lucky in that, when I first started playing around with web production, I was a little intimidated by tables. A background in print production steeped in templates and stylesheets made tables seem awkward and strange to me; CSS, temperamental as it was, at least bore some resemblance to the cascading style sheets of print production programs like Quark and InDesign. These days, it's rarer and rarer (but not unheard of) that I find myself beating my head against the wall over a CSS problem. I've learned HTML and CSS patterns that I reuse often, and I've learned to spot -- and speak up about -- design-induced ratholes. If you're finding yourself sucked in by the latest round of CSS vs. tables debate, take heart, stand firm, and reconsider the source of your frustration.

Useful things:

Filed under  //  css   front-end development  
Comments (18)
Posted

Solution for Google Map contents not showing

Posted

I just spent more time than was reasonable trying to figure out why some Javascript I was using to show a Google map on one site wasn't working to show the map on another site. The map controls and copyright were rendering, but there was no actual map. Turns out the problem wasn't with my Javascript; I had a CSS rule that was setting overflow:hidden on all divs within a container, and the divs created by the Google map API were getting that rule too. No good. I wrote a new CSS rule to set overflow:visible on all divs inside the map container -- problem solved.

Filed under  //  front-end development   troubleshooting  
Comments (0)
Posted

Notes on handing off a design to a front-end developer

Posted

I've been spending a lot of time lately turning other people's designs into working websites, and often there are a few rounds of back-and-forth before I have everything I need. Some notes on must-have pieces before I can begin work: Design

  • Custom fonts. If the design includes fonts that aren't on this list, then either the designer needs to provide a PSD that has all instances of the font being used in the design, or else I'm going to need the font file in order to create them. (There may be licensing issues here, which I leave as an exercise for the reader. In print land, we were allowed to provide the print shop with the fonts required to produce a printed piece, and the print shop was not supposed to retain them once the print run was complete. I imagine something similar applies to web production.)
  • Navigation state information. What should navigation elements look like in the up, over, and current states? Ideally I'd like to see all of the buttons in each state, but if the variations are simple then I can probably make them myself.
  • Link state information. What color should links be? Should they be underlined all the time, or only on hover? What color should they be when they are hovered? When they've already been visited?
  • Form treatment. If the site has any forms on it, what should form elements -- text inputs, submit buttons and input labels -- look like?
  • Typography specifications. Decisions about these can dramatically affect the feel of the site, and you may not want to leave them up to me. Specifically:
    • How big should body copy be?
    • How much space should there be between body copy lines? (Normally the "line-height" is set at 1.2 times the size of the font; increasing this can make body copy more legible.)
    • How much space should there be between body copy paragraphs?
    • How should headings be styled? How big should primary and secondary headlines be relative to the body copy?
    • How should lists (ordered and bulleted) be styled?
  • Imagery specifications. Like typography specifications, these considerations should be made carefully, as they affect the feel of the site. Specifically:
    • How should text wrap around an image? Should the image float to the left, with copy wrapping around the right? Float to the right, copy on the left? Leave it up to the user?
    • If an image is floated to the left or right, how much space should be between it and the text?
Documentation
  • Approved content documents. Personally I prefer a single content document per static page that needs to be created, and a content sample for any dynamic pages that will need to be created. If there are any repeating elements in the design that require content, I'd enjoy getting a document that contains their text as well. Lastly, if there are any dynamically generated content items -- for example, a list of latest posts -- I'd like a document that shows me how these should be formatted. This will help me:
    • Make sure I've accounted for the pieces of the content and how they fit together.
    • Know that all content has been considered, reviewed and approved, so there shouldn't be too many surprises later.
    • Reconcile the content documents with any other documentation I've received.
  • Functional spec document. Let me know what should happen when someone fills out a form. Let me know how the items in the sidebar should be gathered. Let me know where that video's going to come from. Basically, anytime I ask "Where does that come from?" or "What does this do?", the functional spec should answer that question. While a functional spec should be initiated long before the design is complete, it is good to review the design and make sure those questions are answered. A functional spec should also include a sitemap.

Filed under  //  freelancing   front-end development  
Comments (0)
Posted

5 reasons you don't really want a jack-of-all-trades developer

Posted

I've spent the last couple of weeks trolling Craigslist and have been shocked at the number of ads I've found that seem to be looking for an entire engineering team rolled up into a single person. Descriptions like this aren't at all uncommon:

Candidates must have 5 years experience defining and developing data driven web sites and have solid experience with ASP.NET, HTML, XML, JavaScript, CSS, Flash, SQL, and optimizing graphics for web use. The candidate must also have project management skills and be able to balance multiple, dynamic, and sometimes conflicting priorities. This position is an integral part of executing our web strategy and must have excellent interpersonal and communication skills.

Really. Now I don't know about you, but if I were building a house, I wouldn't want an architect doing the work of a carpenter, or the foundation guy doing the work of an electrician. But ads like the one above are suggesting that a single person can actually do all of these things, and the simple fact is that these are fundamentally different skills. The foundation guy may build a solid base, but put him in charge of wiring the house and the whole thing could, well, burn down. When it comes to staffing a web project or product, the principle isn't all that different -- nor is the consequence. I've thought a lot about this these last couple of weeks, and I don't think this post is sour grapes about the fact that I don't have the top-to-bottom, front-to-back web development skills that this ad and others seem to be asking for. I'm proud and confident of the abilities I've assembled when it comes to front-end development, and I have a rock-solid understanding of what makes websites tick. The thing is, the more you know, the more you find out you don't know. A year ago I'd have told you I could write PHP/MySQL applications, and do the front-end too; now that I've seen what it means to be truly skilled at the back-end side of things, I realize the most accurate thing I can say is that I understand PHP applications and how they relate to my front-end development efforts. To say that I can write them myself is to diminish the good work that truly skilled PHP/MySQL developers are doing, just as I get a little bent when a back-end developer thinks they can do my job. So to all of those companies who are writing ads seeking one magical person to fill all of their needs, I offer a few caveats before you post your next Craigslist ad:

  1. If you're seeking a single person with all of these skills, make sure you have the technical expertise to determine whether a person's skills match their resume. Outsource a tech interview if you need to. Any developer can tell horror stories about inept predecessors, but when a front-end developer like myself can read PHP and think it's appalling, that tells me someone didn't do a very good job of vetting and got stuck with a programmer who couldn't deliver on his stated skills.
  2. A single source for all of these skills is a single point of failure on multiple fronts. Think long and hard about what it will mean to your project if the person you hire falls short in some aspect(s), and about the mistakes that will have to be cleaned up when you get around to hiring specialized people. I have spent countless days cleaning up after back-end developers who didn't understand the nuances and power of CSS, or the difference between a div, a paragraph, a list item, and a span. Really.
  3. Writing efficient SQL is different from efficiently producing web-optimized graphics. Administering a server is different from troubleshooting cross-browser issues. Trust me. All are integral to the performance and growth of your site, and so you're right to want them all -- just not from the same person. Expecting quality results in every area from the same person goes back to the foundation guy doing the wiring. You're playing with fire.
  4. Asking for a laundry list of skills may end up deterring the candidates who will be best able to fill your actual need. Be precise in your ad: about the position's title and description, about the level of skill you're expecting in the various areas, about what's nice to have and what's imperative. If you're looking to fill more than one position, write more than one ad; if you don't know exactly what you want, try harder to figure it out before you click the publish button.
  5. If you really do think you want one person to do the task of an entire engineering team, prepare yourself to get someone who is OK at a bunch of things and not particularly good at any of them. Again: the more you know, the more you find out you don't know. I regularly team with a talented back-end developer who knows better than to try to do my job, and I know better than to try to do his. Anyone who represents themselves as being a master of front-to-back web development may very well have no idea just how much they don't know, and could end up imperiling your product or project -- front to back -- as a result.

If your budget really is limited to a single position, you might want to consider whether you'd be better off working with several contractors with specific and proven skills, rather than a single person who claims to encompass everything you're after. Your management overhead will increase in the short term, yes, but your headaches down the road will decrease exponentially. In the process, you'll gain access to people who can help you evaluate potential full-timers, and probably gain some insight into the actual list of skills a full-timer needs to provide. If you're one of the people who's written these ads, all is not lost. Invest in a technical consultant -- probably one you can't afford to hire full-time -- to help you really understand your needs and the skills required to solve them. Often they can assist you with writing and posting the ad, and interviews too. For example, I'll meet with a client, write and post a detailed ad, identify candidates, and interview contenders; if I don't have the technical skills required to evaluate a candidate, chances are I personally know someone who can. Doing that homework up front, and understanding and describing what your needs really are, is vastly more likely to give you the perfect fit you're after than if you just cast a wide net and see what you catch.

Filed under  //  front-end development   hiring tips   thoughts   web developer  
Comments (40)
Posted

Attach data from classnames to an element using $().data()

Posted

At DailyStrength, we're working on an abstract way to attach a Javascript behavior (popping a modal, sliding in a form) to objects -- journals, comments, etc. -- being displayed on the site. We wanted to attach some information to the objects by putting their type and ID in classnames. Then it would be up to Javascript to extract that data if it needed it. Previously, I'd done this on an as-needed basis with a function custom to the object and behavior, but I wanted a way to do it going forward without thinking about it. I'd read about the $().data() function that was made available in jQuery 1.2.3, and figured I could leverage it for the purpose. Now, given an element like

an element
I can use a simple plugin to assign data to an element:
{
  key1 : [ value1, value2, value3],
  key2 : value4
}
This means that I can then do $(element).data('key1') and get back the array. I also added a little helper to get back all of the keys for an element, so I can do:
$(element).getDataFromClassname();
var element_keys = $(element).data('keys');
var element_data = [ ];
$.each(element_keys, function(key,value) {
  element_data[key] = value;
});
Here's the simple plugin:
$.fn.getDataFromClass = function() {
        return $(this).each(function() {
                var $this = $(this);
                if ($this.attr('class').match('_')) {
                        var classes = $this.attr('class').split(' ');
                        var keys = [ 'keys' ];
                        $.each(classes, function(i,c) {
                                if (c.match('_')) {
                                        var parts = c.split('_');
                                        var prefix = parts[0];
                                        keys.push(prefix);
                                        var data;
                                        if (parts[1].match('-')) {
                                                data = parts[1].split('-');
                                        } else {
                                                data = parts[1];
                                        }
                                        $this.data(prefix,data);
                                }
                        });
                        $this.data('keys',keys);
                }
        });
};

Filed under  //  front-end development   howto   jquery  
Comments (0)
Posted