I have found a JavaScript gallery.
When I view the JavaScript code, I really don't understand how to write code in this style. What is the style called? Where can I find documents related to it?
Note: what i want to know is the way that define Class in this code
(function (){ ... })(window)
what is style ?
jQuery Mobile. http://jquerymobile.com/
The reason you can't read it is because they are compressing the code which changes around variable names and makes the code as small as possible. This helps the code load faster.
jQuery.com
Based on your question, it seems you're not familiar with jQuery. jQuery is a JavaScript framework written in JavaScript. It is most useful for it's selector/filter capabilities, being able to pull objects of objects using something like $('div'); (or jQuery('div');), which would pull all the divs from the page. Using dot notation, you can perform methods on those returned objects.
(function (){ ... })(window)...
is both an unnamed function definition and call, passing in the window object. It's sort of like function foo (){...} foo(window), only you don't store the definition in variable foo and you need to wrap the definition in parentheses for syntax recognition in order to call it with the trailing parentheses.
For more advanced JavaScript topics, google closures.
Developers typically minify their javascript before deployment. This makes it hard to understand. but typically you can go to their website if they are willing to share the code
Try to get a look at the github website of the app.
Related
I'm just in the process of studying jquery. And I have the following question. I have a page that relies on js for ajax and reporting to user.
So basically I have created a file with $(function() {}) construct. Inside of that construct I'm using standard jquery functionality to work with my modal windows, smth. like
$('.text-danger').hide();
$(".btnajax").click(function() {})
But now I want to work with another modal window at the same page, not at the same time. What would be a better way:
Continue inside the same anonymous function construct and keep working with IDs and Classes when referencing the specific buttons and form actions?
OR
Create new anonymous function construct? OR
Create named functions and call them when needed?
I would like to build correctly from the scratch, so I don't have to redo everything later when I'm better with JS.
Thank you in advance.
Continue inside the same anonymous function construct and keep working
with IDs and Classes when referencing the specific buttons and form
actions?
This is not a good idea as every time you would do something with the buttons or the form it would access the DOM which is unnecessarily expensive.
Create new anonymous function construct?
Actually, anonymous functions are rarely a good idea as they make your code hard to read. Imagine there are no named functions and everything is anonymous. That would require the reader to always get the context in order to quickly understand what the function is doing
Create named functions and call them when needed?
Especially when reusing that functionality, it's a good idea. But also in terms of readability it is good because the name of the function describes what is happening so when someone (you) read the code again after some time, will know hat is happening without studying the body of the functions.
Apart from that:
I would like to build correctly from the scratch, so I don't have to redo everything later when I'm better with JS.
I can tell you: you will not avoid rewriting parts of your code once the requirements change. That is just what coding is about. You can not foresee every required change to your application. If you try to then you end up having an over engineered code. Instead, you should follow YAGNI.
Generally speaking, for everything that's more than just 5 buttons and a form, a JS file with jQuery is not the way to go. Those times are over. Switch to something that gives you a separation of concerns between model, (model)view and controller.
I am learning jquery and started my first attempt at building a form validation script based on what I know so far (which isnt much).
This is really only the Radio button portion of the validation script, but I thought I get on the right track -coding wise- before I went too far. There are some fundamental issues that I know need addressing.
The Script (jsFiddle): http://jsfiddle.net/pkdsleeper/xNt5n/
The Questions:
a. How best to remove the global variables using
b. jsLint recommends "use strict", so I added it, but im not sure what it does.
c. any good refs?
d. Generally, feel free to rip this code apart (cuz I AM trying to learn) but
please explain my errors in noob-speak :)
Thanks In advance
sleeper
a. How best to remove the global variables using
Wrap it in an anonymous function and assign it to the form as a submit listener.
b. jsLint recommends "use strict", so I added it, but im not sure what it does. any good ref's?
Don't bother. It's just a buzz-word for those trying to be hip. You can't use strict mode features on the general web because way too many browsers don't support them. You can use it with otherwise compliant ES 3 code, but it's only useful as a debugging tool for errors that should have been found during testing anyway (e.g. calling constructors without new).
No c?
d. Generally, feel free to rip this code apart (cuz I AM trying to learn) but please explain my errors in noob-speak :)
> $rdoGroup = [], // an empty array which will be used to hold
You seem to be using $ to indicate a variable that references a jQuery object, but $rdoGroup is just an array. That may be confusing later.
> $rdoGroup.push($(this).attr("name"));
The $ function is very expensive, don't use it if you don't need to. Standard HTML attributes are available in all browsers as DOM properties, so:
$rdoGroup.push(this.name);
Is up to 100 times more efficient, depending on the browser.
> for (i = 0; i < $rdoGroup.length; i++) {
> if ($rdoGroup[c].toString() !== $(this).attr("name").toString()) {
The values assigned to $rdoGroup are strings, calling their toString method is redundant.
As above, use this.name. The name property is a string, so no need for toString.
I think the exercise would be easier without jQuery, which seems to be getting in the way far more than helping. If you are trying to learn javascript, I'd suggest that you learn javascript without using any library.
Once you are reasonably confident with using javascript, then you are far better equipped to use a library for the things the library is good with, and not using it for the things it isn't good at.
a. Well, you got rid of the globals pretty well. But as your code looks right now, you can wrap the entire thing in (function(){ ... all your current code in here ... }()) and leave nothing behind in global scope.
b. For "use strict" see this question
c. typeof questions['c'] === "undefined"...
d. Currently, your js is too tied to the markup (html) and vice-versa. If you add or remove something in the form, you'll have to edit your js. If you want to use the validation for another form, you'll have to start the whole thing over again.
Validators are prime candidates for "unobtrusive javascript"/progressive enhancement (here's some material: A List Apart & Wikipedia). Basically, your markup (the html), your styling (the css), and your "behaviors" (the javascript) should all be separate, so they can be changed independently. Here's something you can try:
Add a class name to your form(s) (e.g. "validate")
Set up your js to look for form.validate when the page has loaded
For each form it finds, add a submit event handler
When the handler fires, you search the given form for inputs with various other class names you specify (e.g. "required" or "phone-number" or whatever). The class names tell your code, what kinds of validations should be done. For instance, <input type="text" class="required zip-code"> would mean that a) it's a zip-code, and b) it's a required field.
If there are any validation errors, cancel the submit and alert the user somehow. Otherwise, let the submit proceed.
That's obviously a very rough outline, but I'm not gonna write your code for you :)
The point is, that if you ever need more forms or different forms or something like that you have a generic validation script, and all you need to do is "mark" the inputs with the appropriate class names.
All that being said: There are tons of jQuery plugins out there that do form validation. It's definitely still a good exercise to write one yourself, but it's also a good idea to look at what's already there, and how it works. Don't look at the code right away, but read up on how those validators are used (e.g. do they use class names or something else?) and try to figure out how they work.
I am writing a lot of Javascript code these days and I am making good use of JQuery. I am wondering if it is considered evil to create strange global variable names. I know that a lot of Javascript frameworks such as JQuery use the dollar character; $, but that greatly simplifies code as it can do so many things.
I am thinking of creating a $$ global variable in my code which would be defined as below:
function $$(tagName)
{
return $('<' + tagName + ' />');
}
The benefit of this is that my code has (1) abstracted out the logic of creating a new element, (2) made the code more concise, and lastly (3) I can almost create html elements within Javascript as concisely as html itself because JQuery has so many other selectors to chain off:
$$('div').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$$('ul').append(
$$('li').text('first'),
$$('li').text('second'),
$$('li').text('third')
);
);
Do you believe the above approach of creating $$ is legitimate or would you regard it as a no-no?
This is of course an opinion, but if I was new to your application, I would have to go look up what that function does in order to understand the code. Also, the function is simple enough that other developers would likely not bother using it, so you'd end up with a mix of techniques which is confusing.. And really, is this so bad?
$('<div/>').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$('<ul/>').append(
$('<li/>').text('first'),
$('<li/>').text('second'),
$('<li/>').text('third')
)
);
I prefer a clear, meaningful, self-documenting name over JQuery style $ any day of the year.
Also I find it confusing that the same name has different meanings depending on the context it is used in. Like $ in JQuery or this in javascript and will avoid using them as much as I can.
EDIT: In my opinion it should be up to the user to decide whether he wants to use a shorthand name for the framework he uses. It requires only one line of code:
var $ = jQuery;
When I look at pages with jQuery in it, all I see is a big mess flooded with dollar signs that do different things in different places. If the library had used meaningful names for the functions it offers it would be a lot easier to decipher other peoples code. Javascript is already difficult and unreadable as a language itself.
Personally I don't think it's adding that much functionality to account for the "namespace pollution", not to mention the possible confusion of people reading your code that aren't familiar with your method.
It's just saving a trivial couple of characters on each invocation of the method, so in that respect it can only be considered a form of syntactic sugar. And the cons outweigh the pros, in my opinion.
It would be good if you take a look at the construction of e.g. jQuery .
It does'nt work with several global variables/functions, there is only one global object required "jQuery" .
Everything else are properties of this one object, so they have minified naming-conflicts.
In the special case of $$ : maybe sometimes you need to work with prototypejs, but you cant, because prototypejs already uses $$.
So my suggestion: create one global object, your own "library" , give it a distinct name, and let your functions/variables be member of this object.
I don't think it's "evil" in general, but if you're going to pop something into the global namespace with a "distinguished" name it might be better if it were something a little more interesting. For your purposes, given your example code, the jQuery micro-template system would probably be a better approach anyway.
I want to know if there exists a tool to help in reversing a compressed javascript that has obscure variable names. I am not looking for a pretty-printing beautifier, but for a tool that actually knows how to change & propagate variable name choices.
Let me be more specific :
- some of the functions belong to the 'public' API and i want to impose readable argument names in their prototypes
- there are intermediary variables for document, window and other browser idioms
I would like to give this knowledge to the tool and then let it create another javascript where the knowledge would have been correctly propagated.
thanks
Jerome Wagner
Sounds like maybe you need a javascript refactoring tool. Something that could refactor javascript, i.e take a javascript file and rename variables.
Here are some plugins for IDE's:
http://www.brics.dk/jsrefactor/index.html
http://www.jetbrains.com/editors/javascript_editor.jsp?ide=idea#JavaScript%5Frefactoring
If you are trying to do this programatically, then this may not be the best solution for you.
Pardon me for giving you a confusing title on this problem.
I'm really confused and i don't know how to put it in other words.
So here is what I what to accomplish.
I am making a Custom Javascript Object to store data.
I have automated this process and inserted each instance of the object into an array.
I am making a loop statement to invoke the unique property value of each instance of the object.
When I want to use an expression, the property name of the object would be variable since i don't know which one it is.
Basically I need to incorporate a string value into the prototype expression.
e.g
document.getElementById('text').style."fontsize"=value;
since I cannot do this directly, i thought possibly I could use the eval function:
eval('document.getElementById("text").style.' + buttons[i].cssvalue + '="39px";');
but this still doesn't work.
Can this be fixed or ss there an alternative way to accomplish this?
If there are some unclear stuff, please point out and I will try to elaborate.
Thanks in advance.
In javascript you can access properties of an object using this notation:
document.getElementById('text').style["fontSize"] = value;
So your code might be:
document.getElementById('text').style[buttons[i].cssvalue] = "39px";
I don't know if this helps or not but I made a utility function which I published to npm which allows you to put in a class name / element along with the CSS properties you're looking at getting. This will then return a Javascript object with the CSS properties and their values within it.
You can find it here on Github and NPM:
GitHub: https://github.com/tjcafferkey/stylerjs
NPM: https://www.npmjs.com/package/stylerjs
First thought, look at a Javascript library or framework like JQuery or Dojo they probably have already solved the problem you are looking at. We use JQuery at work but I prefer Dojo's design but it is more targeted at large web applications.
Other than that Jakub's solution should work.