What does the jQuery method $.on return?
Example:
$(document).on("CustomEvent", CustomFunction);
What does the jQuery method $.on return?
$(document).on(...) returns the jQuery object created by $(document). This makes it chainable as in:
$(document).on("click", clickHandler).on("hover", hoverHandler);
In fact all jQuery methods that don't have a specific value to return will return the jQuery object so they can be chainable in this fashion.
Another commonly used example:
$("#target").fadeIn(2000).delay(5000).fadeOut(2000);
But, a method that has a specific value to return such as .prop() or .attr() will return that specific value:
var isChecked = $("#myCheckbox").prop("checked");
var imgSrc = $("#myImg").attr("src");
The return value for any jQuery API is listed in the documentation (here's a screen shot from the doc page for .on():
If you want to prevent an event handler from getting called again, you can either use .one() which will only trigger the event once or you can use .off(...) to remove the event handler as desired or you can use some sort of flag in your own code to tell the event handler whether it should do its work or not.
The cleanest architectural solution to preventing repeat calls to something triggered by .load() is to move the event handler setup code to a different area of your Javascript so it is not loaded again by .load() and is only loaded once by the parent page. That way it only gets called once. Exactly how to do that depends upon the specific circumstances of your design which you have not disclosed so we can't advise more specifically than that.
using jquery .load causing some repeating actions in page. if i am not wrong, you have to call your callback function inside "promise"
example
$(document).on("click", ".someClass", function () {
//do something
}).promise().done(function() {
//your callback function
});
});
Related
This is my js file content:
window.onload = function() {
obj = document.getElementById("_accountwebsite_id");
Event.observe(obj, 'change', function () {
alert('hi');
});
}
I want to fire the on change event for my dropdown: _accountwebsite_id . The prototype library it is loaded before this file. I got no errors in the console. Where am i wrong ? thx
You're doing a lot of extra work here that Prototype does for you. First off, setting the document's onload method not only is really old-school, it also will clobber any previously set observer on that event.
$(document).observe('dom:loaded', function( ... ){...});
...is the modern way to register one (or more) event listeners to the document load event.
Next, you're using getElementById here, which will work, but does not return a Prototype-extended object in some browsers.
$('element-id');
...will both get the element reference and extend it if your browser failed to respect every aspect of prototypal inheritance.
Finally, this whole thing can be made both simpler and more bulletproof by using a deferred observer. Imagine if your interface DOM was updated by Ajax -- that would make your observer miss the events fired by this select element, because it was not referring to the same (===) element, even if the ID matched.
$(document).on('change', '#_accountwebsite_id', function(evt, elm){
alert(elm.inspect());
});
This observer will respond to any change event on an element with the correct ID, even if it was added after the observer was registered with the document.
We have started using jquery load in our site to load contents into a div rather than re-loading whole page. However in the complete function we have a method that re-applies various bindings. Is it possible to provide load method with a default complete function? So developers don't have to specify it in the jquery load complete function.
As we currently are providing a lot of duplicate complete functions
E.g.
$('#Target').load(callBackRedirect, function () {
ApplyBindings('#Target');
});
These bindings can't be applied using on and need to be re-applied on page loads. We also do some other work that we want to do on every page load.
The answer is no.
You need the callback because that's what the method calls when the request is done.
This works with on method to, you might be doing something wrong out there in the code.
You could create a helper function for this.
function loadSomething(targetElement, uri,callback) {
targetElement.load(uri, callback);
}
loadSomething(
$('myElement'),
'mylink.com/content',
function() {
applyBindings($(this));
}
)
Yes. Check out the list of Global AJAX Event Handlers.
e.g.
$(document).ajaxComplete(function() {
alert('Triggered ajaxComplete handler.');
});
That said, you shouldn't need to reapply your bindings after an AJAX call. If you need to do this, you're probably doing something wrong. Check out jQuery.on, which explains how to bind to content which is added dynamically.
Try $.ajaxSetup:
$.ajaxSetup({
complete: function() {
ApplyBindings('#target');
}
});
EDIT
You could also make a named function like:
var ajaxApplyBindings = function() {
ApplyBindings('#Target');
// anything else...
};
And then pass it to load:
$('#Target').load(callBackRedirect, ajaxApplyBindings);
I've noticed that the call to the createJSAPI method in my plugin is only called after I somehow try to interact with the actual DOM element.
Is there a way to make it happen before any javascript interaction is happening?
In the documentation for getRootJSAPI it states:
It is not recommended to call this from the constructor or before
setHost is called, as many JSAPI objects need the BrowserHost and a
weak_ptr to the Plugin class to function correctly
So when is it appropriate to call this method? in onPluginReady or onWindowAttached?
Thanks.
Edit
This is my createJSAPI code:
FB::JSAPIPtr plugin::createJSAPI()
{
this->jsApi = JSApiPtr(new pluginAPI(FB::ptr_cast<plugin>(shared_from_this()), m_host));
return this->jsApi;
}
And this is the onPluginReady code:
void plugin::onPluginReady()
{
this->getRootJSAPI();
this->jsApi->fireMyEvent(this->myId);
}
and the event isn't fired, though this does:
bool plugin::onMouseDown(FB::MouseDownEvent *evt, FB::PluginWindow *)
{
this->jsApi->fireMyEvent(this->myId);
return false;
}
Why is that?
As for the build in onload mechanism, I need my own, since I need to pass some parameters to that fired event.
Thanks.
You can call this method during or after onPluginReady -- that's one of the main purposes of the function.
EDIT:
To answer your further question, onPluginReady is likely to be called before your onLoad callback from the param tag gets called; that means your event handlers aren't attached yet. That's the reason that FireBreath provides the onload param callback -- it gives you a place to attach event handlers and find out that things are loaded.
I'm trying to understand what the differences are (if any) between these 2 ways of calling JavaScript/jQuery functions.
Method 1, in document.ready():
$('body').on('click', 'a.popup', popup);
then
function popup() {
$(this) // do something
}
Method 2, in document.ready():
popup();
then
function popup() {
$("a.popup").click(function (e) {
// do something here
});
}
All advice appreciated.
In method 2, the popup function is likely to be called only once, otherwise you attach the same function onclick several times, which propably is not what you want.
Therefore there is no great benefit in writing the popup function's body elsewhere than directly in document.ready().
Advantage of method 1 is if you want to attach the same function to various events and/or various elements, e.g. onclick, onmousemove etc. This way you won't have to write the function's body twice.
In short, i don't see benefits in method 2, whereas i see some in method 1.
I'm not quite sure, but I think you're asking what the difference between calling the jQuery .on() method and the jQuery .click() method, right?
As in:
$someEl.on('click', someFunc);
// or
$someEl.click(someFunc);
Like this, both are pretty much equivalent. However with the .on() method you have the opportunity to introduce namespacing (explained in the first link) to your element's events. Like so:
$someEl.on('click.do1', someFunc1);
$someEl.on('click.do2', someFunc2);
So if in a later progress you want to remove or trigger only one of your callback functions (someFunc1, someFunc2), you'll be able to do so by calling:
$someEl.off('click.do1');
$someEl.trigger('click.do2');
Hope this helps
Is there a way to tell the browser to run an addtional java script function on an event such as 'window.resize' instead of overwriting what is already there?
Using jquery's
$(window).resize(<something>);
Seems to replace what is already there. Is there a way to tell it to do something in addition?
Is this a poor design / wrong way to do it?
I wouldn't think that jQuery would break what's there, but you could wrap the functions in a single function:
// if a function already exists...
if( window.onresize ) {
var prev_func = window.onresize; // cache the old function
window.onresize = function( event ) { // new function for resize
prev_func.call( window, event ); // call the old one, setting the
// context (for "strict mode") and
// passing on the event object
// call your code or function
};
}
EDIT: Fixed it to use onresize instead of resize.
EDIT2: Missed one! Fixed.
If you're using jQuery to bind all event handlers, then you're not breaking anything. jQuery supports multiple handlers for same event.
But if other code (not using jQuery) binds to the event, then you'll overwrite handler with your statement. The solution will be: always use jQuery for event binding or try to save old handler (see patrick dw's answer).
See element.addEventListener (element.attachEvent in IE 8 and under):
// Standards
if (window.addEventListener){
window.addEventListener("resize", callOnResize, false);
// IE 8 and under
} else if (window.attachEvent){
window.attachEvent('resize', callOnResize);
}
function callOnResize() {
console.log("resized");
}
Keep in mind this is pure JavaScript—jQuery (and pretty much any big JS library) has a method to handle creating standards and IE handlers without you needing to write each. Still, it's good to know what's happening behind the scenes.
jQuery and all other frameworks supporting custom events attach a function to the event of the elem (or observe it). That function then triggers all functions that have been bound (using bind) for a specific event type.
domelement.addEventListener does not override an other function and your function added can't be removed by other (bad) javascript, except when it would know the exact footprint of your function.