Use of $ and _ in Javascript - 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

Related

What is the default “tag” function for template literals?

What is the name of the native function that handles template literals?
That is, I know that when you write tag`Foo ${'bar'}.`;, that’s just syntactic sugar for tag(['Foo ', '.'], 'bar');.¹
But what about just ​`Foo ${'bar'}.`;? I can’t just “call” (['Foo ', '.'], 'bar');. If I already have arguments in that form, what function should I pass them to?
I am only interested in the native function that implements the template literal functionality. I am quite capable of rolling my own, but the purpose of this question is to avoid that and do it “properly”—even if my implementation is a perfect match of current native functionality, the native functionality can change and I want my usage to still match. So answers to this question should take on one of the following forms:
The name of the native function to use, ideally with links to and/or quotes from documentation of it.
Links to and/or quotes from the spec that defines precisely what the implementation of this function is, so that if I roll my own at least I can be sure it’s up to the (current) specifications.
A backed-up statement that the native implementation is unavailable and unspecified. Ideally this is backed up by, again, links to and/or quotes from documentation, but if that’s unavailable, I’ll accept other sources or argumentation that backs this claim up.
Actually, the first argument needs a raw property, since it’s a TemplateStringsArray rather than a regular array, but I’m skipping that here for the sake of making the example more readable.
Motivation
I am trying to create a tag function (tag, say) that, internally, performs the default template literal concatenation on the input. That is, I am taking the TemplateStringsArray and the remaining arguments, and turning them into a single string that has already had its templating sorted out. (This is for passing the result into another tag function, otherTag perhaps, where I want the second function to treat everything as a single string literal rather than a broken up template.)
For example, tag`Something ${'cooked'}.`; would be equivalent to otherTag`Something cooked.`;.
My current approach
The definition of tag would look something like this:
function tag(textParts, ...expressions) {
const cooked = // an array with a single string value
const raw = // an array with a single string value
return otherTag({ ...cooked, raw });
}
Defining the value of raw is fairly straightforward: I know that String.raw is the tag function I need to call here, so const raw = [String.raw(textParts.raw, ...expressions)];.
But I cannot find anywhere on the internet what function I would call for the cooked part of it. What I want is, if I have tag`Something ${'cooked'}.`;, I want const cooked = `Something ${cooked}.`; in my function. But I can’t find the name of whatever function accomplishes that.
The closest I’ve found was a claim that it could be implemented as
const cooked = [expressions.map((exp, i) => textParts[i] + exp).join('')];
This is wrong—textParts may be longer than expressions, since tag`Something ${'cooked'}.`; gets ['Something ', '.'] and ['cooked'] as its arguments.
Improving this expression to handle that isn’t a problem:
const cooked = [
textParts
.map((text, i) => (i > 0 ? expressions[i-1] : '') + text)
.join(''),
];
But that’s not the point—I don’t want to roll my own here and risk it being inconsistent with the native implementation, particularly if that changes.
The name of the native function to use, ideally with links to and/or quotes from documentation of it.
There isn't one. It is syntax, not a function.
Links to and/or quotes from the spec that defines precisely what the implementation of this function is, so that if I roll my own at least I can be sure it’s up to the (current) specifications.
Section 13.2.8 Template Literals of the specification explains how to process the syntax.

Creating library without encapsulation Javascript

I am very new in creation of libraries in javascript and encapsulations in javascript. I created very first library with the help of one or two tutorials from the web.
The example looks like the following,
<script>
var libs=[];
(function(libs){
function firstLibrary (){
this.initializeHoldings = function () {}
  this.myLibrary = function(){
    var _myLibraryObject = [{FirstName: 'Ibrahim', LastName: 'Shaikh', CompanyName: 'Plexitech'},
{FirstName: 'Nizam', LastName: 'Siddiqui', CompanyName: 'Neoquant'}];
    return _myLibraryObject;
  }
}
libs.customLibrary = firstLibrary;
})(libs);
let $ = new libs.customLibrary();
console.log($.myLibrary());
</script>
This is how my code looks,
now the confusions are,
1): What are the difference between libraries and encapsulations in
javascript?
2): How can I create library without encapsulating it in javascript?
3): Does encapsulation always create library?
Yes, I know it might be a silly question for some of you but many newbies might get confused on this.
1): What are the difference between libraries and encapsulations in javascript?
A "library" is a set of functions/classes. "Encapsulation" doesn't really have a meaning as a unit of code like "library." Wikipedia's short definitions of "encapsulation" are pretty good:
A language mechanism for restricting direct access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
As you can see, neither means anything like "library." But you would probably use encapsulation in parts of your library.
2): How can I create library without encapsulating it in javascript?
Probably, if you didn't have any data maintained by the library that you needed to prevent other code from using, and didn't need to combine data with methods.
3): Does encapsulation always create library?
No, not at all. They're largely unrelated terms and concepts.

