Conflict in ES6 String Interpolation and jQuery $ - javascript

STUPID QUESTION : DON'T BOTHER
I am newbie in ES6 and following this guide here to get started. I looked at the following code and been thinking since then.
function printCoord(x, y) {
console.log(`(${x}, ${y})`);
}
So we use ${VARIABLE} to get it's value as string. Now if I were to use jQuery as $ would it conflict with the above code? or jQuery would just ignore anything in between `` ?
Would we be able to do something like...
console.log(`(${ $('.selector').text() })`);
Would it require me to use jQuery as jQuery everywhere?

I made a jsfiddle. (Added jQuery, babel as language)
http://jsfiddle.net/kamikazefish/hd1Le21z/
<div class="selector">This is the text in the selector</div>
console.log(`(${ $('.selector').text() })`);
alert(`(${ $('.selector').text() })`);
Seems like it works.

Related

Babel plugin - How to transform JSX without react

I have wrote my own module which takes a JSX string as a parameter and turns it into a javascript object, so I call it like so:
import parser from 'own-parser'
console.log(parser("<h1>Hello world</h1>"))
This works, but what I actually need is to transform the JSX into the object when it compiles, so I could write it like a normal JSX expression:
var jsx = <h1>Hello World</h1>
and get the result from my function as output like so:
var jsx = {element: 'h1', children:[/*...*/]}
I undrestand there are many babel plugins like "babel-plugin-transform-jsx" which can accomplish this, but I want to learn about babel plugins and how they work so I can make my own.
I've tried to analize the code of the plugin mentioned above but still cannot understand how things work, for example, how does the plugin know that he is working with a JSXElement?
The only thing I am trying to do is to extract that JSX, put it inside my function and transform it into the function's return
How can I do that? Thanks
I've figured it out, turns out you can get the code of a node with path.toString(), for example to declare a visitor like that:
JSXElement(path, state) {
if (path.parentPath.type != "JSXElement") {
const parsed = parser(path.toString())
path.replaceWithSourceString(JSON.stringify(parsed))
}
}
This is not present in the babel plugin handbook, I suppose this is a bad practice, but anyways it is a quick solution in case anyone wondered

What does the command that start with '$.' do/mean in Javascript? This is NOT '$' selector to select an element [duplicate]

In the following JavaScript code there is a dollar ($) sign. What does it mean?
$(window).bind('load', function() {
$('img.protect').protectImage();
});
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).
There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier. JavaScript allows upper- and lower-case letters (in a wide variety of scripts, not just English), numbers (but not at the first character), $, _, and others.¹
Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.
¹ For the first character of an identifier, JavaScript allows "...any Unicode code point with the Unicode property “ID_Start”..." plus $ and _; details in the specification. For subsequent characters in an identifier, it allows anything with ID_Continue (which includes _) and $ (and a couple of control characters for historical compatibility).
From another answer:
A little history
Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.
jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
The $() is the shorthand version of jQuery() used in the jQuery Library.
In addition to the above answers, $ has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict().
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
Ref:https://api.jquery.com/jquery.noconflict/
From the jQuery documentation describing the jQuery Core Object:
Many developers prefix a $ to the name of variables that contain jQuery
objects in order to help differentiate. There is nothing magic about
this practice – it just helps some people keep track of what different
variables contain.
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)

$ae. javascript notation

