I couldn't find the syntax something like this anywhere:
var mz = jQuery.noConflict();
mz('#zoom01, .cloud-zoom-gallery').CloudZoom();
This means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery').CloudZoom();
And something like this:
$(window)[this.off?'off':'on']("scroll", fixDiv );
So, I'm wondering about the syntax something like of these:
jQuery.noConflict()(syntax) and $(window)[syntax](syntax) and I also think there might be something like this $(selector){syntax}
Can anyone elaborate of those syntax?
The best place to start is the documentation
$.noConflict()
Many JavaScript libraries use $ as a function or variable name, just
as jQuery does. In jQuery's case, $ is just an alias for jQuery, so
all functionality is available without using $. If you need to use
another JavaScript library alongside jQuery, return control of $ back
to the other library with a call to $.noConflict(). Old references of
$ are saved during jQuery initialization; noConflict() simply restores
them.
In other words, noConflict() sets a variable to equal jQuery, so this
var mz = jQuery.noConflict();
mz('#zoom01, .cloud-zoom-gallery').CloudZoom();
is the same as
$('#zoom01, .cloud-zoom-gallery').CloudZoom();
or
jQuery('#zoom01, .cloud-zoom-gallery').CloudZoom();
noConflict() does not directly take selectors, it's just a function that sets jQuery in a certain scope to a variable so you can have multiple versions of jQuery (which you shouldn't) or use other libraries that also uses $ for something, it does not mirror the selector engine or anything else, even if it might seem so at first glance, it simply returns an instance of jQuery
In javascript there is dot notation and bracket notation, so an object can be accessed as
object.propertyName
or
object['propertyName']
as everything in javascript is an object, even jQuery methods, they can be accessed as
$('#element').fadeIn(200);
or
$('#element')['fadeIn'](200);
it's the same thing, so doing
$(window)['on']("scroll", fixDiv );
is the same as
$(window).on("scroll", fixDiv );
the advantage of using brackets is that they can contain any string, even variables, or in this case ternary statements, or the returned result of a function
var event = 'on';
$(window)[event]("scroll", fixDiv );
or
var event = this.off ? 'off' : 'on';
$(window)[event]("scroll", fixDiv );
that one also uses this, which in the global scope would be window, and it's the same as
$(window)[this.off ? 'off' : 'on']("scroll", fixDiv );
The ternary statement itself is just a fancy condition, and this
var event;
if (this.off) {
event = 'off';
} else {
event = 'on';
}
is exactly the same as
var event = this.off ? 'off' : 'on';
Added for the edited question :
jQuery() or $() is a function, something we can tell from the parenthesis, so it's something like
function jQuery(arguments) {
// do something
}
which can be called as
jQuery(some_arguments);
and as var $ = jQuery one can also do $();
Now that we know it's a function, it makes sense that we can do
$('#element_id')
and internally jQuery checks what kind of argument we passed, it sees that is's a string, and it's starting with #, so it's an ID, and then jQuery can do document.getElementById() and get that DOM element, and at the same it wraps that element in a new array-like object, usually referred to as a jQuery object.
We can also pass in a DOM node, array, object or anything else, and jQuery tries to figure out what it is, and wrap in that jQuery object for us to use with other jQuery methods, so this :
$({x:10, y:20})
is the same as
var obj = {x:10, y:20};
$(obj)
and its turned into one of those jQuery objects with the properties x and y. Passing in an object like this means we can chain on methods, and those properties are available in the methods.
$({x:10, y:20}).animate({x:50}, 1000);
And that's basically how it works, simplified a lot.
As for passing objects to methods, that's a very common way to pass arguments.
To see how it works, it's easiest to create a method:
$.fn.doStuff = function(argument) {
this.css(argument);
}
inside a jQuery plugin, this is the jQuery object, and we can now use the mothod above that does nothing more than pass the arguments to jQuery's css().
We know we can pass an object to css() like this :
$('#element').css({left: '10px', top: '20px'});
so using our plugin we can do the same
var obj = {left: '10px', top: '20px'};
$('#element').doStuff(obj);
and it ends up doing exactly the same thing. Of course, we could do anything with the object :
$.fn.doStuff = function(args) {
if ( typeof args == 'string' ) {
alert(args); // if it's a string, just alert it
} else if ( typeof args == 'object' ) {
for ( var key in args ) { // if it's an object, iterate
this[0].style[key] = args[key]; // and do something
}
}
}
foo['bar'] syntax is to get the property bar from object foo.
foo() is to execute the function foo.
And you can combine these as you wish.
jQuery.noConflict() returns a function so you could execute the result by jQuery.noConflict()(syntax).
$(window) returns an object so you could get a property from it by $(window)[syntax], and if the property is a function, then you could execute it by $(window)[syntax](syntax).
This is just javascript syntax.
person.name is exactly the same as person["name"]
The same happens with methods
$(window).on(...) is exactly the same as $(window)["on"](...)
One cool thing about the second way is that you can make the member name variable, for example:
So doing:
var windowMethod = "on";
$(window)[windowMethod](...)
is the same as
$(window)["on"](...)
And you can have an expression inside the brackets, so this:
$(window)[this.off ? 'off' : 'on']("scroll", fixDiv );
would be exactly the same as doing this:
if(this.off)
$(window).off("scroll", fixDiv);
else
$(window).on("scroll", fixDiv);
But the former is shorter.
Hope this helps. Cheers
PS: The jQuery.noConflict()(syntax) is straightforward, .noConflict() just returns a function and then we append some other parens to call it just as any other function.
Related
I'm writing a utility file and I've gotten some examples from online and this a form of writing the utility I've come across:
$.util = $.extend($.util || {}, {
//functions here...
});
and so I think I understand what it's doing. It allows me to call $.util.function() somewhere else, however when I remove the . in front of the $ the code breaks. What does this notation mean? What's the difference between $. and $?
$.util = something means "assign something to property util of object $".
$util = something means "assign something to variable $util"
Similarly, $.extend is "get value of property extend of object $" (which is a function in this exact scenario) and $extend is "get value of variable $extend"
If you're using jQuery, $ is just a variable contaning the jQuery object. So by writing $., you're essentially accessing jQuery properties and functions. Instead of $, you could also write jQuery and it should work the same way.
There's no special meaning to the $ character in JavaScript other than that. It acts like any other character, so $util is just a variable name.
jQuery is an object that is assigned to both jQuery and $ on the window
It has methods that act on collections of elements eg $('.some-element').someMethod() and static methods that are just attached to the jQuery object but don't modify a collection, They are just normal function attached to the jQuery object to prevent exposing too many functions to the global context.
$. - allows you to proceed to $ (jQuery) object property or method directly
$ - usually used as shortcut for invoking jQuery object
Whilst prefixing anything with $ won't make it jQueryable bec. this character can be used in variable name along with others (e.g. what is not applicable for PHP).
Consider jQuery as a big class woth a lot of static functions and constructs.
The right way for calling any of its functions should be jQuery.someFunc() for static functions and var obj = jQuery('css selectors') for creating an object for HTML objects and then executing functions on that object.
Now for easier coding, jQuery added $ as an alias for jQuery. It's nothing more than an alias.
Try this code:
<script type="text/javascript">
document.write('(jQuery === $) is ' + (jQuery === $) + '<br />');
document.write('typeof(jQuery) = ' + typeof(jQuery) + '<br />');
</script>
You will see:
(jQuery === $) is true
typeof(jQuery) = function
So jQuery is a function with a bunch of extra properties and functions attached to it.
If you're coming from a strongly-typed language background, the concept of attaching properties and methods to a function might seem strange, but you can do it in javascript.
I use the following jQuery structure a lot so I want to write it shorter (EDIT: the addClass and removeClass are EXAMPLE functions, I want to know a general ternary way to apply different functions to an object, so do not tell me about toggleClass which doesn't even work like below code):
if(something){
obj.addClass('class');
}else{
obj.removeClass('class');
}
I want to write it in a single line, so I would like to know how to apply jQuery functions conditionally. Something like the following using a ternary operator, only this doesn't work yet:
$[something?'addClass':'removeClass'].apply(obj,'class');
This is easily done in regular javascript but how do I structure the above correctly to work in jQuery?
EDIT: I am not searching for two separate calls such as:
something ? obj.addClass('class') : obj.removeClass('class');
Just put it to equal the something, if it is true it will triger otherwise wont triger.
$( this ).toggleClass( "class" ); = something;
What about writing a helper function?
function ternary(object, condition, a, b) {
var method = condition ? $.fn[a] : $.fn[b];
var args = arguments.slice(4);
return method.apply(object, parameters, args);
}
Then you could do
ternary(obj, something, 'addClass', 'removeClass', 'my-class-name');
ternary(obj2, somethingElse, 'slideUp', 'slideDown');
I'm having trouble understanding a type of jQuery selection, and I hope someone can explain it to me in clear terms.
It's taken from this Stack Overflow question.
Basically, it has the common jQuery: $( selector ).
But inside that it has $({ y: iFrameScrollY }).
I've never seen this before. What does it mean to have { ... } and someVal: anotherVal inside the brackets?
Also, please recommend a different title for this question, to make it easier for others to find it.
What $({ y: iFrameScrollY }) does is wrap a jQuery selector object around the JavaScript object { y: iFrameScrollY }.
The JavaScript object is declared { y: iFrameScrollY }, meaning it contains a property named y set to the value of iFrameScrollY.
By wrapping the object into a jQuery object one can avail of executing jQuery methods against the wrapped object.
See this documentation for more details.
Wrapping plain JavaScript object inside jQuery object you can use few jQuery methods including: .data(),.prop(),.bind(), .unbind(), .trigger() and .triggerHandler().
Here is an example taken from jQuery.com:
// define a plain object
var foo = {foo:'bar', hello:'world'};
// wrap this with jQuery
var $foo = $(foo);
// test accessing property values
var test1 = $foo.prop('foo'); // bar
// test setting property values
$foo.prop('foo', 'foobar');
var test2 = $foo.prop('foo'); // foobar
// test using .data() as summarized above
$foo.data('keyName', 'someValue');
console.log($foo); // will now contain a jQuery{randomNumber} property
// test binding an event name and triggering
$foo.bind('eventName', function (){
console.log('eventName was called');
});
$foo.trigger('eventName'); // logs 'eventName was called'
That's a call to the jQuery() function, which is overloaded to do a lot of different things, depending on the arguments being passed.
The {someVal : anotherVal} is a JavaScript object with a property named someVal with a value equal to the value of the anotherVal variable.
If you join those two pieces of information together, and look at the linked page, you'll see this:
jQuery( object )
object A plain object to wrap in a jQuery object.
I am using the following function closure in a jqgrid (a jquery grid) to retain changes in edits when paging in a variable called 'retainedChanges'- does this look ok; Im i breaking any good practices in javascript;
the code works alright just want to make sure I dont introduce features that can break in the future
(function($){
var retainedChanges;
retainedChanges = new Array();
$.retainChangesOnPaging = function(){
var changedCells = $('#grid').jqGrid('getChangedCells');
// loop over changedCells array, removing duplicates if you want to...
return retainedChanges.push(/* this is inside the loop; push current value to array*/);
....
}
$.getRetainedChanges = function(){
return retainedChanges;
}
})(jQuery);
This works fine, although you should probably accept jQuery as an argument:
(function($){
This way, even if the $ symbol is being used for something else outside of your closure, it won't effect your code inside the closure.
2 more things:
1) You should declare and assign you variable together, and use [] instead of new Array().
2) You're missing a $ symbol here: ('#grid').
For a full rundown, look at this:
(function($){
var retainedChanges = [];
$.retainChangesOnPaging = function(){
var changedCells = $('#grid').jqGrid('getChangedCells');
// loop over changedCells array, removing duplicates if you want to...
return retainedChanges.push(/* this is inside the loop; push current value to array*/);
....
}
$.getRetainedChanges = function(){
return retainedChanges;
}
})(jQuery);
You are passing jQuery into a function that has no arguments and never uses the jQuery object passed in. You may have meant:
(function($){
Other than that it looks fine.
There are several things you could improve:
1) You pass jQuery to the function, but do not use it (you use global object $, if it is defined). Modify your code to accept one parameter, named $:
(function($){
2) You can shorten retainedChanges declaration:
var retainedChanges = new Array();
3) If you are trying to write jQuery plugin, then follow the following tutorial: jQuery: Plugins/Authoring
If not, then maybe use different global object than jQuery?
Yeah so I've been messing around with javascript a while but only recently got into stuff like object orientation, prototyping and using objects for all functions and vars.
But, many frameworks like jQuery or extJS have something I have yet to grasp, you can define an object by using a built in function for searching the dom, example:
var a = $('#mydiv');
and then you can do a.click(function);
So my question is, how can I create a "framework" of sorts where I can write code in that style, like example:
var mydiv = document.querySelector('mydiv');
mydiv.neph(args,args);
So I have my object defined, in this case it's a dom element or whatever, now I pass it to my function "neph" with arguments, I want to create code that allows me to do this. But since mydiv does not have any function, it only has in this case the dom element right so mydiv.neph does not exist, but in jquery you can define whatever var and .click or .mouseover or whatever does exists within the object as functions? Confusion ensues! :D
Ok sorry if this is a retarded question btw =P
jQuery and other libraries define a function called $ that takes several optional parameters. The object returned by calling $ is not a DOM element, but a jQuery object wrapping a DOM element up with a set of convenient functions.
You can do something similar yourself:
<html>
<body>
<input id="derp" type="text"/>
<script type="text/javascript">
function $(id)
{
return new myLibrary(id);
};
function myLibrary(id)
{
this.el = document.getElementById(id);
};
myLibrary.prototype.help = function()
{
alert(this.el.id);
return this;
};
// Woah! My own fake jquery!
$("derp").help();
</script>
</body>
</html>
jQuery is far more sophisticated, of course. For example, it will use apply and call to set this correctly in calls like jQuery.each.
You need to create a Prototype in javascript. This is what allows you to add a function to an object that's already defined (i.e. the .click() function that you gave as an example).
You can have a look at the jQuery code, it's open source. It's not the simplest code, but you can still see how it works and how they do it.
Mike's comment is a good answer: Look at jquery or Ext-Core's sources.
Maybe what you're missing is that, in jquery, for instance $() returns a jquery object, which wraps the plain vanilla DOM node, providing extended functionality.
In jQuery, $ is just an alias to the jQuery object. So when you call $('#mydiv'); you're really calling a function like jQuery('#mydiv'); So part of what makes jQuery so cool is that every the $() function returns this, which means when you call the $() you're getting a handle to the jQuery object and all of the methods it has on it. That is what allows you to do something like this:
var a = $('#mydiv');
a.click(function() { // etc etc etc });
So to pull off your example:
var mydiv = document.querySelector('mydiv');
mydiv.neph(args,args);
You'd have to create an object that has a function called neph on it and return that object in the context of mydiv when you call querySelector.
var myFramework = function() {
this.context = undefined;
this.neph = function(arg, args) {
console.log(arg, args);
}
};
var myCuteFunction = function(element) {
var f = new myFramework();
f.context = element;
return f;
}
// ...
var x = myCuteFunction('#mydiv');
x.neph(arg, args);
Since nobody has really answered about Ext, you can easily extend the element wrapper prototype:
Ext.override(Ext.Element, {
myMethod: function(a, b){
console.log(a, b, this);
}
});
"this" will refer to the Ext.Element object.