Can jQuery event namespaces contain dashes? - javascript

Can jQuery event namespaces contain dashes (hyphens)? I have long namespaces and I want to separate them with dashes, is it possible? I didn't find any documentation on http://api.jquery.com/unbind/. Do you know where it's documented?
The code is something like this:
var close_menu_event_element = $('{selector}');
var event = 'click.our-top-menu'; // Can be also 'click.our-compose-menu'
if (close_menu_event_element.length > 0) {
close_menu_event_element.unbind(event);
if (typeof(func) === "function") {
close_menu_event_element.bind(event, func);
}
}
Update: bind and unbind work in Chrome 41.0.2272.101 m with namespaces with dashes, but I want to know if it works in any browser with jQuery? We are using jQuery 2.1.1.

I want to know if it works in any browser with jQuery
Yes, it will work in all major browsers without problems. All jQuery do to resolve namespaces is split selector string by . character. Something like this:
namespaces = ( tmp[2] || "" ).split( "." ).sort();
Nothing fancy here, split method will work everywhere, you can use - or # if you want in namespace substring.
Here is the best documentation: source code.

Not sure if jQuery gets the last word on this, but the answer is no according to the jQuery documentation for .on().
Namespaces should contain upper/lowercase letters and digits only.

Related

Replace deprecated jQuery "live" to "on" format using RegEx?

I updated jQuery in an application with 1000+ screens and would like to do a mass update from "live" to "on" for the event handlers.
I plan on bubbling everything to the document just to make the application run at least. That will give me enough time to take another pass on it manually and update from document to some parent element.
I'm trying to replace this format:
$("#some-id").live('click', function () //or
$('.some-class').live('submit', function ()
to this:
$(document).on('click', "#some-id", function () //or
$(document).on('submit', '.some-class', function ()
I'm using Visual Studio but can use another software if needed to do the mass search/replace. Anyone know of a RegEx to do this, even if it takes a couple of expressions to do this?
For the first case, with the string selectors, you'd want to
find \$\(\s*(["'][^"']*['"])\s*\)\.live\(([^,]*)
and replace with $(document).on(\2, \1
(I haven't used visual studio in a while, so I don't know if it does regex, or if it uses \2 or $2 for substitution).
For the second case, with a variable, you'd want:
find ([^\s"()']+)\.live\(([^,]*)
Note this one is more risky because any call to a .live method on an object will end up changed. Probably OK if you don't have any functions called live.
In either case I'd probably do each replacement one at a time to make sure it's doing the right thing.
Here's one approach that's pretty close. It doesn't strip off the jquery selectors like you asked for the second parameter of the output.
var output = input.replace(/(\S.*)[.]live[(]([^,]+),/g, "$$(document).on($2, $1,");
This regex is in javascript, as specified in your question tags, but it should be able to translate to any language.
Here's a jsfiddle: http://jsfiddle.net/qc2homx6/

Array check element ID with wildcard in if statement

I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.
If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))
First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))
Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}
You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.
You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }

jQuery selector using regex (or something else)

I need to select an attribute in my code that match a string+number in the class name, using jQuery
What I need to do is to match something like that:
var myVar = 'item';
$('#id [class="'+myVar+'\d+"]');
My code contain other classes starting by "item" as well, so I can't use the selector class^="item"
I found out different things on Internet, but nothing that match perfectly my requirement.
I found the jQuery extension ":regex" but I'm not allowed to use it. http://james.padolsey.com/javascript/regex-selector-for-jquery/
I found the use of "filter" as a function but this is horrible for the performance
jQuery filter selector, is this right?
I tried to do something but it's not even working:
$('#id *').filter(function() {
return this.className.match("/"+myVar+"\d/");
});
Do you have some better suggestions?
Thanks.
No you can't use \d with CSS/jQuery selectors.
I suggest you split the number out into another attribute like data-number or something. This way you can target the class easily and efficiently and still have the number available.
<span class="my-class" data-number="1"></span>
<span class="my-class" data-number="6"></span>
<span class="my-class" data-number="10"></span>
jQuery example
$.each($('my-class'), function () {
$(this).attr('data-number');
});
As #Asad mentions they can also be selected using $('.my-class[data-number="1"]').
How about:
$('#id [class*=' + myVar + ']').filter(function() {
return this.className.match(new RegExp('(^|\\s)' + myVar + '\\d+(\\s|$)'));
});
Check jsfiddle demo here.
The selector picks every descendant element of #id with myVar in a class name. Finally it filters them, leaving only those who have myVar followed by one or more of digits as the name of one of its classes.
Note: You probably aready know that, but it is worth warning anyway: you must prevent myVar from having chars with special meaning to selectors (which would mess the [class*=' + myVar + ']' selector) and to regexes (such as the string '[a-z]', which would make the regex match a range instead of the literal '[a-z]' -- in this case, it should be escaped, as '\[a-z\]').

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'); } $();");

Parsing XML with namespaces using jQuery $().find

I'm trying to get the contents of a XML document element, but the element has a colon in it's name.
This line works for every element but the ones with a colon in the name:
$(this).find("geo:lat").text();
I assume that the colon needs escaping. How do I fix this?
Use a backslash, which itself should be escaped so JavaScript doesn't eat it:
$(this).find("geo\\:lat").text();
That isn't just an ordinary element name. That's a qualified name, meaning that it is a name that specifically refers to an element type within a namespace. The element type name is 'lat', and the namespace prefix is 'geo'.
Right now, jQuery can't deal with namespaces very well, see bug 155 for details.
Right now, as a workaround, you should be able to select these elements with just the local name:
$(this).find("lat").text();
If you have to distinguish between element types with the same local name, then you can use filter():
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("lat").filter(function() { return this.namespaceURI == NS; }).text();
Edit: my mistake, I was under the impression that patch had already landed. Use Adam's suggestion for the selector, and filter() if you need the namespacing too:
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("geo\\:lat").filter(function() { return this.namespaceURI == NS; }).text();
if you have a jquery selector problem with chrome or webkit not selecting it try
$(this).find('[nodeName=geo:lat]').text();
this way it works in all browsers

Categories

Resources