hashbang slash or no slash? [closed] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Should we do site.com/#!/blog or site.com/#!blog?
I understand there's no actual difference, however as a community of webdevelopers there should still be a conventional standard so that users can easily remember the url. If there's no already established standard, ideally someone will post an answer in favor of one and someone will post another in favor of another and one will get a lot more votes than the other...
Personally I prefer: site.com/#!blog simply because it's shorter. However I've seen many other sites use the other variant.
By the way, if your first instinct is to instruct us to not use hashbangs, then this question is not for you, please leave us alone.

You forgot the third option of site.com#!blog.
If you want to get all semantical, the question becomes "what does a '/' represent in a url?"
Does it represent a physical
directory? [site.com#!blog]
When navigating a file system, folders are separated with slashes. This is the natural behavior on the web as well, but routing has changed this.
Does it represent a hierarchy of
content? [site.com/#!blog]
outing introduced hierarchy of content. Instead of question marks and ampersands, query vars were separated with slashes creating a deep link structure based on what the developers feel is important.
Does it represent a separation of
context within your url? [site.com/#!/blog]
Stack Overflow is a good example of what I mean by "separation of context". The URL of this question is [http://stackoverflow.com/questions/5414972/hashbang-slash-or-no-slash/]. The slash between the question ID and the question title isn't there because there is a file inside a folder named 5414972. There is only one question with the ID 5414972 so it isn't necessary for hierarchy either. It was a conscious choice to use a slash to separate the ID and the name rather than using any other delimiter such as a hyphen, underscore, or even no delimiter at all. A delimiter that isn't a slash would probably make the two variables resemble one. By putting slashes on either sides of the hash bang, the url becomes:
url prefix > ajax crawling notation > the specific page
rather than
url prefix > ajax crawling notation and the specific page.
Depending on what you answer yes to (and yes, it's subjective), you will have your answer. I think it's a little silly to try and get the entire world to agree on a standard for this when we still can't decide on how we should format dates.
As for that last little comment about resentment towards the "hash bang", I think you are imagining this. Who wouldn't like "hash bangs" when they sound so similar to "flash bangs"?

One slash is like one ant: when you see it, you expect to see another.
site.com/#!/blog is correct iff there's a site.com/#!/blog/latest , site.com/#!/blog/archive/october, or something like that in our future.
Just my €0.014185.

This depends on what you're doing. If you are basically just trying to ajaxify your site structure, then IMO it makes sense to include that root /, so /#!/blog. Popups, jumping through tabs, etc can use the other structure.
I don't believe there should be a conventional standard for this. There's a reason such tools as mod_rewrite exist: there are infinite solutions to infinite problems and attempting to standardize something as complex as URLs is impossible.
Also, for anyone wondering what a legitimate use is for hashbangs: http://code.google.com/web/ajaxcrawling/

An advantage of using the slash is easier parsing. Without having to worry about whether a particular browser returns a "" or a "#" in case of a missing ("") or empty hash ("#"), you can simply take the first slash as your starting point: You don't have to worry about what's before it.
var tokens = window.location.hash.split("/").shift();
tokens becomes an array of tokens with [#]! already out of the way. Especially handy when you use a hierarchy of slash-delimited tokens in your hashes.
But of course, you should still check the stripped token to make sure it is a valid hashbang.

Related

How would I create a Text to Html parser? [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Edit: I recently learned about a project called CommonMark, which
correctly identifies and deals with the ambiguities in the original
Markdown specification. http://commonmark.org/ It has great C# library
support.
You can find the syntax here.
The source that follows with the download is written in Perl, which I have no intentions of honoring. It is riddled with regular expressions, and it relies on MD5 hashes to escape certain characters. Something is just wrong about that!
I'm about to hard code a parser for Markdown. What is experience with this?
If you don't have anything meaningful to say about the actual parsing of Markdown, spare me the time. (This might sound harsh, but yes, I'm looking for insight, not a solution, that is, a third-party library).
To help a bit with the answers, regular expressions are meant to identify patterns! NOT to parse an entire grammar. That people consider doing so is foobar.
If you think about Markdown, it's fundamentally based around the concept of paragraphs.
As such, a reasonable approach might be to split the input into paragraphs.
There are many kinds of paragraphs, for example, heading, text, list, blockquote, and code.
The challenge is thus to identify these paragraphs and in what context they occur.
I'll be back with a solution, once I find it's worthy to be shared.
The only markdown implementation I know of, that uses an actual parser, is Jon MacFarleane’s peg-markdown. Its parser is based on a Parsing Expression Grammar parser generator called peg.
EDIT: Mauricio Fernandez recently released his Simple Markup Markdown parser, which he wrote as part of his OcsiBlog Weblog Engine. Because the parser is written in OCaml, it is extremely simple and short (268 SLOC for the parser, 43 SLOC for the HTML emitter), yet blazingly fast (20% faster than discount (written in hand-optimized C) and sixhundred times faster than BlueCloth (Ruby)), despite the fact that it isn't even optimized for performance yet. Because it is only intended for internal use by Mauricio himself for his weblog, there are a few deviations from the official Markdown specification, but Mauricio has created a branch which reverts most of those changes.
I released a new parser-based Markdown Java implementation last week, called pegdown.
pegdown uses a PEG parser to first build an abstract syntax tree, which is subsequently written out to HTML. As such it is quite clean and much easier to read, maintain and extend than a regex based approach.
The PEG grammar is based on John MacFarlanes C implementation "peg-markdown".
Maybe something of interest to you...
If I was to try to parse markdown (and its extension Markdown extra) I think I would try to use a state machine and parse it one char at a time, linking together some internal structures representing bits of text as I go along then, once all is parsed, generating the output from the objects all stringed together.
Basically, I'd build a mini-DOM-like tree as I read the input file.
To generate an output, I would just traverse the tree and output HTML or anything else (PS, LaTex, RTF,...)
Things that can increase complexity:
The fact that you can mix HTML and markdown, although the rule could be easy to implement: just ignore anything that's between two balanced tags and output it verbatim.
URLs and notes can have their reference at the bottom of the text. Using data structures for hyperlinks could simply record something like:
[my text to a link][linkkey]
results in a structure like:
URLStructure:
| InnerText : "my text to a link"
| Key : "linkkey"
| URL : <null>
Headers can be defined with an underline, that could force us to use a simple data structure for a generic paragraph and modify its properties as we read the file:
ParagraphStructure:
| InnerText : the current paragraph text
| (beginning of line until end of line).
| HeadingLevel : <null> or 1-4 when we can assess
| that paragraph heading level, if any.
Anyway, just some thoughts.
I'm sure that there are many small details to take care of and I'm pretty sure that Regexes could become handy during the process.
After all, they were meant to process text.
I'd probably read the syntax specification enough times to know it, and get a feel for how to parse it.
Reading the existing parser code is of course brilliant, both to see what seems to be the main source of complexity, and if any special clever tricks are being used. The use of MD5 checksumming seems a bit weird, but I haven't studied the code enough to understand why it's being done. A comment in a routine called _EscapeSpecialChars() states:
We're replacing each such character with its corresponding MD5 checksum value;
this is likely overkill, but it should prevent us from colliding with the escape
values by accident.
Replacing a single character by a full MD5 does seem extravagant, but perhaps it really makes sense.
Of course, it'd be clever to consider creating a "true" syntax, for a tool such as Flex to get out of the regex bog.
If Perl isn't your thing, there are Markdown implementations in at least 10 other languages. They probably don't all have 100% compatibility, but tend to be pretty close.
MarkdownPapers is another Java implementation whose parser is defined in a JavaCC grammar.
If you are using a programming language that has more than three other
users, you should be able to find a library to parse it for you. A
quick Google-ing reveals libraries for CL, Haskell, Python,
JavaScript, Ruby, and so on. It is highly unlikely that you will need
to reinvent this wheel.
If you really have to write it from scratch, I recommend writing a
proper parser. With this technique, you won't have to escape things
with MD5 hashes. (I agree that if you have to do something like this,
it's time to reconsider your design.)
There are libraries available in a number of languages, including php, ruby, java, c#, javascript. I'd suggest looking at some of these for ideas.
It depends on which language you wish to use, for the best way to implement it, there will be idiomatic and non idiomatic ways to do it.
Regexes work in perl, because perl and regex are best friends.
Markdown is a JAWL (just another wiki language)
There are plenty of open source wiki's out there that you can examine the code of the parser. Most use REGEX
Check out the screwturn wiki, is has an interesting multi pass formatter pipeline, a very nice technique - see /core/Formatter.cs and /core/FormatterPipeline.cs
Best is to use/join an existing project, these sorts of things are always much harder than they appear
Here you can find a JavaScript-implementation of Markdown. It also relies heavily on regular expressions, as this is just the fastest and easiest way to parse the text.
But it spares the MD5 part.
I cannot help directly with the coding of the parsing, but maybe this link can help you one way or another.

Naming convention to use for singletons in javascript [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.
That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

Reasoning behind the default jQuery alias ($) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been thinking a lot about the way that jQuery is implemented in Javascript code. Libraries such as jQuery and Prototype bind to an alias by default; for these examples, they use the dollar sign $. (Underscore, appropriately, uses an underscore character _.)
I understand how this works. I also understand that many libraries provide a noConflict mode.
My question is, why do these libraries use an alias by default?
From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial. (Honestly - I'm a little biased, because I don't have issues typing long variable names.) I thought that maybe it was for filesize purposes, but with the proliferation of minifiers, it seems like it'd be a moot point (and a form of premature optimization).
On the flip side, the aliases seem to cause a lot of confusion for people using these libraries.
Now, I'm not really arguing against the use of aliases - I'm just wondering why it's the default option for these libraries. Currently, to avoid an alias, we explicitly have to declare that we don't want to use it. Are there specific benefits that I'm missing about the use of aliases for library calls? The only advantage that I could readily think of is if you somehow wrote cross-library code - to swap libraries, you simply swap the alias. I don't think I've ever seen this done, though.
Anyone know the reasoning behind this? I, for one, would really love to know.
"From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial."
That's what the people who designed VB thought too. "What's this
for (int i=0; i<10;i+=2){
}
Stuff! What's wrong with:
For i as Integer = 0 To 10 Step 2
Next i
So I save 13 keystrokes! That's trivial."
It's not trivial when this is what we do all. day. long.
Take the jQuery Cycle plugin: http://malsup.github.com/jquery.cycle.all.js. It has 400 instances of $. If you were to use jQuery instead of $, that would be an extra 2000 keystrokes. It's the reason why IDEs now perform autocomplete of parens, etc. etc. etc.
Using jQuery and Prototype together is not good idea. Ideally there must be only 1 javascript framework for the site, and a lot of calls to it. So the best (default) choice is to use shorthand alias for it's main function.
Anyway, if you need to use several libraries/frameworks together on the same page, and you want to avoid conflicts, you can use noConflict mode.

How specific should my classes in a game be? (Or anywhere else for that matter) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I made two games so far, one was a simple 2D MMO, and another one was a 2D portal clone with some more features.
Anyway, I noticed that my class design in those two games varied a bit:
In the MMO, I'd create a class called "Enemy", and this class would take some arguments such as image and attack_power.
In the Portal-like game, I'd create classes for every kind of object specifically, for example "Box" or "Wall" or "Doors". Then, these would take only position as an argument, and inside I'd flag them for movable, physics with true/false, and then I would have an update function which would act upon these objects.
What is the best approach to this kind of problem? How specific should I be, and should I use something completely different?
I made those games in Python and Javascript.
That depends on the purposes of each class, on the language which you're using, on what you're trying to achieve, the specific problems you're trying to solve, and a zillion other factors - every problem and every program is different.
I'd recommend doing some research around the SOLID prinicples of OO design, these principles are more like guidelines than rules, but understanding them and being able to apply them to a real problem might help you achieve 'good' class design - http://davesquared.net/2009/01/introduction-to-solid-principles-of-oo.html
There is no "best" approach, since there are no universal right or wrong ways to solve a problem, and a perfect solution is not always possible or desirable when you factor in other real world issues which you might come across along the way.
The kinds of questions you might think about asking yourself could be along the lines of
What does my program actually do? Often, the most useful classes emerge when you start to think about the way your program works. For example, your movable Box class may end up doing very little to the point where it's easier to represent it as a simple struct, but you might find a use for a BoxMover class which is packed full of 'move' logic, and knows how to move Boxes around.
How do the different entities in my program behave? You don't mention very many details about your classes, so only you would know whether they do different things, but if you end up with dozens of almost-identical classes (particularly where the differences are restricted to data) then you may have gone too far.
What do I actually want to do with the classes? Its important to think about interfaces; the focus of OO design is more about the way your classes are used than the data which your classes store. (e.g. contrary to popular belief, a Square may have absolutely nothing in common with a Rectangle). Likewise, a class which has nothing more than single-line get-set functions for its interface is probably not making your life any easier, or bringing you any closer to finding a good solution.
What is the best approach to this kind of problem?
Some game developers would say that OOP is not the type of programming you would use for games. They would have a global data store, and use procedural code to access the global data store.
You're the only one who can really answer this question. Did your classes help or hinder your game programming?
How specific should I be, and should I use something completely different?
As specific as you need to be to model the game. In my opinion, since you finished the games, you had a good model. As you get more development experience, you'll have seen more models that you can use.

JavaScript naming conventions [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.
That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

Categories

Resources