I am using selenium addon as well as jquery in my addon. Due to use of jquery functions with $ being used in selenium throwing function not found error. Removing the Jquery, everything works fine. Using Jquery (ajax call) is must for me. Please suggest how can I make them work together.
One recommended way to solve this kind of conflict is to wrap your javascript code inside a function, and pass jQuery as an argument to this function :
// e.g : turn this code :
$(function(){
$('.my-class').on('click', function(){
$.ajax(...);
});
...
});
// into :
(function($) { // start an anonymous function,
// whose first argument is named '$' ...
$(function(){
$('.my-class').on('click', function(){
$.ajax(...);
});
...
});
}(jQuery)); // and call this function right away,
// passing the jQuery object as first argument
Note that $ is just a shortcut for jQuery :
jQuery('.my-class') and jQuery.ajax(...)
// are exactly the same as :
$('.my-class') and jQuery.ajax(...)
You can also use your own alias :
var $j = jQuery;
If some day you need to mix jQuery with another library which defines a $ variable, you can also use jQuery.noConflict() (example taken from this use case) :
var $j = jQuery.noConflict();
Related
I am using javascript file and jquery.From my javascript file,I am doing like this:
abc.cde.on({
});
which is calling one widget written in jquery.
abc.cde are namespaces in jquery widget file.
Can anyone please tell how abc.cde.on is calling jquery method without using $ sign before abc.cde
Because cde is already an instance of a jQuery object. You can perfectly store the result of a jQuery selection (or a jQuery widget instance) in an object to reuse it after, see example:
var namespace = {
obj: $('div'),
};
//then you can do:
namespace.obj.on('click', function(){
this.style.color = 'red';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>CLICK ME</div>
Because the $ is already used in previous reference... I suspect abc was defined something like this:
var abc = $('#abc')
So the $ is already referenced...
I'm writing a bookmarklet using jQuery. It looks like javascript:document.write('<script src="path/to/loader.js"></script>'), and loader.js does the initializing stuffs:
check_the_environment();
document.head.innerHTML='<meta charset=utf-8>';
document.body.innerHTML='(the webpage)';
var jq=document.createElement('script');
jq.src='path/to/jquery.min.js';
document.head.appendChild(jq);
function load_core() {
if(window.$)
eval('(core js code)');
else
setTimeout(load_core,50);
}
load_core();
The loader loads the core javascript code after the jQuery is available.
But sometimes I get this error in my core code:
$(...).on is not a function
It seems that jQuery was still initializing itself although $ variable is setted.
So, I need to wait for jQuery to be completely initialized before the loader loads the core code. How can I do that?
The traditional way of using $(document).ready(...) is infeasible, as jQuery is being loaded after the webpage is ready.
Here is a minimal Python code to check whether the solution is working:
import cherrypy
mod='''
var htmlroot=document.getElementsByTagName('html')[0];
function load_core() {
if(window.jQuery)
jQuery(function(){
alert($(document).on);
});
else
setTimeout(load_core,10);
}
if(!document.head)
htmlroot.appendChild(document.createElement('head'));
var jquery=document.createElement('script');
jquery.src='http://libs.useso.com/js/jquery/2.1.1/jquery.min.js';
document.head.appendChild(jquery);
load_core();
'''
class Website:
#cherrypy.expose()
def mod(self,_time):
return mod
#cherrypy.expose()
def index(self):
return '''Mod'''
cherrypy.quickstart(Website(),'/');
The right and foolproof way would be:
jQuery(function(){
// code
});
Since jQuery may be loaded in noConflict mode the $ var may not have been initialized.
For the sake of productivity the following can also be used to have access to $ var inside the jQuery scope.
jQuery(function($){
// you can use $ without worrying about conflicts now
});
You can check type of $ as below
if(typeof $ == "function"){
//Jquery loaded
}
below, it says $ sign refers to jQuery. i need help understand how?
jQuery(function($){
// Here `$` refers to jQuery
});
When you pass a function to jQuery like this:
jQuery(function() {
...
});
It's the same as using jQuery's "document ready" handler:
jQuery(document).ready(function() {
...
});
however the argument passed to that function is actually the global jQuery object itself - it's just that most such handlers never use that parameter. Hence the real signature is this:
jQuery(document).ready(function($) {
...
});
so, within that function $ is a local alias to the global jQuery object. The variable name could be anything you wanted, but $ is a popular alias for jQuery, and the default global alias unless you call jQuery.noConflict().
This is described in more detail in the paragraph "Aliasing the jQuery Namespace" at http://api.jquery.com/ready/
That function is a so called allonymous function where jQuery runs that allonymous function with the first parameter this.
So just for understanding it makes something like this:
function jQuery(xx) {
xx(this);
}
Just an example for show you how is it possibile
function externalLibrary(b) {
if(typeof b === 'function') {
b(externalLibrary);
}else {
// other stuff
}
}
var myFunc = function(aliasOfExternalLibrary) {
// here aliasOfExternalLibrary is a reference to externalLibrary
}
externalLibrary( myFunc );
jQuery do the same (in one more complex system)
i was exploring in the last few days how big frameworks works , how they assign their function name and it can't(?) be override , i pretty much know how framework work with anonymous function , for example they do it this way or similar version :
(function(){
var Sizzle = function (){
var x;
};
Sizzle.f = function(){
alert("!");
};
window.Sizzle = Sizzle;
})();
i still don't get few things about those huge frameworks and i hope i can find answer :
how do they assign function name and the name can't be override?
in the code above to call the function i need to write Sizzle.f() to get the function to work , but when i use jquery i don't write Jquery.show() , just show() , how do they vanish the "jquery" from "jquery.show()" function call?
by saying the name can't be override i mean , if i create function with one of the jquery functions names , the jquery function will work.
thanks in advance.
As has been shown for #2, it's really easy for BIG_NAMESPACE.Functions.doStuff to be added to anything you want.
var _ = BIG_NAMESPACE.Functions.doStuff;
_(); // runs BIG_NAMESPACE.Functions.doStuff;
As for #1:
Most libraries DO let their functions be overwritten.
It's the values that are inside of the framework's closure which are preserved, for safety reasons.
So you could do something like:
BIG_NAMESPACE.Functions.doStuff = function StealEverything() {};
(BIG_NAMESPACE.Functions.doStuff === StealEverything) // true;
But doStuff would have NO access to any of the variables hidden inside of the framework's closure.
It would also mean that until the page was reloaded, doStuff would also not work the way you want it to.
HOWEVER, in newer versions of JavaScript (ECMA5-compatible browsers), it WILL be possible to do something like what you're suggesting.
BIG_NAMESPACE = (function () {
var do_stuff = function () { console.log("doin' stuff"); },
functions = {
set doStuff (overwrite) { }
get doStuff () { return do_stuff; }
};
return { Functions : functions };
}());
Then, this will work:
BIG_NAMESPACE.Functions.doStuff(); // "doin' stuff"
BIG_NAMESPACE.Functions.doStuff = function () { console.log("ain't doin' jack"); };
BIG_NAMESPACE.Functions.doStuff(); // "doin' stuff"
However, Frameworks aren't going to use this for a LONG time.
This is not even remotely backwards compatible. Maybe in 2016...
There were defineGetter and defineSetter methods as well, but they aren't a formal part of the JavaScript language. Like innerHTML, they're things that the browser vendors put in, to make life better... ...as such, there's no real guarantee that they're going to be in any/all browsers your users have. Plus, they're deprecated, now that new browsers use the get and set constructs that other languages have.
(function(){
var jqueree = {};
jqueree.someval = 22;
jqueree.somefunc = function(){ alert(this.someval); };
window.jqueree = jqueree;
window.somefunc = function(){ jqueree.somefunc.call(jqueree); };
window.$$$ = jqueree;
})();
// all equivalent
window.somefunc();
window.jqueree.somefunc();
$$$.somefunc();
somefunc();
Answering your Questions
At the top of jQuery you'll see: var jQuery = (function() {, which creates the local function (its incomplete; the }); occurs elsewhere).
At the very end of jQuery you'll notice the following, which is how it attaches it to the global namespace:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
I have never seen a jQuery function called without referencing the jQuery object. I think you always need to use jQuery.show() or $.show(); however maybe you're saying you don't have to call window.jQuery.show(), which you are permitted to drop the window, since that is the default.
Using your example
(function(){
/* This is where Sizzle is defined locally, but not exposed globally */
var Sizzle = function (){
var x;
};
/* If you put "window.f = Sizzle.f = function(){" then you could *
* call f() w/o typing Sizzle.f() */
Sizzle.f = function(){
alert("!");
};
/* The following line is what makes it so you can use Sizzle elsewhere *
* on your page (it exposes it globally here) */
window.Sizzle = Sizzle;
})();
use function _name_() {} and the name is static
the simply use var $ = jQuery; to create an alias.
jQuery works this way:
Supposed you have this jQuery code:
$("#title").show();
You have three elements to that line.
$ is a javascript function
"#title" is an argument to that function
.show() is a method call
Here's how it works.
Javascript executes the function named $ and passed it an argument of "#title".
That function does it's business, finds the #title object in the DOM, creates a jQuery object, puts that DOM element into the array in the jQuery object and returns the jQuery object.
The Javascript execution engine then takes the return value from that function call (which is now a jQuery object) and looks for and executes the .show() method on that object.
The .show() method then looks at the array of DOM elements in the jQuery object and does the show operation for each DOM element.
In answer to your question, there is no .show() all by itself. It's a method on a jQuery object and, in this example, that jQuery object is returned from the $("#title") function call.
In this video there is a snippet of code that goes something like this:
if (jQuery) {jQuery(function() {
// ...
})}
I've never seen the jQuery() function before (then again, I'm not a savvy jQuery user), what does it do? Does it ship by default with jQuery or is it specific to IxEdit? Since the usual $(window).load() snippet is missing and the code is somewhat similar I'm guessing it's a shortcut / alias to:
$(window).load(function() {
// ...
)}
Am I right? Also what is that jQuery variable? What does it hold? And why is he checking it?
$() is an alias for jQuery(), defined as:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
http://code.jquery.com/jquery-1.4.js
there is a special case defined when $() or jQuery() is called with the first argument being a function:
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
sometimes $ can conflict with other libraries (like prototype) that define the same function, so if you call
jQuery.noConflict();
it will remove the $ alias, setting it back to the original value found, essentially:
window.$ = _$;
jQuery(function()
is same as
$(document).ready(function()
if(jQuery)
is a check whether the jQuery.js file has been loaded or not.
There is another way to check this
if (typeof jQuery == 'undefined')
{
//jQuery has not been loaded
}
The $ function is an alias for the jQuery function. So, they are the same.
If you use jQuery in noConflict mode, there is only jQuery() function
I think it is the same that using $() but you use jQuery() for compatibility with other libs which also use $()
jQuery can be a variable that store a function. Guess that if is to check if it is not undefined or something like that