This is a completely updated post to explain the problem in a better way with an improved concept an code (based on the answers given here so far)
I try to realize a completely ajaxed website, but I got some problems with multiple bound events.
This is the basic HTML:
<header id="navigation">
<ul>
<li class="red" data-type="cars">Get Cars</li>
<li class="red" data-type="vegetables">Get Vegetables</li>
</ul>
</header>
<div id="anything">
<section id="dymanic-content"></section>
</div>
The navigation is been created dynamically (as the content of #navigation can be replaced with another navigation), so the binding for the nav-elements would look like this:
$('#navigation').off('click', '.red').on('click', '.red', function() {
var type = $(this).attr('data-type');
var data = { 'param': 'content', 'type': type };
ajaxSend(data);
});
The content of the site is also being loaded dynamically. For example there are two different content:
1:
<div id="vegetables">Here are some information about vegetables: <button>Anything</button></div>
2:
<div id="cars"><img src="car.jpg"></div>
While loading the content, I will also load a specific JS-file, which has all the bindings needed, for this type of content. So the loading-script looks like this:
var ajaxSend = function(data) {
$.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" })
.done(function( json ) {
if (json.logged === false) { login(ajaxSend, data); }
else {
$.getScript( 'js/' + json.file + '.js' )
.done(function( script, textStatus ) {
$('#result').html(json.antwort);
});
}
});
}
As you pass the parameter for the type of results you need (i.e. vegetables or cars), the result will be shown in #result. Also the files cars.js or vegetables.js would be loaded.
So my problem is to avoid multiple event bindings. This is how I'm doing it:
cars.js:
$('#result').off('mouseover', 'img').on('mouseover', 'img', function () {
// do anything
});
vegetables.js:
$('#result').off('click', 'button').on('click', 'button', function () {
// do anything
});
Is this the proper way? I think it is just a workaround to use off(). So I would appreciate any improvements!
Furthermore I don't know if there is a problem, if the user clicks on the navigation multiple times: In that case the js-files are loaded multiple times, aren't they? So are there multiple bindings with that concept?