22. Know your tools!
var loginField =
document.getElementById('user_login');
function loginChanged() {
alert(loginField.value);
}
if (loginField.addEventListener) {
loginField.addEventListener(
'change', loginChanged, false);
} else if (obj.attachEvent) {
obj.attachEvent('onchange', loginChanged);
}
23. Know your tools!
X
var loginField =
document.getElementById('user_login');
function loginChanged() {
alert(loginField.value);
}
if (loginField.addEventListener) {
loginField.addEventListener(
'change', loginChanged, false);
} else if (obj.attachEvent) {
obj.attachEvent('onchange', loginChanged);
}
44. the classic Solution
•strong coupling
•hard to maintain
•no/ little code reuse
•bloated HTML
•code that actually belongs together is
distributed over several places
•easy to write in the first place
46. Full Separation
•define JavaScript controls that encapsulate
all frontend logic
•mark elements with class, rel or HTML5‘s
data-* attributes
•full separation of HTML and JavaScript
•Initialization of controls on dom:loaded
event
47. Full Separation
•define JavaScript controls that encapsulate
all frontend logic
•mark elements with class, rel or HTML5‘s
data-* attributes
•full separation of HTML and JavaScript
•Initialization of controls on dom:loaded
event
55. Full Separation
•clean, semantic HTML
•full separation of concerns
•clean HTML/CSS/JS is crucial
•Behaviour is (kind of) implicit
•discipline required
57. explicit Controls
•like Full Separation
•but controls are initialized in the templates
•more explicit/ obvious what‘s going on
58. explicit Controls
index.html.erb
<div id="someElement">
some text that's replaced later
</div>
<%= link_to 'Replace', controls_replace_path,
:id => 'replacerLink' %>
<script type="text/javascript" charset="utf-8">
document.observe('dom:loaded', function() {
var replacer = new Replacer('replacerLink', 'someElement');
});
</script>
59. explicit Controls
class ControlsController < ApplicationController
def index
end
def replace
respond_to do |format|
format.js { render :partial => 'new_content' }
end
end
end
60. explicit Controls
_new_content.html.erb
<b>Fresh new content rendered at
<%= Time.now %></b>
<%= link_to 'Replace again', controls_replace_path,
:id => 'secondReplacerLink' %>
<script type="text/javascript" charset="utf-8">
var newReplacer = new Replacer(
'secondReplacerLink', 'someElement'
);
</script>
61. explicit Controls
_new_content.html.erb
<b>Fresh new content rendered at
<%= Time.now %></b>
<%= link_to 'Replace again', controls_replace_path,
:id => 'secondReplacerLink' %>
<script type="text/javascript" charset="utf-8">
var newReplacer = new Replacer(
'secondReplacerLink', 'someElement'
);
</script>
No initialization on dom:loaded here as this is
the result of an AJAX request (dom:loaded not
fired)
62. explicit Controls
•HTML is (mostly) clean and semantic
•Behaviour is explicit in the templates
•easier to grasp what‘s going on than with
Full Separation
•though not as nice as full separation