21

I'm pretty new in our develepors team.

I need some strong arguments and/or "pitfall" examples, so my boss will finally understand the advantages of Unobtrusive JavaScript, so that he, and the rest of the team, stops doing things like this:

<input type="button" class="bow-chicka-wow-wow" 
       onclick="send_some_ajax(); return false;" value="click me..." />

and

<script type="text/javascript">

function send_some_ajax()
{
  // bunch of code ... BUT using jQuery !!!
}
</script>

I suggested using a pretty common pattern:

<button id="ajaxer" type="button">click me...</button>

and

<script type="text/javascript">

// since #ajaxer is also delivered via ajax, I bind events to document 
//  -> not the best practice but it's not the point....

$(document).on('click', '#ajaxer', function(ev) {
var $elem = $(this);
ev.preventDefault();

});

The reason why my boss (and others) do not want to use this approach is that the Event-Inspection in FireBug (or Chrome Dev Tools) isn't simple anymore, e.g. with

<input type="text" name="somename" id="someid" onchange="performChange()">

he can immediately see what function executes on change-event and jump right to it in a huge JS file full of spaghetti-code.

In the case of Unobtrusive JavaScript the only thing he would see is:

<input type="text" name="somename" id="someid" />

and he has no idea whether some events, if any, were bound to this element and which function will be triggered.

I was looking for a solution and found it:

$(document).data('events') // or .. $(document).data('events').click

but, this "approach" caused it to take "too long ..." to find out which function fires on which event, so I was told to stop bind events like that.

I'm asking you for some examples or strong advantages or any other kind of suggestions for "Why we should use UJS"

UPDATE: suggestion to "change the job" is not an ideal solution.

UPDATE 2: Ok, I've not only suggested to use jQuery event-binding, I did so. After I wrote all Event-Delegation, the Boss came to me and asked me, why am I doing event delegation with different approach and approach he dind't know

I mentioned some obvious benefits, like - There are 15 input-fields and all of then have an onchange event (not only, some of them have also onkeyup) So it's more pragmatic to write this kind of event-delegation ones for ALL input-fields, instead of doing it 15 times, especially if all of the HTML will be rendered with PHP's echo -> echo '... <input type="text" id="someid" ... />...'

5
  • The "class" in your first codebox probably needs an =.
    – Joe Z.
    Commented Feb 20, 2013 at 19:30
  • 6
    You can: 1) convince your boss to let you use techniques he does not know; 2) teach your boss new techniques; 3) stop using techniques your boss does not know; or 4) change a job. Did I forget an option? If you don't want 4, and you can't succeed in 1 and 2, your only remaining option is 3. Just keep in mind that your market value depends on what you know. So after you learn everything your boss approves of, your remaining options are: 3A) stop learning and watch your market value drop; 3B) learn and use new techniques in your free time. Option 3A costs you money, option 3B costs you time. Commented Feb 21, 2013 at 13:53
  • 1
    I would use the an approach like github does: every element that have events binded in JS has a js-this-class-do-something class, so, you can easily CTRL+F for it in the code.
    – caarlos0
    Commented Feb 21, 2013 at 19:32
  • FireQuery could help with the "takes too long" part. Not sure how well it works with events, but it should at least tell you that an element has events on it.
    – Izkata
    Commented Feb 24, 2013 at 18:59
  • 1
    Here's a nice utility that I love to use when working with events
    – karka91
    Commented Feb 27, 2013 at 7:05

5 Answers 5

