Intellisense on object using special comments - javascript

In Sublime or VS Code you can define a special comment (DocBlockr or JSDocs as example) that Intellisense will recognize en give you smart tooltip functionality.
I have a function which takes an options parameter. This is an object and can have several properties that could contain functions, strings, ints etc. An example would be:
function foo(options){
options = options || {};
if(options.foo){
console.log(options.foo);
}
if(options.bar) {
console.log(options.bar());
}
}
foo({foo: 'foo', bar: function(){return 'bar';}});
I could add a DocBlockr comment, but that would only yield a tooltip that shows it needs an object.
Is it possible to make some sort of definition of that options object, so it would popup using intellisense?

For Sublime Text 3, you can use my JavaScript Enhancement plugin (you could find it also on Package Control) that will turn it into a JavaScript IDE like (It uses Flow under the hood). In your case, using Flow type annotations, you could use this code to get what you want:
//#flow
function foo(options /*: { foo: string, bar: function} */){
options = options || {};
if(options.foo){
console.log(options.foo);
}
if(options.bar) {
console.log(options.bar());
}
}
foo()
So, on the Sublime Text 3 editor, you will get something like this:
also on multiple lines (/* : need to be on the same line of the parameter):
Also, the plugin offers not only a smart javascript autocomplete but also a lot of features about creating, developing and managing javascript projects (real-time errors, code refactoring, etc.).

Related

Why does Eclipse not un-indent braces in JavaScript?

I have pored over the formatting settings on Eclipse for hours and found no solution to this problem:
Video of issue
When I type the opening curly brace on the line immediately following an if, else or function line the ending brace is automatically added, but neither conform to my formatting rules (i.e. the braces should be aligned with the if, else or function text).
The way it looks:
if (a)
{
}
The way it should look (and does after running the formatter):
if (a)
{
}
I would chalk it up to a deficiency in Eclipse except for one thing: when editing PHP, Java or C++ code it works as I'd desire; the braces are un-indented appropriately.
It's because Javascript formatting is exactly like that.
The if statement standards:
if (a) {
// your code
}
And if you use an Array of Objects, for example:
var arr = [
{ prop: 'value', prop2: 5 },
{ prop: 'value', prop2: 5 }
];
It's working exactly as it was intended to. Take a look at this Javascript's style guide.
This is just because the formatter is not applied after you write the code. Here is the way to do it.
On Eclipse, go to Window>Preferences
Under JavaScript>Code Style>Formatter, create a New Profile.
On creation of new profile or on edit, you would be shown with a window to change the format style. Go to Braces.
For Blocks, choose Next Line
Click OK. Confirm the profile and click OK.
Now, after you write the following:
if (true)
{
}
Use formatter to make changes for you, usually by Ctrl+Shift+F or from menu by Source>Format. You may apply formatting to selected piece of code too.
Update
Once you have the above setting, go to Window>Preferences>JavaScript>Editor>Save Actions, enable Perform the selected actions on save and Format source code which would make the this operation better.

how would i go about creating a Command Line Interface in javascript?

How would i go about creating a CLI like interface in JavaScript?
What i mean is an example like this cmd.fm
I work with a lot of jquery and forgive me if i'm wrong but the only idea i have as to how to build this is by getting what the user typed in and using the switch function and checking if the command exists and then executing the command.
It all depends how complicated you need the commands to be!
I'll assume you you know how to render the page in lines, and capture keypresses (simplest way would be to style a text input, and listen for the return key, rather than trying to decode a key event).
I'd build a data structure like this (in JS):
var commands = {
"doThing": function(args) { /* do stuff with the args */ },
"doAnotherThing": function(args) { /* do other stuff with the args */ }
}
The user would type:
> doThing foo bar blah
In this simple example, you'd split the line by space characters, and treat the first element in the resulting array as your command name. You'd then check to see if commands[commandName] exists, and if so, run it: commands[commandName](args);
If you want to do something more advanced, you're going to need to write a tokeniser (technically the split on space is a simple tokeniser) - then things get more complicated, but the same basic method applies.
I hope that's enough to get you started.

How do you display translated strings using i18next on js alerts?

We're developing an app that utilizes html/css/js, and it uses i18next to display translated strings.
In order to display translations, I embed an attribute within a tag. For example:
利用規約<label for="checkbox2" data-i18n="text_agree">に同意する</label>
In addition to this, the app uses a javascript file to replace strings with translations. For instance, the above code corresponds with:
en: { translation: {
text_agreement: 'Agree to EULA'
} }
This method of translation works for HTML tags. What I don't know is how to translate strings within js code. For instance, how would I display translated strings for this?
element.alert('なまえを記入してください。');
Help would be very much appreciated.
The initialization function gives you a function to translate your strings. ;)
You can 'put' this function to the window object, so you can use it everywhere in your code.
i18n.init(function(t) {
window.t = t("Your string here");
});
// ... more code
// Now you can use window.t to translate
element.alert(window.t('Your string'));
But note that it's asynchronous (!), so it could happen that the console says, that t() is undefined.
So first initialize i18next and then use window.t();
Also have a look at the documentation: http://jamuhl.github.io/i18next/pages/doc_init.html

Compound Javascript Elements

I've got this page I'm doing some tests in Javascript and jQuery: JS Tests
I've got a few questions on how to create, not sure if this is right term, but compound controls via Javascript. In something like Flash, you'd create the Object class, have the getters and setters, draw your images, etc. In JS, it seems to be a very different thought process. My main question is How do you create multiple elements with getters and setters to be rendered, filtered, and interacted with in Javascript?
The main code regarding this example sits with:
var html = (function(){
// var FRAG = $(document.createDocumentFragment());
htmlBox = $(document.createElement("div"));
var eTitle = $(document.createElement("h4"));
var ePrice = $(document.createElement("p"));
// set class first
htmlBox.addClass("box")
htmlBox.css({
backgroundColor : color
})
// set text values
eTitle.text(title);
ePrice.text("$" + price);
htmlBox.append(eTitle)
htmlBox.append(ePrice)
return htmlBox;
})();
... inside the Box() class. If someone could take a look at the source and let me know what isn't quite right, that'd be great.
EDIT
Here's the final result for this example. Some logistics to work out, but what I'm after.
http://geerswitch.in/tests/obj/
As for the jQuery creating nodes, the built in JS version works fine for this, and some research on Google shows that the non-jquery way is faster in most cases anyway (and looks worse, imo)
You're doing it almost right. You've created a Box class to represent your higher-order UI element, you're instantiating it for each element, and your main program is manipulating the elements through its interface. The only thing you're missing is the split between the public interface and the private implementation. There's nothing to prevent me from doing myBox.price += 10 right now, even though the Box interface clearly implies that price should be set at construction and never modified.
JavaScript doesn't have visibility modifiers like "private" and "public", but you can create the same effect yourself. Check out Douglas Crockford's explanation for the details. Crockford is an opinionated genius when it comes to JavaScript, and he's the brains behind JSLint and JSON.

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