jQuery or javascript syntax that I don't understand - javascript

I´m reading a Polymer tutorial but I don't understand some code lines, like this:
postTask: function(e) { // Add a new task
var tsk = this.$.tTask.value;
var usr = this.$.tUser.value;
...
In this code block I don't understand the selector this.$.tTask.value, is another way to select in jQuery syntax?

I know nothing about Polymer, so I can only answer this question based on javascript syntax.
This code doesn't necessarily involve jQuery.
In javascript, the $ symbol is just an identifier.
When you include jQuery, it happens to assign the jQuery function to window.$. But jQuery does not 'own' the $ symbol.
Here, a variable with the identifier of $ has been assigned to the current object. For example, some code somewhere could be calling
this.$ = {
tTask: { value: "TaskValue" },
tUser: { value: "UserValue" }
};

Related

What is .$ means for in CKEditor?

I am currently looking into some plugins of CKEditor. Here is the code I encountered:
var dummyElement = editor.document.createElement('span');
var obj = dummyElement.$;
The plugin comes from here.
What is .$ means for in this context? Does it also supported in jQuery or other libraries?
$ is a perfectly valid variable or property name so without digging into the source code (or docs) and seeing what is assigned there is no way to know from your snippet alone what it is used for
As seen here you can do anything with it
var obj ={ $: 'foo'}
alert(obj.$);// "foo"

jQuery DOM Insertion with variable insert-method

My code uses a jQuery plugin that inserts some HTML code.
I have the option to change the inserting method, by setting them via variable.
The variable is called:
var options = {insert: 'append'};
I don't want to do that with an if condition, like that:
if(options.insert === 'append') {
$('#foobar').append(htmlcode);
}else if (options.insert === 'prepend'){
$('#foobar').prepend(htmlcode);
... and so on.
Is there any solution to insert the html code with a given varibale method?
Because the jQuery construct is an object, you can use bracket notation to access functions. Try this:
$('#foobar')[options.insert](htmlcode);
So long as options.insert matches the name of a function, it'll work.
Example fiddle

Determine if a string is a valid jQuery selector?

Does jQuery have a method to determine if an argument passed to function is a selector?
I am making a template for some jQuery plugins and I need to be able to check if the argument passed in is a jQuery selector. I want to allow for other data types and perform different methods based on what data type is passed. Detecting data types is easy, but selectors are just a string and can be constructed is many different ways.
My goal is to create plugins that are forgiving with what you pass in for the arguments and makes educated decisions about what to do with it. Take the jQuery UI plugins for example, in some plugins, lets say we pass a callback function in the argument place holder that is for a number for a speed, it still takes the callback and runs it and uses the default for speed. That's the kind of functionality I'm going for and selectors are a pretty unique case.
Has jQuery written a Regex for this? I couldn't find one in the code.
If not, I guess I'll just have to write a huge Regex for this?
To go straight to the point:
No, jQuery has no method to check if a selector is valid.
jQuery has lots of Regex' for this, that's why you cannot find one in the code.
You do not have to write a huge Regex for this, the answer is more simple as shown below.
I understand your problem because I experienced it, there are cases in which you're not in control of the selector to give to the jQuery function.
The problem not outlined enough is that if a selector is not valid jQuery throws an error (it is important because here is the answer).
Example using jQuery v1.9.1:
$('##somewhere');
It logs into the console the following line:
throw new Error( "Syntax error, unrecognized expression: " + msg );
which source is at row 4421 of the jQuery.js file (non-minified and uncompressed version).
So, instead of looking for an inner method of jQuery (which could surely simplify things but is not available), you can just listen the error thrown to establish if the selector is valid:
function isValidSelector(selector) {
if (typeof(selector) !== 'string') {
return false;
}
try {
var $element = $(selector);
} catch(error) {
return false;
}
return true;
}
You can also make it a jQuery plugin:
jQuery.extend({
isValidSelector: function(selector) {
if (typeof(selector) !== 'string') {
return false;
}
try {
var $element = $(selector);
} catch(error) {
return false;
}
return true;
}
});
to be used this way:
alert($.isValidSelector('#what?!?'));
Best regards.
EDIT:
added type validation: the selector must be a string.
Anyhow it is a partial solution, it does not return false for selectors defined as string objects var selector = new String('##wrong-selector#!');, which are not a primitive type.
Lots of strings can technically be a selector like $('blah') could select custom elements! There isn't any good way of knowing the intent of what to do with the argument passed to your function, so it's best to have a well defined structure like Gaby has commented.
Selector:
yourFunction({ selector: 'div' });
Or
yourFunction({ value: 'testing' });
Will take a different route in your code.
Without this technique the best you can do is just attempt for jQuery to find elements based on the selector, check with .length, if elements are found then assume the caller intended a jQuery selector. Another option could be just to document that a jQuery object must be passed i.e.:
yourFunction({ value: jQuery('div') });
Then for a different route you can do
if (value instanceof of jQuery) { .... }
There can not be a regex for this, since the selectors are extensible and anyone could add any number of personal selectors (with custom defined symbols etc) ...
Perhaps you should try passing your arguments as a single object with named parameters.
{ selector:'...',
otherargument:'somevalue',
afunction: function(){...}
}
The jQuery code for determining the selector is valid is about 108 lines long, so don't expect to determine if it's a valid selector or not in one RegEx statement.
Your best bet is probably to look at what jQuery determines to be a valid selector, and make a function that essentially checks the same way, but returns whether it's valid or not.
https://github.com/jquery/jquery/blob/master/src/core.js#L80-188
This does not answer your question, but i think it can be helpful. It checks not if an argument is a jQuery selector, however it tests whether the selector exists in the document.
$.fn.inDom = function() { return $(document).find(this).length; };
BTW: I dont use $(selector).length directly, since it will return 1 if the passed argument is an HTMLNode.
For better interpretation purposes:
$('foo').length // 0
$('.foo').length // 0
$('#foo').length // 0
$('<foo>').length // 1
$(document).find('foo').length // 0
$(document).find('.foo').length // 0
$(document).find('#foo').length // 0
$(document).find('<foo>').length // 0

JavaScript dollar function, function $() error

I've come across the dollar sign function over the internets and decided to use it for a javascript toggle menu. However, the "$" symbol makes my code fail.
This is what I'm trying to use:
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
function toggle(obj) {
var el = $(obj);
el.style.display = (el.style.display != 'none' ? 'none' : '' );
}
The $ from "function $(){" seems to break the code. How do you declare this function?
If I replace $ with "anything", it works, but not as a dollar function...
The dollar sign is not a standard Javascript function, but is part of a third party library.
There are two well-known libraries which use the dollar sign in this way.
The older one is called Prototype, but the one which is currently in vogue, and most likely to be the one you've seen in use is JQuery.
Both these libraries would be used by adding a <script> tag to your HTML page, to include the library code, after which you can use their functionality.
Most of the functionality of both these libraries is contained within their respective $() functions. In the case of JQuery, you can also refer to the $() function as jQuery() to prevent namespace clashes, in the event that you wanted to use both of them.
I suggest reading up on JQuery before continuing -- JQuery is very powerful, and adds a lot of functionality, but the coding style for writing JQuery code can be quite different from regular Javascript, and can take a bit of getting used to. And that's quite apart from learning the API and finding out what it can do.
To actually answer your question -- which is how to declare $ as a function name, I suggest having a look at the JQuery source code to see how they do it. However, I managed to produce a working $() function first time I tried, like this:
var $ = function() {alert('dollar works for me');}
$();
But to be honest, I wouldn't do that. If you really want to use the $() function in the way it's being used in other sites, you need to use JQuery. It does a whole lot more than just wrapping document.getElementById().
By the way, JQuery and Prototype are not the only similar libraries out there. If you're interested in this sort of thing, you may also want to look into MooTools, YUI, and a few others.
Hope that helps.
The $ sign is a notation for various javascript frameworks (prototype/jQuery). Since replacing it with "anything else" works, you most likely have a clash between that inline function and the framework you are using.
In itself, the notation and function is correct, as the following example shows.
Open a new tab/window and enter this on the address bar:
javascript:eval("function $() { alert('hi'); } $();");

How to change all $ to jQuery where some variable name starts from $ in some Jquery Plugin?

I learned from this article that to avoid confliction between javascript libraries, use jQuery.noConflict(); function just before jQuery(document).ready ( function () { }) and replace jQuery at all instance of $
but i have seen many jQuery plugin where $ is used with variable declaration???
here is an example on this link on below section
How to...
[edit]
...retrieve the index of the currently selected tab
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0
now i m really confused how to replace $ with jQuery in var $tabs??
first of all tell me how can we use jQuery instead of $ in above example and
what is the logic behind declaring variable starting with $ in javascript?? ( although this is a PHP varaible decalarion syntax)
Thank you.
$tabs is just a variable name. That's because javascript accepts a $ as part of a variable.
You can also use variables like my$var = 10 or my$other$var$ = 20.
To use jQueryinstead of $ just substitute it in your code:
var x = $('#mydiv')
becomes
var x = jQuery('#mydiv')
JavaScript variable names start with a letter, $, or underscore.
http://javascript.about.com/od/variablesandoperators/a/vop04.htm
so $tabs is a normal variable and has nothing to do with jQuery.
Like javascript many other languages allow usage of $ in variable names.
You can refer this answer why does several javascript libraries use $ for one or other use for wonderful explanation of why $ is used in javascript or jQuery.

Categories

Resources