50
  1. Stop using buzzwords and try making strong arguments instead. Even the Wikipedia page for Unobtrusive JavaScript says that the term isn't formally defined. It may be a blanket term for a number of good ideas, but if it sounds like a mere fad or fashion your boss and coworkers won't pay a lot of attention. Worse, if you keep going on about something they view as useless, they may start to discount completely unrelated ideas that you advocate.

  2. Figure out why you think the Unobtrusive JavaScript ideas are important. Is it because you read that they're considered best practices? Have you run into problems that you can attribute to not following these ideas? How much will adopting these ideas impact the company's bottom line?

  3. Get inside your boss's head. Why does he do things the way he does, and why has he rejected your changes? He's probably not stupid, and he's probably more experienced than you are, so he probably has some good reasons for doing things his way. You've already alluded to some of them -- follow that thread to its end. Then figure out if and how your suggestions will improve the things that he's most concerned about.

  4. Hint 1: Managers like money. The more directly you can tie your suggestions to increased income or reduced spending, the more impact your argument will have. Hint 2: Time is money. Hint 3: By itself, the aesthetic appeal of code doesn't make money. The opposite, in fact -- it takes time to make code look nice. Ugly code that works well is just fine with most managers.

  5. Don't just talk about it, do it. If you're lucky enough to have a small, self-contained project come your way, ask your manager if you can do it using the "UJS" style as a sort of demonstration. When you're ready, hold a code review where you can explain how it all works and why you think it's better than the current style.

  6. Idealism is great, but don't let it get in the way. It's more important to be seen as someone who gets things done than as a dilettante who complains about uncouth coding style. This is especially true if you're the new guy. If you can't get traction with UJS now, get some good work done instead and slowly build a case for the changes you'd like to make as you gain credibility.

  7. Read Switch: How to Change Things When Change is Hard. It'll give you a lot more good ideas about how to build your case effectively.

8
  • The gist of the answer is prove that ujs works realistically. Show them it works. Commented Feb 20, 2013 at 14:33
  • 2
    @AvinashR The point is just that the thing that motivates managers is often not the same thing that motivates developers. We developers like code to be nice and tidy, elegantly designed, etc. Managers want to maximize profit. If your change will result in more sales, great. If it results in shorter development time or less time spent reworking or fixing bugs, great. Glad to hear that clients like your GUI, but does the boss attribute that to UJS or to the way the GUI looks? If clients look at your code and say "we want our code to look like this!" it should be easy to make your case.
    – Caleb
    Commented Feb 20, 2013 at 15:31
  • 3
    In addition to "Switch", I'd also recommend "Driving Technical Change" by Terrance Ryan: terrenceryan.com/book. Also, in "Hello HTML5 and CSS3", Rob Crowther puts it simply: "HTML for content, CSS for presentation, and JavaScript for behavior." By keeping the JavaScript out of the HTML, you can build a library of behaviors and reuse HTML all over the place with no extra coding. That, to Caleb's point #4, saves time and money. Commented Feb 20, 2013 at 17:19
  • 2
    Point 3: Dont overrate experience. I'd rather want on my team a super talented 22-year old Leo Messi rather than a 32-year old overpaid experienced lazy casual Premier League player. Young, fresh, talented blood is often very valueable. Commented Feb 20, 2013 at 21:41
  • 1
    "Managers want to maximize profit." -- Managers also want to reduce risk; might be another avenue. Commented Oct 30, 2013 at 9:41
8

What you can do is give them a demo of debugging a USJ html using the tools FireQuery as well as Chrome Query.

FireQuery is a firebug extension and does a pretty good job at it. As for Chrome Query, I cannot vouch for how much it is good, but it definitely is used by some of the devs (a post at stackoverflow).

Also know that the .data function is removed to return the internal event data since jQuery 1.8.0, and replaced with $._data(element, "events") which can be unstable, as per the official changelog

This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.

UPDATE:
When I started working I had the same dilemma. But upon creation of a demo with fully functional GUI (single page application) which included dynamically opening tabs (closable too), Accordion menu (dynamically created from db), they finally understood that it is better to use USJ all the way.

Also the plus of using USJ is that you can minify your entire application into a small (unreadable) script. Also show them the scripts for google.com / github.com (as an example), and point out that even they are having the code compressed, which is always better, as the viewer of site will have a hard time decoding the security flaws and utilize them to start a full-fledged attack on your site (scare them), even though unlikely.

UPDATE 2:
Btw, I didn't knew I was doing USJ until I saw this question, so thanks in one way.

2

