What does event binding mean? - javascript

What does event binding mean? I always come across this word whenever I search around the internet and whatever I try to look for the meaning, it's still vague to me #_#
A while ago, while reading some blogs regarding JavaScript I see people using this sacred word that I cannot grasp.

Event binding refers to telling the browser that a particular function should be called whenever some 'event' occurs. Events mostly relate to user input, such as clicks.
An example of binding to an event in jQuery can be the following:
$("#elem").bind("click", function() {
alert("Clicked!");
});
This binds a function to click event of DOM object with identifier elem. When user clicks it, an alert (message box) will be shown. Binding is done by invoking the jQuery bind function but there are other means to do that, (e.g. jQuery click function in case of binding to click event).

When you bind something to an event, it will be triggered when the event is fired. It's like gluing a fog horn to the brake pedal on your car.

When you perform an action on a web page, it will trigger an event. This might be something like:
Click a button
Select a value from a drop down
Hover the mouse over an item
These events can be captured in your JavaScript code.
A common (and often misguided) way of capturing events is to do so on the HTML element itself (as shown in the onclick attribute below)
<input id="MyButton" type="button" value="clickme" onclick="Somefunction()" />
So, when the user clicks the button, the SomeFunction function will be executed.
However, it is considered a better approach to adopt a technique called 'late-binding'. This ensures that your HTML and JavaScript are kept completely separate.
So, we can modify the above exmample like so:
document.getElementById("MyButton").onclick = function(){
//functionality here.
}
jQuery makes this even easier:
$("#MyButton").click(function(){
//functionality here.
});

Binding in JS, is to capture some events (like focus, click, onmouseover, etc) and perform some other stuff before the actual process starts.
Detailed explanation:
http://triaslama.wordpress.com/2008/07/22/four-ways-javascript-binding-event-listeners/
http://api.jquery.com/bind/

Related

Vue.js enter key and blur events together