I am starting to learn jQuery. Looking though the MVC3 project that makes use of Awesome MVC Html helpers, I have stumbled upon a javasript code that I don't know how to understand yet:
$ae.autocomplete('Requestor'
What is $ae is calling a jQuery autocomplete on in this case? ae isn't an element, so this isn't an id or class selector.
P.S. And while you are at it, please let me know what $. as in $.getJSON calls getJSON on?
Assuming that there isn't a typo, $ae is a variable. Since $ is just a javascript function you can assign the result of it to a variable, $ae = $("#myid"). While I don't know that $ae is definitely the result of that, the naming convention ($ at the beginning) makes me suspect that it is.
In jQuery, the $ is a convenient alias for the jQuery object. So $.getJSON() is calling the getJSON() method of the jQuery object. This is pretty confusing at first, but once you get used to it it's nice and concise.
It seems like common practice in jQuery development to use a $ to prefix variables that result from selecting things with jQuery, like this:
var $myList = $('.list-item');
The $ is a legal character to use in variable names, so I guess it's a reminder that the object contains a jQuery wrapped set. It's a good idea to assign the results of your selections to variables if you'll use the selected items again; otherwise you're wasting resources.
In your example, the $ae is the equivalent of something like this:
$('#my-input').autocomplete('Requestor ...

Javascript/jQuery Regular Expression code issue

I am working with jqDock on a DotNetNuke project. I ran jQuery.noConflict() and went through the jqDock.js file and changed all '$' to 'jQuery' (though I don't think it was necessary).
In this little bit of code I have an issue:
altImage : function(){
var alt = jQuery(this).attr('alt');
return (alt && alt.match(/\.(gif|jpg|jpeg|png)$/i)) ? alt : false;
} //end function altImage()
At the end of the regular expression there is a chunk that says $/i, My find/replace set this to jQuery. It broke the program. Is this because that '$' symbol isn't associated with jQuery there? Is it part of the Regular Expression? If so...what exactly is it saying?
The $ sign in this case is used as part of the regular expression, not as a call to jQuery, so that's why you had problems. It matches the end of the string that the regular expression is being performed on.
The $ matches the end of the string so it's not jQuery related here.
Some reading on regexp can be found here
The usual style to writing jQuery plugins would mean that one would not need to replace $ throughout the plugin. Most plugins are written such that the plugin code is surrounde by a self-invoking anonymous function that passes in jQuery for a parameter $ such that $ refers to the jQuery object inside of that function. Like so
(function($) {
// I can happily use $ here to refer to the jQuery object
$.fn.myFunction ....
})(jQuery);
So be careful when doing a naive find/replace.
As others have already mentioned, in the context of a regular expression, $ is used to match the end of the string.
Finally, when using $.noConflict(), you can assign the jQuery object to a different alias and use that alias throughout the subsequent code. For example
var $j = $.noConflict();
// can use $j alias for jquery now
$j(document).ready(function($) {
// can use $j or $ for jQuery object inside this function as the
// jQuery object is passed in
});
Be really careful when doing such huge find/replaces in your code. You changed the $ sign used in a regular expression to a jQuery expression, which is wrong. Every replace of this magnitude (replace everything in a document by other string) should be done wisely.
Read noConflict documentation to see which options do you have when using it - there's even one that let's you still use $ for jQuery.

How to make custom, no editing need, bulletproof jquery's noconflict version?

in my job i always have to use jquery with prototype can i make any custom jquery with library file like once i will add in head and then no need to change anything in any code.
is it possible?
I don't want to change anything in an code $ to jQuery.
from http://www.cssnewbie.com/runing-jquery-with-other-frameworks-via-noconflict/
Keeping it Short
The noConflict mode does have one other bit of functionality that I’ve found useful in some of my projects: you can select a different variable to use instead of the standard “jQuery”. The usage looks like this:
var $j = jQuery.noConflict();
Now in addition to using the default jQuery() notation, I can also use the shorter $j() notation. This allows me to avoid running into problems with other frameworks, while still enjoying almost the same conciseness in my code.
This just begs the question why dont you simply implement all your stuff in Prototype then - or implement everything in jQuery. Overall they both have the same capabilities.
However to directly answer your question - ther isnt really a way to make a custom build of jQuery. But you could simply put your noConflict call immediately following your inclusion of the jQuery library.
Then for your stuff you can simply wrap it all in
(function($){
// your jQuery code here... Can be used with $ as normal.
})(jQuery);
within that function youll be able to use $ as the alias - outside of it you would need to use jQuery. The only gotcha here is that if you want a variable defined inside here to be global youll need to make it that way manually as everything within this will be scoped to the function. You can do this like so:
(function($){
window.myGlobalVar = 'This is a global variable';
})(jQuery);
The best thing is often to wrap the $ in a private scope:
(function($) {
// jQuery stuff
})(jQuery)
You can also call the jQuery.noConflict() function before the wrap: http://api.jquery.com/jQuery.noConflict/
Another clean option is chaining the noConflict() into a domReady callback:
jQuery.noConflict()(function($){
// code using jQuery or $
});
console.log(typeof $ === 'undefined') // prints true
To address your question of whether you can have an "include-once" file, yes, you could do something similar to:
/* MyLibLoader.js */
document.write("<script type='text/javascript' src='prototype.js'></script>");
document.write("<script type='text/javascript' src='jquery.js'></script>");
window.$j = jQuery.noConflict();
And then in HTML
<head>
<script type='text/javascript' src='MyLibLoader.js'></script>
</head>
But this approach assumes you're happy to change your jQuery usage to $j

Categories