_str is not defined while using underscore.js - javascript

This is the first time I am using Underscore.js. I have included the production underscore-min.js at the bottom of my page ( which is in Jade originally ), just before my custom script.
<script src="/javascripts/underscore-min.js">
<script src="/javascripts/custom.js">
Now, I call this function in my custom.js:
var selections = "Bold;Business-like;Charming";
var num_selections = _str.words( question.selected_words, ";").length;
Basically, I need to know the number of words selected and the native javascript method split returns 1 for even a blank string. But when I use this code, I get this error in my browser console:
Uncaught ReferenceError: _str is not defined
I tried using this line before using _str, but then I get require is not defined:
var _ = require('underscore');
Or, perhaps I can put my question as How do we start using underscore functions in our front-end javascripts?

Even though you are using node, require is not available on the front-end. Front-end javascript is not the same as back-end, nor do they directly interact. Underscore is called using _. All the methods available here: http://underscorejs.org/ are accessed via _.<method_name>. I am not too familiar with underscore and maybe you are using an older version but I cannot find _.str anywhere in the docs. So first, make sure you are using the correct notation for underscore _.<method_name> and make sure the function exists in the documentation. This fiddle shows some basic underscore functions: https://jsfiddle.net/mawpw2c5/

Related

Use of $ and _ in Javascript

I'm trying to interpret this piece of Javascript code. What is the use of the $ and _ signs here? In particular, is $ an alias for the JQuery library, and does this also apply for $set?
Template.postEdit.events({
'submit form': function(event) {
event.preventDefault();
var currentPostId = this._id;
var postProperties = {
url: $(event.target).find('[name=url]').val(),
title: $(event.target).find('[name=title]').val()
}
Posts.update(currentPostId, {$set: postProperties}, function(error) {
if (error) {
// display the error to the user
throwError(error.reason);
} else {
Router.go('postPage', {_id: currentPostId});
}
});
}
});
Explaination
$ and _ are mostly appended in Javascript variables to give more readability and to be more distinguishable ( visually most of the times ) from other variables. They are just conventions used by JS developers. Not necessary you've to use them. Major libraries/frameworks like Jquery, Angular like to follow this style in their frameworks.
Usage of $
Jquery have wrapped their features in $ . If you have included jQuery in your application, then $ used alone stands for jquery Object. Jquery being a really popular modern library, have somehow snatched the variable in JS. But its not like they have licensed the variable ( Just think, if variable name could be licensed, development would be more painful than it is now :p ), its more like they have dominated the use of $.
var selector = $('.someclass'); /* This is jquery object similar to
var selector = jQuery('.someclass') */
var $somestring = 'some string'; // Here $ character is appended to a variable.
//It doesn't adds any special behavior to the variable.
Some people have make good use of $, check it out here.
A naive developer who have used too much or the only library as JQuery in his lifespan is prone to this confusion. When he sees source code from framework like AngularJS, he tries to relate things with his former love jQuery. In Angular variables like $scope, $compile, etc, they seem confusing to him, as they have heavily appended $ to name their objects. Its just another name, you can write code with or without it. Angular uses this convention to distinguish variables from local to special objects. Big guns always try to dominate their conventions over the developer community. Can't blame them much, its for the betterment for all
Usage of _
Riding in similar vogue bandwagon, _ was nearly snatched by another useful ( really ? we can live without it ) library called Underscore Js . So they use the _ as their Underscore object, or mostly developers are to be blamed for this abuse, as they have paved its path to the vanity. But we can't blame developers for this, they were just using following good naming conventions.
var _myName = 'Who Cares'; // similar to $ no special behavior
var currentPostId = this._id; // In your case it seems
Well _ is mostly used by developers to distinguish the variables as private data members of their class, but only naming doesn't guarantee the access level. A good post briefly explaining for this is here
The best part is that, all the special characters that are allowed in Javascript to create distinguishable variable names are already invaded by biggies. So no more confusion. It is understandable why underscore invaded _ as their supremo, it stands for its meaning. But I am still curious why $ was chosen by jQuery. It doesn't even rhyme with it. No distant relation, it seems jQuery just took it as their property. I don't find any post explaining their invasion over it.
Sorry for being so dramatic, comic and sarcastic. Feel free to downnvote if it does not suit your appetite. Here to just help and make this space more interesting.
P.S : A list of valid characters for the naming convention used in JS
is explained here

L20n get translated string in javascript