I am trying to make it so that if I press enter key or if element loses focus then it hides the element and shows a message. But the problem is that when I press the enter key and the element hides then it also triggers the blur event. It should only execute one of them.
Also how could I avoid having to repeat myself twice by calling the hideField() function. Can I call it only once (bur or key.enter)?
<input id="name" v-on:blur="hideField('name')" v-on:keyup.enter="hideField('name')">
Here is a fiddle.
http://jsfiddle.net/dag5ch26/3/
You should call the blur method on the keyup.enter event. This results in the blur event being triggered indirectly.
<input id="name" v-on:blur="hideField('name')" v-on:keyup.enter="$event.target.blur()">
Given the limitations of your example, I don't think it is necessary to fire the event on enter like you have it. As you see, the keyup.enter event also fires the blurs event, so why not rely on the blur exclusively? I understand you may have simplified your use case, but I don't see a reason for the keyup.enter here.
As a side note, instead of selecting the element by ID, you can just use
event.target for the element reference. E.g. #v-on:blur="hideField". The event is passed to hideField() automatically. Alternatively, you could do #v-on:blur="hideField($event.target)" which would just pass the element itself to the method. This simplifies your call(s) and reduces unnecessary lookups.
I've updated the fiddle here: http://jsfiddle.net/dag5ch26/7/
I don’t believe there is a way to do this currently, although a v-on-many would be nice in future.
You could bind the event handlers yourself in JavaScript during the created life cycle handler.
Something like the below (although IMo this may be worse than your current implementation):
Component code {
...
created() {
window.addEventListener(‘click keyup’, function() {
this.myComponentMethod(); }
} }

Do I need to delete duplicate dynamic functions in Javascript?

I just got through figuring out that I need to watch out for duplicate event handlers in jquery if I'm dynamically assigning them multiple times as described here: http://www.parallaxinfotech.com/blog/preventing-duplicate-jquery-click-events
Do I need to watch out for this or handle it somehow if I'm declaring a function dynamically within another function multiple times? How does JavaScript really handle this? Does it only use the last function that was called or does it only instantiate a function once at load time? From what I can tell it's not running the function multiple times.
$(document).on("click",".button",function() {
function alertThem()
{
alert('Clicked!');
}
alertThem();
});
JavaScript will remember every function you're assigning it.
$('button').click(function(){
alert('hi')
})
$('button').click(function(){
alert('hi')
})
The code above will alert "hi" twice. If you're assign new function and you want to clear the old one, you can do unbind().click(). what it will do is it will unbind all events, or you can do unbind('click') which will unbind just the click. see https://jsfiddle.net/rznbtc1p/
$('button').click(function(){
alert('hi')
})
$('button').unbind().click(function(){
alert('hi')
})
The link you provided does not work (gives me timeout) so I hope I understood what you asked.
About what happens there:
In your script you created a closure and bound it to a click event. Each time you click on the element with class button, the anonymous function is triggered. Each time is triggered it defines function alertThem(), and calls it. Only once defines it, only once calls it. The scope of that function is its parent, the closure. That function is not defined outside that scope, so no need to worry about double definition.
Side note here: Personally as a rule of thumb don't think is a good idea to define functions like this, but if it suits your project... go for it.
Now about duplication. Since I cannot see the link, I think you are referring to double event binding.
In js can bind any number of events to the same element. You can for example bind on click something that says "Hi, you clicked me", then bind also on click something that says "Hi, you received a message before saying you clicked me". When you click that element, you will see both messages.
This can actually become a problem. You have 3 options:
Be really careful how you bind events
Keep tracking of what you bound
Check if events are already bound (although that is a bit unreliable). You can check how here: jQuery find events handlers registered with an object
In your code snippet, you aren't creating duplicate event handlers.
What is happening in your snippet is that you are creating a new function alertThem within the scope of your click handler function and then executing it in the line below.

Performing an action on Parent/Child elements independently

I have HTML similar to the following in my page
<div id="someDiv">
<img src="foo.gif" class="someImg" />
</div>
The wrapper div is set up such that when it is clicked, it's background-color changes using the following jQuery code.
$("div").click(function(event){
$(this).css("background-color", "blue");
});
I also have some jQuery associated with my img that will do some other function (for the sake of argument I am going to display and alert box) like so:
$("img[class=someImg]").click(function(event){
alert("Image clicked");
});
The issue I have come across is that when I click on the img, the event associated with the div is also triggered. I'm pretty sure that this is due to the way that jQuery (or indeed JavaScript) is handling the two DOM elements - clicking the img would require you to also technically click the div, thus triggering both events.
Two questions then really:
Is my understanding of the
DOM/JavaScript flawed in some way or
is this actually how things are
occurring?
Are there any jQuery methods that
would allow me to perform actions on
a child element without invoking
those associated with its parent?
That is known as event bubbling, you can prevent it with stopPropagation():
$("img[class=someImg]").click(function(event){
alert("Image clicked");
event.stopPropagation();
});
.
Is my understanding of the DOM/JavaScript flawed in some way or
is this actually how things are
occurring?
That is because of what is known event bubbling.
Are there any jQuery methods that would allow me to perform actions
on a child element without invoking
those associated with its parent?
Yes, you need stopPropagation()
No, this is by design. Events bubble up through the entire dom, if you put another handler on body, it would fire too
Yes :) JQuery normalizes the event object, so adding event.stopPropagation() in your img click handler will give you the behavior you expect on all browsers
The problem you just facing is called "event bubbling". That means, if you click on a nested
element, that click event will "bubble up" the DOM tree.
If other elements also are bound to an click event, their listeners will fire aswell.
Solution to prevent this is called:
stopPropagation()
which is used within your event handler
$("img[class=someImg]").click(function(event){
event.stopPropagation();
alert("Image clicked");
});
This is what's called event bubbling, and you can stop it to get the behavior you want with .stopPropagation() (or return false; if you want to stop the event completely, including handlers on the same level), like this:
$("img[class=someImg]").click(function(event){
alert("Image clicked");
event.stopPropagation();
});
You can view a demo here, comment it out and click run again to see the difference.
The short version is that when most event types happen, they happen on the immediate element, then bubble up the DOM, occurring on each parent as they go. This is not jQuery specific at all, native JavaScript does this. If you're more curious, I'd read the linked article, it has a great explanation of what's going on.

