does jquery have an equivalent of dojo.connect()? - javascript

Forgive my ignorance as I am not as familiar with jquery. Is there an equivalent to dojo.connect() ?
I found this solution : http://think-robot.com/2009/06/hitch-object-oriented-event-handlers-with-jquery/
But there isn't disconnect feature !
Do you know other solution in jquery ? There are jquery.connect but this plugin not work in my tests.
Thanks for your help,
Stephane

The closest equivalent jQuery has is .bind(), for example:
$("#element").bind('eventName', function(e) {
//stuff
});
And .unbind() to remove the handler, like this:
$("#element").unbind('eventName');
There are also shortcuts for .bind(), so for example click can be done 2 ways:
$("#element").bind('click', function() { alert('clicked!'); });
//or...
$("#element").click(function() { alert('clicked!'); });
There is also .live() (.die() to unbind) and .delegate() (.undelegate() to unbind) for event handlers based on bubbling rather than being directly attached, e.g. for dynamically created elements.
The examples above were anonymous functions, but you can provide a function directly just like dojo (or any javascript really), like this:
$("#element").click(myNamedFunction);

What do you mean by an equivalent to dojo.connect() ?
If you are willing to create your own custom event handlers, look at bind(), trigger() and proxy() in the Events.
The proxy() function will alow your to redefine what this points to in your callback function.

There isn't as such but you can acheive the same thing as follows:
$('#someid').click(function() { SomeFunc($(this)) });
That will wire somefunc, to the click event of control with id "someid". When the control is clicked the function will be called and the parameter will be a jquery object that refers to control that was clicked.
Update I have just done a bit more research and i think .delegate() is closer to what you want.

jQuery connect is equivalent to dojo.connect.

Related

Idiomatic way to set property to function value using jQuery

