JQuery: Why Unobtrusive JavaScript / Document Read

2019-01-23 00:02发布

问题:

I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

<form ...>
<p>Find what? <input ...></p>
<div class="ButtonArray">
  <a href="AddRecord.ASP&amp;Action=ADD">ADD</a>
  <a href="#" onClick="return MyFormSubmit();">FIND</a>
</div>
</form>

This displays Buttons for [Add] and [Find]. For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the for the Find button and in JQuery I could write something like:

$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot of programming topics, there is more than one approach and people will vehemently stand by their beliefs! If we're talking about a single method for a single button, I totally understand where you're coming from...

If we're talking about lots of JavaScript, with same function calls for more than one element, different function calls for different methods, etc. I think that it would be more difficult for oneself to mix inline and unobtrusive approaches, and it would be better to adopt one or the other approach"

回答1:

Unobtrusive JavaScript is the main driver for separating JS code from markup

  • Separation of functionality (the "behavior layer") from a Web page's
    structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support
    advanced JavaScript functionality

With the code in document.ready, it will not execute until the DOM has loaded and before the page contents are loaded

From Learning jQuery

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.

You may want to take a look at jQuery in Action, I'd highly recommend it. You can sample Chapter 1 and Chapter 5 on the book's homepage. I think doing so may provide further insight into why separation can work well.

Finally, have a look at this question which has answers that detail how you would find the event listeners on a DOM node.

EDIT:

Some thoughts which may persuade you why unobtrusive JavaScript can be a good idea.

Imagine that you have a function bound as an event handler for the same event raised on each of a number of elements -

  • Would it be easier to find out which elements call that function to handle an event when the declaration is inline in each element, or the declaration is in one place, outside of the markup?

  • What if you want to add to the elements that call that function when the event is raised on each of them? Would it be easier/better to add the event handler inline to each element or to change the code in one place?



回答2:

the document ready event is well before the document load event. document ready occurs once the DOM is loaded which is so that all the elements exist before you start working on them.

So yes the JS will be ready as the document is rendered. The other point about binding is that it is useful for changing bindings to elements when cetain actions occur.

You can still declare the action on the element if you prefer though.



回答3:

Over time I think you get used to the jQuery syntax and reading:

class="MyFormSubmit" becomes as informative as reading onClick="return MyFormSubmit();

Where the power really starts to kick in (aside from all the benefits mentioned by other posters) is the ease with which you could change the onClick binding via selectors tied to other actions on the web page in ways that never seem to present themselves initially.

One question I ask myself is how deep I plan on going with any new tool, if I am planning to make extensive use of a framework or library then writing my code in it's "more native" coding style will become a lot more natural and other developers that know the tool will find the code a lot cleaner and more understandable.



回答4:

You do it this way to seperate the UI logic from the actual HTML design.