Inline event handlers stink because:

  • No event delegation - which is great when you want to be able rip elements in and out of a page dynamically without having to rebind.

  • You've bound behavior to HTML tags rather than class/ID attributes of HTML tags. Let's say you have a class of "combo_box" all across your app. Suddenly, on half your old pages, you want a slight variation on your combo boxes when they're in a different container. Tied to a class, you can alter that behavior based on container context, e.g. "#special_container .combo_box". Bound inside the damned HTML you could find yourself tracking down every little select box with a .combo_box class in any number pages to change those handler references one by one rather than tweaking or writing a couple new lines of code to filter from a single file location.

  • If you want multiple handlers, you have wrap them in a function and then bind that unnecessarily to specific HTML files. How maintainable is that?

  • A subtler point is that it is much easier/more maintainable/flexible and robust to handle behavior with more of a control panel mentality. By binding from a central location, you've got a place where you can get an overview of all behavior happening on the page all at the same time, which is handy when, for instance, you need to figure out why certain pages occasionally run into a certain bug that's hard to understand but not others.

  • This is the client-side. We have multiple browsers all interpreting heavy complexity in their own ways to account for. Slop-it-all-together and let the IDE sort it out for you mentalities do not work well here. Keeping your code tight, minimal, loosely coupled and clean is not fashionable, it's absolutely essential in order to establish a maintainable front end that's easy to modify and update and yes, that's where the $$$s come in assuming your manager actually has foresight.

  • It's not !@#$ing 2002 anymore. This argument is as old as tables as layout. Get over it and start trusting experienced client-side-specialized dev you yourself hired expressly because you lacked their expertise (not that I'm channeling any anger from personal experience or anything).

And to rebutt your boss's argument, it's really not that hard to track down what class or ID is being used in event delegation or handler binding with CTRL+F and a tool that lets you view all JS on the page like my own personal embarrassingly jquery/prototype-only bookmarklet version I hastily cobbled together when web dev toolbar's started crapping out on me (damned color-coding). Bookmark from the link at the js fiddle page or copy the JS and make your own.

A JS fiddle link that will presumably expire eventually

3
  • +1 Finaly someone pointed out the main disatvantages of inline JS. Will use this arguments in next debate with the my boss.
    – V-Light
    Commented Feb 24, 2013 at 16:28
  • @V-Light Did they work? Commented Dec 9, 2013 at 19:01
  • 2
    nope! The 'ChangeYourOrganization' option was the solution
    – V-Light
    Commented Dec 9, 2013 at 21:04
0

One major advantage of your suggested technique is you only have to bind once the event handler to a parent such as "document" and this handler will be able to catch the events coming from all children that satisfied the given selector such as "button.anyclass". Saves memory and maintainable such that only need one edit instance and it affects all elements.

With regards to not being able to recognize at once the bound function, your team just could standardize a way on declaring such functions probably on the bottom most part of the page. So you all know where to look at, naming convention also is very important.Comments would be hugely beneficial, but make sure it is being stripped away by the server before serving it as response to the browser.

Also, if you want to provide obfuscation and minification of javascript for security purposes, your technique would make it possible, unlike the old style your team is still using.

-2

The obvious answer is that you can only bind one function to your button with the onclick attribute, whereas the JQuery event allows you to bind multiple functions. A common problem with the onload event: if your document is composed of more than one file, collisions often happen.

Another solution that could satsify both you and your boss is the use of data-binding, with a library like Knockout or Angular, which would keep track of modifications on your view and suppress the need for a large part of the event handlers.

5
  • 1
    regarding Knockout, Angular and other JS frameworks for cool-kids...unfortunately it's not an option. The reason is the same as above...it's "too much" or "too new" or "too cool" or just "we don't want to learn something new, let's do it old (stupid/dumb) way..."
    – V-Light
    Commented Feb 20, 2013 at 11:41
  • @Niphra: In addition, you can only bind a function to only one component. Commented Feb 20, 2013 at 11:43
  • 3
    @V-Light: "You can ChangeYourOrganization or ChangeYourOrganization." Maybe this is interesting for you: jamesshore.com/Change-Diary Commented Feb 20, 2013 at 11:46
  • Hey, my company sticks with Classic ASP because ASP.NET is "too new", yet I still managed to push Knockout in our code. Try to see what their concerns really are and see if you can make a change. Commented Feb 20, 2013 at 13:11
  • 1
    @Niphra "my company sticks with Classic ASP:" that's.... terrifying. Commented Feb 25, 2013 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.