Jade : New warning on multiple attributes - javascript

I have updated jade to latest version, and started seeing this message in console
You should not have jade tags with multiple attributes
It is mentioned as feature, here
0.33.0 / 2013-07-12
Hugely more powerful error reporting (especially with compileDebug set explicitly to true)
Add a warning for tags with multiple attributes
and I see it in the code.
https://github.com/visionmedia/jade/blob/a38aa552f6f53554ac5605299b6b8c7e07cbdf1f/lib/parser.js#L662
But, what does it really signify. When will I get this warning. For example, when will I get error based on the below code (It works without warning, but to like to know when will I get error so that I can compare with my code)
mixin link(href, name)
a(class=attributes.class, href=href)= name
a(href=href, attributes)= name
+link('/foo', 'foo')(class="btn")

Multiple "attributes" doesn't mean what you probably think it means. It's not an HTML attribute as we know it, but a token of type "attribute".
Example:
a(href="#WAT").some-class(title="WAT")
Note how I have two attribute sections, each with one attribute.
Better put them in one attribute section:
a(href="#WAT", title="WAT").some-class

(I found this question through googleing this warning as one of the first results because I wanted to get rid of it ...)
The accepted answer above did not help me in the following case, but it shows how one can get rid of the warning without loosing the attributes functionality
(it does not provide an answer to why it works this way):
// using mixins similar to +link(param1,param2) above where 'data' and 'class'
// below are not named mixin params
// OK (without a warning):
+link("foo", data="true")(class="bar")
// WARNING is shown:
+link("foo")(class="bar")(data="true")
// ERROR on compiling:
+link("foo", class="bar", data="true")
(I'm sorry to create so much misunderstandings as shown in the comments below and hope my last edit here clarifies it to be a valid, although slightly more general, answer/help for those docpad warnings)

Related

Uncaught TypeError: Cannot read property 'children' of null while running JavaScript in Chrome Console

I got this error while executing my JS code in chrome console
Uncaught TypeError: Cannot read property 'children' of null
at getFollowers (<anonymous>:98:53)
at <anonymous>:57:7
My Function being
function getFollowers(){
var followersDiv = document.querySelector('div[role="presentation"]').querySelector('li').parentElement.children;
for (var i = 0;i<followersDiv.length;i++){
var tempUser = followersDiv[i].lastElementChild.children[0].children[1];
followers.push({
userID: tempUser.children[0].textContent,
userName: tempUser.children[1].textContent,
});
}
document.querySelector('[aria-label="Close"]').click();
}
The line seems to have missing something here
var tempUser = followersDiv[i].lastElementChild.children[0].children[1];
Can someone help me with this?
I would’n say that the line you’re pointing is missing something. I would say this given line expects things to be here without providing enough guarantees.
One way or another, tempUser is built trying to use something that can be null. In my opinion, your code is quite optimistic : you assume lastElementChild to be nonEmpty, to have a children field which is a non empty array, etc… Each step after "followersDiv[i]" may lead to failure, you did not check the values’ content.
There are two strategies to make your code more robust, IMO :
Use an external library like lodash to have a more robust code. In particular, you may use _.get and _.isEmpty
Try to use a more accurate CSS selector in your querySelector as I’m not sure you need to manually browse the DOM if your selector is good enough. This way, you won’t have nodes that don’t fit your expectations.

Will jQuery complain/throw error if it doesn't find element in selector?

I'm a little confused, suppose I do various selections, both single and multi:
$('#button1').off('handler').on('handler')
$('input[id*="my_button"]').each(function() {
But in my HTML there are no elements with IDs "button1" (Ex. 1) or any substring of "my_button" (Ex. 2).
Will there be JS errors if no elements are found, or the code will just silently not execute?
I've seen both, and I'd like to silently process/skip if there are no matching elements.
No, it will not error. It will return an empty result set. Any operations attempted on it will simply be ignored.
There is no difference between a "single" and a "multiple" selector. As far as jQuery is concerned, it is a (potentially empty) group of elements.
.on and .off, for example, will apply/remove the event handler on each of the elements in the group. If that group happens to be empty, then nothing happens.
In some ways, this is a good thing - it removes the need for manually checking it. However, I tend to see it as a problem. Let's say I write:
document.getElementById('button1').addEventListener(...);
But #button1 does not exist on the page. I get an error telling me such (sort of - "Unable to get property 'addEventListener' of undefined or null reference" is not immediately obvious but you learn to understand it) and I can resolve the problem either by fixing the absence of the desired element, or adding a check to explicitly say "it's okay if there isn't such an element".
However in jQuery you don't get that choice. Typo in your selector? The empty collection is handled just fine and events mysteriously disappear. I consider this to be a bad thing personally, but there's no way for jQuery to know whether you intended for zero, one, or hundreds of elements to match...

JSON return error as undefined when the value is numeric

not sure where the errors lies in what I am trying to achieve.
I am working with someone else's code and unfortunately they have used numbers for div ids in some places.
These number ids are used in various places and if I can, I want to find a way to keep things as they are.
So,
returning the following in JSON:
editorID: "1000"
And in my AJAX call i use that return like so:
var editorID = response.editorID;
CKEDITOR.instances.editorID.insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
However this gives me an error saying that the editorID is undefined.
As you can I already use a JSON response in my code, this works fine so its not a problem with datatypes etc.
I also tried to do:
alert(response.editorID);
which gave me the correct value.
When I tried putting a number directly into CKEditor insertHTML code it was showing my syntax errors so maybe thats the issue. If so, any work around for it?
Thanks. Craig.
To use a variable as a property, you have to use [] notation:
CKEDITOR.instances[editorID].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');
When you use .editorID, it's looking for a property named editorID, not 1000.
You also have to use this syntax when the property isn't a valid identifer. So if you wanted to put the number directly, you would write:
CKEDITOR.instances['1000'].insertHtml('<br><img class="buildimage" src="http://www.buildsanctuary.com/phpLibs/bulletproof-master/src/userBuildImages/'+response.imageName+'"><br>');

Object has no method 'charAt' in jQuery plugin

I am attempting to use the autoNumeric jQuery plug-in which helps with the conversion of various currencies in jQuery.
The plug-in itself works when I use it in a jsFiddle example.
$(function () {
$('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
However, as soon as I integrate it into a big, legacy project, I start receiving the above error on line 194. I know why I'm getting the error - a string is not being passed into the negativeBracket function (negativeBracket(s, nBracket, oEvent) is the signature). Instead, it seems to be a jQuery object - e.fn.init1. I'm confused on how this might be happening. I realize the community may not be able to give a direct answer, but I would love (and will accept as an answer) being pointed in the right direction as nothing has jumped out at me so far.
Update
So, have some additional info that may be of help. It still has me stumped how it's happening (unfortunately, the answers below didn't help to provide any additional insight). When I link in autoNumeric, I key it off of any text field with the class money. It does work as I am typing in the box. I can see see formatting. However, when I tab into a new box, the box I just finished typing in clears itself completely after hitting line 152 in autoNumeric with the same exact error.
#Carlos487 was correct in his answer when he said I have an object that is not a string. I instead have an object that, I believe, is a function. Here's what I'm seeing in Chrome debugger tools:
e.fn.init[1]
> 0: input#price.money required
> context: input#price.money required
length: 1
selector: ""
> __proto__: Object[0]
The "arrowed" items can be further expanded out. I don't know if this provides any more clues, but it's at least something a bit different.
The errors like
no method XXXXX in Object
are produced because you are trying to call obj.XXXX() and obj is not of the desired type, in your particular case a string.
Have you tried in another browser because older or IE can be a little troublesome. I would recomend using chrome developer tools with your legacy app to see if anything else is conflicting or producing the error
I will bet money that you are using a second library which is interfering with jQuery. It has probably overridden $ with its own function.
Try using jQuery instead of $:
jQuery(function () {
jQuery('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
It turns out that the issue was a myriad of issue compounding into the error I saw. A couple things that was happening:
The validator plug-in was wrapping the jQuery object in its own structure (hence the charAt issue).
Once I fixed that, I also learned that some homegrown code was also wiping and rewriting data into the field to provide formatting (which is what autoNumeric is also doing), so autoNumeric would bomb out because it would get a null value and attempt to format it.
There was some other random craziness that also needed cleaned up. So...issue resolved! Still more to work on, but at least this hurdle is past. Thanks all for your help.

Simple way to check/validate javascript syntax

I have some big set of different javascript-snippets (several thousands), and some of them have some stupid errors in syntax (like unmatching braces/quotes, HTML inside javascript, typos in variable names).
I need a simple way to check JS syntax. I've tried JSLint but it send too many warnings about style, way of variable definitions, etc. (even if i turn off all flags). I don't need to find out style problems, or improve javascript quality, i just need to find obvious syntax errors. Of course i can simply check it in browser/browser console, but i need to do it automatically as the number of that snippets is big.
Add:
JSLint/JSHint reports a lot of problems in the lines that are not 'beauty' but working (i.e. have some potential problems), and can't see the real problems, where the normal compiler will simply report syntax error and stop execution. For example, try to JSLint that code, which has syntax errors on line 4 (unmatched quotes), line 6 (comma required), and line 9 (unexpected <script>).
document.write('something');
a = 0;
if (window.location == 'http://google.com') a = 1;
document.write("aaa='andh"+a+"eded"');
a = {
something: ['a']
something2: ['a']
};
<script>
a = 1;
You could try JSHint, which is less verbose.
Just in case anyone is still looking you could try Esprima,
It only checks syntax, nothing else.
I've found that SpiderMonkey has ability to compile script without executing it, and if compilation failed - it prints error.
So i just created small wrapper for SpiderMonkey
sub checkjs {
my $js = shift;
my ( $js_fh, $js_tmpfile ) = File::Temp::tempfile( 'XXXXXXXXXXXX', EXLOCK => 0, UNLINK => 1, TMPDIR => 1 );
$| = 1;
print $js_fh $js;
close $js_fh;
return qx(js -C -f $js_tmpfile 2>&1);
}
And javascriptlint.com also deals very good in my case. (Thanks to #rajeshkakawat).
Lots of options if you have an exhaustive list of the JSLint errors you do want to capture.
JSLint's code is actually quite good and fairly easy to understand (I'm assuming you already know JavaScript fairly well from your question). You could hack it to only check what you want and to continue no matter how many errors it finds.
You could also write something quickly in Node.js to use JSLint as-is to check every file/snippet quickly and output only those errors you care about.
Just use node --check filename
Semantic Designs' (my company) JavaScript formatter read JS files and formats them. You don't want the formatting part.
To read the files it will format, it uses a full JavaScript parser, which does a complete syntax check (even inside regular expressions). If you run it and simply ignore the formatted result, you get a syntax checker.
You can give it big list of files and it will format all of them. You could use this to batch-check your large set. (If there are any syntax errors, it returns a nonzero error status to a shell).

Categories

Resources