JSLint "eval is evil." alternatives

I am have some JavaScript functions that run on both the client (browser) and the server (within a Java Rhino context). These are small functions - basically little validators that are well defined and don't rely upon globals or closures - self-contained and portable.
Here's an example:
function validPhoneFormat(fullObject, value, params, property) {
var phonePattern = /^\+?([0-9\- \(\)])*$/;
if (value && value.length && !phonePattern.test(value))
return [ {"policyRequirement": "VALID_PHONE_FORMAT"}];
else
return [];
}
To keep things DRY, my server code gets a handle on each of these functions and calls toString() on them, returning them to the browser as part of a JSON object. Something like this:
{ "name" : "phoneNumber",
"policies" : [
{ "policyFunction" : "\nfunction validPhoneFormat(fullObject, value, params, property) {\n var phonePattern = /^\\+?([0-9\\- \\(\\)])*$/;\n if (value && value.length && !phonePattern.test(value)) {\n return [{\"policyRequirement\":\"VALID_PHONE_FORMAT\"}];\n } else {\n return [];\n }\n}\n"
}
]
}
My browser JS code then takes this response and creates an instance of this function in that context, like so:
eval("var policyFunction = " + this.policies[j].policyFunction);
policyFailures = policyFunction.call(this, form2js(this.input.closest("form")[0]), this.input.val(), params, this.property.name));
This all works very well. However, I then run this code through JSLint, and I get back this message:
[ERROR] ValidatorsManager.js:142:37:eval is evil.
I appreciate that often, eval can be dangerous. However, I have no idea how else I could implement such a mechanism without using it. Is there any way I can do this and also pass through the JSLint validator?
I wouldn't worry about it since you are only passing these function strings from the server to the client, and are thus in control of what will be evaluated.
On the other hand, if you were going the other direction and doing the evals of client-passed code on the server, that would be an entirely different story...
Update:
As disabling the validation option in your comment may cause you to miss future errors, I would instead suggest passing the function name rather than the entire function and have the function library mirrored on the server and client. Thus, to call the function, you'd use the following code:
var policyFunction = YourLibraryName[this.policies[j].policyFunctionName];
var policyArguments = this.policies[j].policyArguments;
policyFunction.apply(this, policyArguments);
Update 2:
I was able to validate the following code with JSLint successfully, which essentially allows you to "turn off" validation for the vast minority of cases where eval is appropriate. At the same time, JSLint still validates normal eval calls, and all uses of this method should throw up flags for future developers to avoid using it/refactor it out where possible/as time allows.
var EVAL_IS_BAD__AVOID_THIS = eval;
EVAL_IS_BAD__AVOID_THIS(<yourString>);
Dont encode a function as a string in JSON. JSON is for content, which you are confounding with behavior.
Instead, I suppose you could return JS files instead, which allow real functions:
{ name : "phoneNumber",
policies : [
{ policyFunction : function() {
whateverYouNeed('here');
}
}
]
}
But while that solves the technical issue, it's still not a great idea.
The real solution here is to move your logic out of your content entirely. Import a JS file full of little validation functions and call them as needed based on a dataType property in your JSON or something. If this functions are as small and portable as you say, this should be trivial to accomplish.
Getting your data all tangled up with your code usually leads to pain. You should statically include your JS, then dynamically request/import/query for your JSON data to run through your statically included code.
I would avoid using eval in all situations. There's no reason you can't code around it. Instead of sending code to the client, just keep it hosted on the server in one contained script file.
If that's not doable, you can also have a dynamically generated javascript file then pass in the necessary parameters via the response, and then dynamically load the script on the client side. There's really no reason to use eval.
Hope that helps.
You can use
setInterval("code to be evaluated", 0);
Internally, if you pass setInterval a string it performs a function similar to eval().
However, I wouldn't worry about it. If you KNOW eval() is evil, and take appropriate precautions, it's not really a problem. Eval is similar to GoTo; you just have to be careful and aware of what you're doing to use them properly.
With very little parsing you could have had it like so:
var body = this.policies[j].policyFunction.substr;
body = body.substr(body.indexOf("(") + 1);
var arglist = body.substr(1, body.indexOf(")"));
body = body.substr(arglist.length + 1);
var policyFunction = new Function(arglist, body);
Which would provide a bit of validation, avoid the literal use of eval and work synchronously with the code. But it is surely eval in disguise, and it is prone to XSS attack. If the malevolent person can get their code loaded and evaluated this way - it will not save you. So, really, just don't do it. Add a <script> tag with the proper URL and that would be certainly safer. Well, you know, better safe then sorry.
PS. My apologises if the code above doesn't work, it only shows the intent, I've not tested it, and if I made a mistake at counting parenthesis or some such - well, you should get the idea, I'm not advertising it by any means.
DRY is definitely something I agree with, however there is a point where copy+pasting is more efficient and easy to maintain than referencing the same piece of code.
The code you're saving yourself from writing seems to be equivalent to a clean interface, and simple boiler plate. If the same code is being used on both the server and the client, you could simply pass around the common pieces of the function, rather than the whole function.
Payload:
{
"name": "phoneNumber",
"type": "regexCheck",
"checkData": "/^\\+?([0-9\\- \\(\\)])*$/"
}
if(payload.type === "regexCheck"){
const result = validPhoneFormat(fullObject, value, payload.checkData)
}
function validPhoneFormat(fullObject, value, regexPattern) {
if (value && value.length && !regexPattern.test(value))
return [ {"policyRequirement": "VALID_PHONE_FORMAT"}];
else
return [];
}
This would give you the ability to update the regex from a single location. If the interface changes it does need to be updated in 2 places, but I wouldn't consider that a bad thing. If the client is running code, why hide the structure?
If you really, really want to keep both the object structure and the patterns in one place - extract it to a single API. Have a "ValidatePhoneViaRegex" api endpoint which is called by all places you'd be passing this serialized function to.
If all of this seems like too much effort, set jslint to ignore your piece of code:
"In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax. The identifier of this warning is W061. This means you can tell JSHint to not issue this warning with the /*jshint -W061 */ directive.
In ESLint the rule that generates this warning is named no-eval. You can disable it by setting it to 0, or enable it by setting it to 1."
https://github.com/jamesallardice/jslint-error-explanations/blob/master/message-articles/eval.md
I would prefer to see copy+pasted code, a common api, or receiving parameters and copy+pasted boiler plate than magical functions passed in from the server to be executed.
What happens if you get a cross-browser compatibility error with one of these shared functions?
Well, the first thing to bear in mind is that jsLint does make the point that "it will hurt your feelings". It's designed to point out where you're not following best practices -- but code that isn't perfect can still work just fine; there's no compulsion upon you to follow jsLint's advice.
Having said that, eval is evil, and in virtually all cases there is always a way around using it.
In this case, you could use a library such as require.js, yepnope.js or some other library that is designed to load a script separately. This would allow you to include the javascript functions you need dynamically but without having to eval() them.
There are probably several other solutions as well, but that was the first one that came to my mind.
Hope that helps.

