JQuery event binding
I saw a lot of jQuery code like this, it goes without saying that I don't like:
<div id="myDiv">
<a class="clickable" href="#">Click Me</a>
<a class="clickable" href="#">Click Me</a>
<a class="clickable" href="#">Click Me</a>
<a class="clickable" href="#">Click Me</a>
</div>
<script>
$(document).ready(function(){
$('clickable').click(function(){
// Do some stuff...
});
});
</script>
I understand that people do this because the event binding and processing involved requires the html structure to be accessible on the page, but this leads to a confusion of presentation, logic and configuration across all website representations. In addition, it is very difficult to debug logic using any debugger.
So, I started coding as follows: in a separate .js file (fiddle here) :
// BEGIN: Event Handlers
var onLoad = function(){
$('.clickable').data('clicked', false);
};
var onMyDivClick = function(){
var clicked = $(this).data('clicked');
if (clicked) {
$(this).trigger('myCustomEvent');
} else {
alert('you clicked me');
$(this).data('clicked', true);
}
};
var onMyCustomEvent = function(){
$(this).css('color', 'dimGray');
alert('please don\'t click me again');
};
// END: Event Handlers
// BEGIN: Event Binding
$(window).on('load', onLoad);
$(document).on('click', '.clickable', onMyDivClick);
$(document).on('myCustomEvent', '.clickable', onMyCustomEvent);
// END: Event Binding
Now I do not need to care about the structure located on the page. I don’t need to wrap everything inside $(document).ready(function(){});And I don’t need to worry about whether the structure will be loaded using ajax or not.
1 ? . , .
2 jQuery?
, . , .
- / - http://knockoutjs.com/
- backbone - http://backbonejs.org/
- ember js - http://emberjs.com/
- angular js - http://angularjs.org/
", " :
http://knockoutjs.com/examples/helloWorld.html
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
// Here my data model
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
. document.ready , .
, dom , . , , .
. . , 5 , - ? 10? , 15?
"" (, , ifs ifs). . .
, , . - , "" , , . , "" "" " ".
, . : - . , .
As previously reported, angular and trunk and ember (and many others) provide the means to achieve what you want. In addition, you do not need to maintain whichever library you choose :)