To hopefully head off the "primarily-opinion-based" close-button-clickers, I'm not looking for opinions on the "best" way to do this; I'm just wondering if there is a more straightforward solution that I'm missing.
My goal is to add the same onclick method to all of the (hundreds of) checkboxes on my page. My first attempt at a jQuery solution was this:
$('input[type="checkbox"]').prop('onclick', function(){alert("Boop!");})
But that runs into the computed-value behavior of $.prop() and calls the function immediately for each checkbox.
So I can do this:
$('input[type="checkbox"]').prop('onclick', function(){return function() {alert("Boop!");}})
But that feels awfully workaround-y. Alternatively, I could do this:
$('input[type="checkbox"]').each(function(_, cb) {
cb.onclick = function(){alert("Boop!");};
});
But that seems uncharacteristically manual for jQuery.
So am I missing a more straightforward solution?
Declare the function and then simply refer to it by name:
function handler() { alert("Boop!"); }
$("input[type='checkbox']").on("click", handler);
Note that you shouldn't be setting up event handlers by setting the "onfoo" properties.
edit — if what you want to avoid is adding the handler over and over again, use delegation:
$("body").on("click", "input:checkbox", handler);
That creates only one event handler registration. As "click" events bubble up the DOM to the body, jQuery will check to see which ones targeted elements that match the selector, and invoke your handler for those that do. (Opinion — I've mostly adopted the practice of exclusively using body-level delegation for all events. It makes things a lot less messy.)
you have to write event no use prop:
$('input:checkbox').on('click', function(){alert("Boop!");})
i will suggest to use change event for checkbox not click:
$('input:checkbox').on('change', function(){
if(this.checked)
{
alert("checked");
}
});

Efficient way of binding events to element in jQuery

I have one anchor element in my page
Click
I know in jQuery we have so many ways of binding events to element like (bind, live, delegate, on).
FYI:
http://blog.tivix.com/2012/06/29/jquery-event-binding-methods/
Currently using jquery1.8.3.min.js. I want to know which one is standard and efficient event registration model in jQuery?
Currently I am doing it like this:
$("#page").click(function(){
................................
});
Can I change to bind like below code:
$("#page").bind("click",clickFunc);
function clickFunc()
{
..........
}
Which one is best practice to register the event in jQuery 1.8 ?
The best way is the way one can understand what's written and the one that works.
The smart way is to use what's suggested to use, in this case the .on() method:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()
The how-to way depends if you need to delegate your event/s to dynamically generated elements or not.
$('.child').on( 'click', function() { /* ... */ });
$('#parent').on( 'click', ".dyn-gen-child", function() { /* ... */ });
.on is the standard method:
$("#page").on("click", function() {
.......
});
If the p element is generated dynamically, you'll have to do:
$(document).on("click", "#page", function() {
.......
});
Actually, after jQuery 1.7, on is the preferred way to bind events rather than bind. So I prefer on API.
And then:
click(function(){})
is just the shortcut of
on('click',function(){})
Internally, they are actually the same -- when the on param is event, handler, but on is more general because it can do more than simple onClick(example:event delegation) see:link
so I recommend on

jquery use of bind vs on click

I have come across several methods for handling click events in jquery:
bind:
$('#mydiv').bind('click', function() {
...
});
click:
$('#mydiv').click(function() {
...
}
on:
$('mydiv').on('click', function() {
...
}
Two questions:
Are they any other ways of doing this?
Which one should I use, and why ?
UPDATE:
As eveyone has helpfully suggested, I should have read the docs better, and found out that I should use:
on() or click(),
which are effectively the same thing.
However, nobody has explained why bind is no longer recommended ? I'll probably get more downvotes for missing the obvious somewhere, but I can't find a reason for this in the documents.
UPDATE2:
'on' has the useful effect of being able to add event handlers to dynamically created elements. e.g.
$('body').on('click',".myclass",function() {
alert("Clicked On MyClass element");
});
This code adds a click handler to elements with a class of 'myClass'. However, if more myClass elements are then dynamically added later, they automatically get the click handler as well, without having to explicitly call 'on'. From what I understand people are saying, this is also more efficient (see Simons answer below).
From the documentation of bind and click :
bind :
As of jQuery 1.7, the .on() method is the preferred method for
attaching event handlers to a document.
The source makes it clear there's no reason to use bind, as this function only calls the more flexible on function without even being shorter :
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
So I'd suggest, just like the jQuery team, to forget the old bind function, which is now useless. It's only for compatibility with older code that it's still here.
click :
This method is a shortcut for .on('click', handler)
This shortcut is of course less powerful and flexible than the on function and doesn't allow delegation but it lets you write a shorter and, arguably, slightly more readable, code when it applies. Opinions diverge on that point : some developers argue that it should be avoided as it is just a shortcut, and there's also the fact that you need to replace it with on as soon as you use delegation, so why not directly use on to be more consistent ?
To your first question: there's also .delegate, which was superseded by .on as of jQuery 1.7, but still is a valid form of binding event handlers.
To your second question: You should always use .on like the docs say, but you should also pay attention on how to use .on, because you can either bind the event handler on an object itself or a higher level element and delegate it like with .delegate.
Say you have an ul > li list and want to bind a mouseover event to the lis. Now there are two ways:
$('ul li').on('mouseover', function() {});
$('ul').on('mouseover', 'li', function() {});
The second one is preferable, because with this one the event handler gets bound to the ul element once and jQuery will get the actual target item via event.currentTarget (jQuery API), while in the first example you bind it to every single list element. This solution would also work for list items that are being added to the DOM during runtime.
This doesn't just work for parent > child elements. If you have a click handler for every anchor on the page you should rather use $(document.body).on('click', 'a', function() {}); instead of just $('a').on('click', function() {}); to save a lot of time attaching event handlers to every element.
I think that you should have searched the jquery docs before posting this question :
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

hover and moveout not giving expcted result

Because I am creating DOM using Jquery it was difficult to copy the output so i am adding one image of code that i have captured using one tool
i have attached hover and mouseout event to id='nf1' using this code
$("#nf"+n).hover(function(){
$("#nf"+$(this).attr("post_id")+"post_delete").show();
});
$("#nf"+n).mouseout(function(){
$("#nf"+$(this).attr("post_id")+"post_delete").hide();
});
Here n is post_id and i am looping all post_id got from response.This attach events but not giving expected behaviour Like when mouse over to id='nf1post_delete' it is hide
Please ask if any doubts
The way you're describing this, you will actually want to pass two functions to .hover(), one for the action on mouseenter and one for the action on mouseleave. You can pass only one function to .hover(), but it will run that function when you roll over and when you roll out.
http://api.jquery.com/hover/
So, try this instead:
$("#nf"+n).hover(function(){
$("#nf"+$(this).attr("post_id")+"post_delete").show();
},function(){
$("#nf"+$(this).attr("post_id")+"post_delete").hide();
});
The .mouseout() function isn't needed at all.
At first, .hover() includes mouseenter and mouseleave. Do you put both function in there and don't use an additional event. Also don't use mouseout(). Use instead mouseleave().
So you either use hover(function(){},function(){}); alone, or you use mouseenter() and mouseleave().
Since you're manipulating the DOM, I'm going to recommend using jQuery .on() instead of .hover():
$(document).on({
mouseover: function(){
$("#nf"+$(this).attr("post_id")+"post_delete").show();
},
mouseout: function(){
$("#nf"+$(this).attr("post_id")+"post_delete").hide();
}
}, "#nf"+n);
If you're creating something in the DOM after the page has loaded, .on() helps to attach event listeners to it.
jQuery API for .on()

jquery late binding

i have a code that bind's on click action on page load, it is a link. When i clicking it, it send ajax request and replace content in some div with jquery append() function. This new content has a links and i need to bind some action for them, but i could't.. bind did't work i think, because jquery append doesn't update DOM tree. How could i get a late binding?
There are 3 functions that can do this:
$(selector).live(events, data, handler); - jQuery 1.3+ - version deprecated: 1.7, removed: 1.9 (reference)
$(document).delegate(selector, events, data, handler); - jQuery 1.4.3+ - As of jQuery 1.7, .delegate() has been superseded by the .on() method. (reference)
$(document).on(events, selector, data, handler); - jQuery 1.7+ - preferred (reference)
It's generally adviced to use on() and it's use is simple and probably preferred way.
The first selector must exist when calling the function and may not be deleted or the event will be gone too (this can be document).
The first parameter is the event (e.g. "click")
The second parameter is the selector of which you want to bind the event on.
Then finally you can add some custom data and a function to the event.
Here's some sample code:
// Make sure the DOM is ready
$(function() {
// Bind the click event to the function
$(document).on("click", "a.class", function(event) {
// Put your code here.
});
});
Late binding is now available by utilizing jQuery's live() event:
$('a.my-links-class').live('click', function() {
// do your link action here
});
Method .live in JQuery 1.9 is deprecated.So now u can do like this:
$("body").on("click", ".classname", function() { ... })
the .live() event was deprecated from verions 1.9 up.
For anyone using later version of Jquery they can use the .on() event, it works pretty much in the same way.
You need to use jQuery's live function, which will bind an event to all elements that match a selector, no matter when they were created.
You can use jQuery 1.3+'s $().live(event, function) function. $("a").live("click", myClickFunc) will bind myClickFunc just like $("a").click(myClickFunc) or $("a").bind("click", myClickFunc), but the events will be bound "live", so elements that are added to the DOM after that function call will also be bound.
You can remove live-bound events with $().die().
For more information on $().live, see the documentation for it.
Another option would be to have a function to bind the elements given a certain context (using the $ selector function's rarely-used second parameter):
function myBindEvents(context) {
$("a", context).click(myClickFunc);
}
and call that whenever you update an element with AJAX:
$("<div>").load("...", "...", function(){myBindEvents(this);});
Hope this helps. :)
In my case I am using js library in that I have element variable and code was like
$(element).click(function(){
//some action
});
but that is not working with my late binding element.
So I finally use core js click event
element.addEventListener('click', function() {
//My some action
}, false);

Categories

Resources