开发者

Why its recommended not use onclicks in your HTML.Use Event Handlers in your JS file

Why its recommended not use onclicks in your HTML.Use Event Handlers in your JS file is consi开发者_JAVA百科dered as best practice???


You can only have one handler with on*.

But no limits on the number of handlers you can attach to the same element for the same event when using the event registration model.

Besides, it helps consolidate all behavior within Javascript and not sprinkled throughout the codebase.

Note: you can attach events using on* inside your Javascript as well. The DOM event registration model was introduced to fix this very problem. See this example for more information:

// HTML
<p id="somePara" onclick="alert('First')">...</p>

// Javascript
var el = document.getElementById("somePara");

el.onclick = function() {
    alert("Second");
};

el.onclick = function() {
    alert("Third");
};

// when <p> is clicked, it alerts "Third", overwriting the first two handlers.

Instead, a better approach is to use the event registration. Continuing the above example (this is just for demonstration and it's not cross-browser),

el.addEventListener("click", function() {
    alert("Un");
});


el.addEventListener("click", function() {
    alert("Dos");
});

// clicking on the <p> will now alert "Third", "Un", and "Dos".


It separates your code from your content and markup. The cleaner that separation is, the easy it is to maintain, especially when your team is bigger than 1.


Also, it contributes to the separation of concerns. HTML is the structure of your page, but Javascript is the "behavior". Separating the structure from the behavior allows more code reuse and ease of maintenance. (This is also why presentation [css] is separated from structure)


It promotes a clean separation between design (HTML, CSS) and action (javascript). For much the same reason that its best to keep server side code separated from the display code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