Measuring pollution of global namespace

Background
I'm trying to refactor some long, ugly Javascript (shamefully, it's my own). I started the project when I started learning Javascript; it was a great learning experience, but there is some total garbage in my code and I employ some rather bad practices, chief among them being heavy pollution of the global namespace / object (in my case, the window object). In my effort to mitigate said pollution, I think it would be helpful to measure it.
Approach
My gut instinct was to simply count the number of objects attached to the window object prior to loading any code, again after loading third-party libraries and lastly after my code has been executed. Then, as I refactor, I would try to reduce the increase that corresponds to loading my code). To do this, I'm using:
console.log(Object.keys(window).length)
at various places in my code. This seems to work alright and I see the number grow, in particular after my own code is loaded. But...
Problem
Just from looking at the contents of the window object in the Chrome Developer console, I can see that its not counting everything attached to the object. I suspect it's not including some more fundamental properties or object types, whether they belong to the browser, a library or my own code. Either way though, can anyone think of a better and more accurate way to measure global namespace pollution that would help in refactoring?
Thanks in advance!
So after some of the comments left by Felix Kling and Lèse majesté, I have found a solution that works well. Prior to loading any libraries or my own code, I create the dashboard global object (my only intentional one) and store a list of objects attached to window via:
var dashboard = {
cache: {
load: Object.getOwnPropertyNames(window)
}
};
Then, after I load all of the libraries but prior to loading any of my own code, I modify the dashboard object, adding the pollution method (within a new debug namespace):
dashboard.debug = {
pollution: (function() {
var pollution,
base = cache.load, // window at load
filter = function(a,b) { // difference of two arrays
return a.filter(function(i) {
return !(b.indexOf(i) > -1);
});
},
library = filter(Object.getOwnPropertyNames(window), base),
custom = function() {
return filter(Object.getOwnPropertyNames(window),
base.concat(library));
};
delete cache.load;
pollution = function() {
console.log('Global namespace polluted with:\n ' +
custom().length + ' custom objects \n ' +
library.length + ' library objects');
return {custom: custom().sort(), library: library.sort()};
};
return pollution;
}())
};
At any point, I can call this method from the console and see
Global namespace polluted with:
53 custom objects
44 library objects
as well as two arrays listing the keys associated with those objects. The base and library snapshots are static, while the current custom measurement (via custom) is dynamic such that if I were to load any custom javascript via AJAX, then I could remeasure and see any new custom "pollution".
The general pattern you've selected works OK from experience. However, there are two things you might need to consider (as additions or alternatives):
Use JsLint.com or JSHint.com with your existing code and look at the errors produced. It should help you spot most if not all of the global variable usage quickly and easily (you'll see errors of 'undefined' variables for example). This is a great simple approach. So, the measurement in this case will be just looking at the total number of issues.
We've found that Chrome can make doing detection of leaking resources on the window object tricky (as things are added during the course of running the page). We've needed to check for example to see if certain properties returned are native by using RegExs: /\s*function \w*\(\) {\s*\[native code\]\s*}\s*/ to spot native code. In some code "leak detection" code we've written, we also try to (in a try catch) obtain the value of a property to verify it's set to a value (and not just undefined). But, that shouldn't be necessary in your case.

JavaScript helper libraries? No DOM or AJAX stuff

As I'm writing JavaScript I'm always missing some fairly basic language features that JavaScript just don't have. So is there any library that would bring such features as trim, sprintf, str.endwith and etc. functions to JavaScript ?
I just have written those functions too many times and I'm also tired of copy/pasting them from my old code. It would be nice to have some library which has those implemented and tested in one place.
Note that I'm not talking about Ajax/DOM-libraries like jQuery or Dojo and such. I know that those libraries bring some of the features that I'm talking here, but not all. And I would like to have also an environment independent library so that same library could be used with server side JavaScript .
Best library so far that I've found is php.js, but I don't like how it is polluting the global namespace. I'm also not too fond of how PHP-functions are named.
EDIT
I'm settling with Underscore.js as found out that it is very easy to extend. So I extended it with my own set of string functions. Check it out here:
https://github.com/epeli/underscore.string
Have a look at Underscore.
On the other hand, what you want seems simple enough:
function endsWith(str, end) {
return String(str).lastIndexOf(end) === str.length - end.length;
}
function trim(str) {
return String(str).replace(/^\s\s*|\s\s*$/g, '');
} // btw, should really be checking for String.prototype.trim
// ... and google "JavaScript sprintf" for a sprintf implementation
You may want to check out the Google Closure Library. It provides the following packages:
array (1)
asserts (1)
async (3)
base.js
color (3)
crypt (5)
cssom (2)
datasource (8)
date (4)
debug (16)
demos (6)
deps.js
disposable (1)
dom (28)
editor (15)
events (18)
format (3)
functions (1)
fx (12)
gears (14)
graphics (25)
history (1)
i18n (15)
iter (1)
json (1)
locale (16)
math (15)
memoize (1)
module (10)
net (29)
object (1)
positioning (9)
proto (2)
proto2 (10)
pubsub (1)
reflect (1)
spell (1)
string (3)
structs (18)
style (2)
testing (37)
timer (1)
ui (133)
uri (2)
useragent (9)
The Closure Library is open source, and Google should be using it in Gmail, Maps, Docs, Sites, Books, Reader, Blogger, Calendar and Picasa.
You may want to check out the Array and String packages to get a quick first impression.
You might want to check out MooTools. It is a very modular library with a focus on enhancing JavaScript code, not just the browser-specific JavaScript environment (DOM, AJAX, etc.).
I'm not aware of any libraries that provide such functions other than the popular AJAX/DOM libraries. Why not hand pick the functions you need from PHP.js and add them to your own namespace? You could even rename them to whatever you like.
You could check out Mootools Server.
It is a customized MooTools build
without any component relative to
browsers. Includes Class, Core and
Native Extensions. It's specifically
made for server-side environments such
as v8cgi, Rhino or SpiderMonkey.
Don't know if it suits your purpose, but it is one way to go.
Javascript substring will help you... if you dont like that way too, i'll recommend regular expressions...
Most of the time, when i need that basics functions in a very simple page, i do regex my bestfriend...
There's a list in Server-side_JavaScript
I agree with Garis. Here is a page that shows the JS String Object functions.
http://www.w3schools.com/jsref/jsref_obj_string.asp
Using the above info and such you can write your own functions using the ones above: for example. If you want to trim a string you would do something like this to allow a certain amount of characters (this one adds elipsis, you can remove that of course):
String.prototype.trim= function(num){
var str = this;
if (!num) {
num = 20;
}
if (str.length > num) {
str = str.slice(0, num);
str += '...';
} else {
str = this + '';
}
return str;
}
alert('this string needs to be shorter'.trim(10));
Output would be: this strin...

Categories

Resources