jquery ajax events called on every element in the page when only targeted at one element

So, you have a page:
<html><head>
<script type="text/javascript" src="jquery.1.3.2.js"></script>
<script type="text/javascript">
$(function() {
var onajax = function(e) { alert($(e.target).text()); };
var onclick = function(e) { $(e.target).load('foobar'); };
$('#a,#b').ajaxStart(onajax).click(onclick);
});
</script></head><body>
<div id="a">foo</div>
<div id="b">bar</div>
</body></html>
Would you expect one alert or two when you clicked on 'foo'? I would expect just one, but i get two. Why does one event have multiple targets? This sure seems to violate the principle of least surprise. Am i missing something? Is there a way to distinguish, via the event object which div the load() call was made upon? That would sure be helpful...
EDIT: to clarify, the click stuff is just for the demo. having a non-generic ajaxStart handler is my goal. i want div#a to do one thing when it is the subject of an ajax event and div#b to do something different. so, fundamentally, i want to be able to tell which div the load() was called upon when i catch an ajax event. i'm beginning to think it's not possible. perhaps i should take this up with jquery-dev...
Ok, i went ahead and looked at the jQuery ajax and event code. jQuery only ever triggers ajax events globally (without a target element):
jQuery.event.trigger("ajaxStart");
No other information goes along. :(
So, when the trigger method gets such call, it looks through jQuery.cache and finds all elements that have a handler bound for that event type and jQuery.event.trigger again, but this time with that element as the target.
So, it's exactly as it appears in the demo. When one actual ajax event occurs, jQuery triggers a non-bubbling event for every element to which a handler for that event is bound.
So, i suppose i have to lobby them to send more info along with that "ajaxStart" trigger when a load() call happens.
Update: Ariel committed support for this recently. It should be in jQuery 1.4 (or whatever they decide to call the next version).
when you set ajaxStart, it's going to go off for both divs. so when you set each div to react to the ajaxStart event, every time ajax starts, they will both go off...
you should do something separate for each click handler and something generic for your ajaxStart event...
Because you have a selector with two elements, you're creating two ajaxStart handlers. ajaxStart is a global event, so as soon as you fire any ajax event, the onajax function is going to be called twice. So yes, you'd get two popups.

Locating an element in a 'Facebox' box

Heres my link:
http://tinyurl.com/6j727e
If you click on the link in test.php, it opens in a modal box which is using the jquery 'facebox' script.
I'm trying to act upon a click event in this box, and if you view source of test.php you'll see where I'm trying to loacte the link within the modal box.
$('#facebox .hero-link').click(alert('click!'));
However, it doesn't detect a click and oddly enough the click event runs when the page loads.
The close button DOES however have a click event built in that closes the box, and I suspect my home-grown click event is being prevented somehow, but I can't figure it out.
Can anyone help? Typically its the very last part of a project and its holding me up, as is always the way ;)
First, the reason you're getting the alert on document load is because the #click method takes a function as an argument. Instead, you passed it the return value of alert, which immediately shows the alert dialog and returns null.
The reason the event binding isn't working is because at the time of document load, #facebox .hero-link does not yet exist. I think you have two options that will help you fix this.
Option 1) Bind the click event only after the facebox is revealed. Something like:
$(document).bind('reveal.facebox', function() {
$('#facebox .hero-link').click(function() { alert('click!'); });
});
Option 2) Look into using the jQuery Live Query Plugin
Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
jQuery Live Query will automatically bind the click event when it recognizes that Facebox modified the DOM. You should then only need to write this:
$('#facebox .hero-link').click(function() { alert('click!'); });
Alternatively use event delegation
This basically hooks events to containers rather than every element and queries the event.target in the container event.
It has multiple benefits in that you reduce the code noise (no need to rebind) it also is easier on browser memory (less events bound in the dom)
Quick example here
jQuery plugin for easy event delegation
P.S event delegation is pencilled to be in the next release (1.3) coming very soon.

Categories

Resources