Is there a way of quickly grabbing translated string in javascript?
For example like this:
var s = L20n.get("hello");
I am using 3.5 from npm.
Following does not work:
document.l10n.ready.then(function(context) {
document.l10n.formatValue('myItemKey').then(function(result){
console.log(result);
});
});
It results in printing item key instead of translated value.
If you're using version 3.x, use formatValue:
document.l10n.formatValue('hello').then(console.log);
You can read more about it here: https://github.com/l20n/l20n.js/blob/v3.x/docs/view.md#viewformatvalueid-args. document.l10n is an instance of the View class that is created automatically for you when the page loads.
The method is asynchronous so that you don't have to worry about race conditions related to language files not being loaded yet.

Example of how to use PEG.js

I'm playing around with PEG.js.
I created some simple code that accepts inputs in the form [LettersNumbers]:
abc123
hello98765
etc.
This is the code:
start = expression
expression = text + number
text =
a: [a-z]+
{return a.join("");}
number =
b:[0-9]+
{return b.join("");}
Here: Online version the code can be tested and the parser downloaded, additionally I downloaded peg.js itself.
Unfortunately, the documentation is very sparse. I tried:
<script src="peg-0.9.0.min.js"></script>
<script src="parser.js"></script>
<script>
var parser = new PEG;
parser.parse("test123");
</script>
But got these errors:
Uncaught ReferenceError: module is not defined
Uncaught TypeError: PEG is not a function
Could anybody please provide me with a working example? I just need to integrate the generated js-files into a website.
This answer assumes that you would like to continue using the PEG.js online version to build your parser.
You only need peg-0.9.0.min.js if you are generating the parser in your web page. Since you are using the PEG.js online version to generate your parser you don't need to do that.
You do need to include the downloaded parser.js. You need to specify a browser-friendly global variable in the PEG.js web version and re-download.
This example uses PARSER:
Following that you can use:
<script src="parser.js"></script>
<script>
PARSER.parse("test123");
</script>
Plunker example
If you want to use it on web, you need to download the browser version, or ref it from CDN.
Also, you need to use its javascriptAPI to create a parser.
// One line version of your grammer.
var parser = PEG.buildParser('start = expression;expression = text + number;text = a: [a-z]+{return a.join("");};number = b:[0-9]+{return b.join("");}');
console.log(parser.parse("test123"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/pegjs/0.7.0/peg.min.js"></script>

Unable to create a MozillaBrowserBot object

I tried to get the MozillaBrowserBot object in mozilla js. But it is not giving the object. I used the code as below:
function externalApplication(){
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
alert("wm: "+wm);
var contentWindow=wm.getMostRecentWindow('navigator:browser').getBrowser().contentWindow;
alert("contentWindow: "+contentWindow);
//I am not gettting this pageBot object
var pagebot=new MozillaBrowserBot(contentWindow);
alert(pagebot);
}
I want to add the find option to the xpath checker. If the MozillaBrowserBot is related to selenium IDE then is there any possibility to get the pagebot object?
Judging by Google search results, MozillaBrowserBot is something that's defined by Selenium IDE. Also, it is apparently defined in the content page you got, not in the context where your code executes. That means that the proper invocation would be:
var pagebot = new contentWindow.MozillaBrowserBot(contentWindow);
This is based on a bunch of guesses of course since your question doesn't provide any context information whatsoever.

Conflict with 2 javascript files

I'm new with javascript, so i'm trying to use two jQuery plugins, together they don't work properly. Just if i remove one of two.
How can i resolve this problem ? I could paste both .js files, but that is 2k lines of code, I don't want bother you with so many lines of code.
jQuery.autocomplete.js
Greybox plugin AJS.js
Or if you know some plugin that do some functionality, will help too =)
--
UPDATE:
Thank you guys,
(i'm not able to add comment in your answers (i really don't know why), some problem with the site.)
#Mörre i noted when i remove this line in AJS.js it works (part of it) :
AJS.exportToGlobalScope();
But after that I don't know what to do, sorry guys, I'm new in javascript so many things that you said I don't understand.
#Jim, i don't find any:
$(document).ready(function() {
});
the replace by jQuery as you said.
I try to replace all '$' by 'jQuery', and still doesn't work.
Valter,
you may find that there's a collision on the $ alias going on. you'll possibly get it to work if you explicity reference jquery object using the full jquery alias i.e rather than:
<script type="text/javascript">
$(document).ready(function() {
});
</script>
try:
<script type="text/javascript">
jQuery(document).ready(function() {
});
</script>
change any $ references to jQuery in the client code when using the autocomplete lib.
just a thought if it's in relation to this'area'
Without checking any further after looking at the code briefly, the AJS code puts everything in a global object AJS at first - but then exports every single property of that object into the global namespace. Bad behavior. The first one is a regular jQuery plugin. Recommendation: Don't use AJS, or remove the export to global space (you then just call AJS methods by prefixing them with "AJS.").

Categories

Resources