JavaScript: Enough BS
Billybob

I'm wasting gobs of time struggling with JavaScript. Is there anyway to have JavaScript tell me all the attributes of a given object? In particular, I need to know what stuff the event object has, because I seriously can't figure out what it does and doesn't have in Firefox.

Or a decent online documenation of what these objects have and don't have under various browsers. w3schools lists some things, but it sucks when it comes to telling me what each browser does and doesn't have.

Marcello
for (var i in o) {
  println("o."+i+"="+o<i>);
}

But I recommend using venkman's debugger thing, it shows a whole tree and lets you set breakpoints and whatnot.

Marcello

ReyBrujo

Indeed. You can install it as a extension for Firefox.

Matthew Leverton
Billybob

Thanks!

Another question while we're here. JavaScript is being its same old self...which is being a pain in the butt.

    var html = "<div style='position: absolute; width: 0px; height: 0px; border: 1px solid black;' id='div-id-" + div_id + "></div>";
    e.src.innerHTML = html + e.src.innerHTML;

Doesn't work right. For some really odd reason JS has decided to convert SOME, but not all, of html's string into html entities. Yes, only some. In particular everything after div-id= gets htmlentities run on it, up until the end of the html string. Everything that was originally in e.src.innerHTML is fine...well except for the fact that it's all corrupted now that there's broken HTML at the top of it.

e.src is:

if(event.target) e.src = target;

Part of a left mouse down event. In this case it's pointing at document.body.

Any ideas what's up?

Marco Radaelli

Aren't you missing a ' somewhere after div-id-?

Billybob

That is a DARN good point. Thanks!

Marco Radaelli

Hehe, these are the kind of things which make programming fun :)

Ceagon Xylas

Javascript is BS, dude.
No offense to any lovers of the code [even though I've only met one in my entire life, so I don't think there are many of you] but it is one of the worst languages I've ever programmed in.

Marcello

Then you clearly know nothing about the language. What's so bad about it? Disregarding crap implementations of it, of course.

nonnus29
Quote:

Javascript is BS, dude.
No offense to any lovers of the code [even though I've only met one in my entire life, so I don't think there are many of you] but it is one of the worst languages I've ever programmed in.

Don't confuse javascript with DOM weirdness either. Javascript (or the language defined by ECMA-262) is actually a really slick little language when you consider it on it's own.

CGamesPlay

Another important technique:
println(uneval(object));

Ceagon Xylas

Well I guess now I've met 3. ^.^

CGamesPlay

You're confusing "people who love JS" with "people who posted since your last reply"...

Ceagon Xylas

Haha well they defended it pretty strongly... Specially Marcello.

ReyBrujo

JS is good enough for what it needs to do. [Now, let's add fuel for the flame war] I believe it is not as "loved" because there aren't many good IDEs. [A bit more] And everyone knows nowadays programmers without an IDE are end users. [That last one was enough I believe ;)]

kentl

The biggest "flaw" of JavaScript IMHO is that Microsoft went the JScript route and thus made cross browser compatibility harder. Apart from that, language wars are always silly per definition. Use the right tool for the job.

Billybob
Quote:

I believe it is not as "loved" because there aren't many good IDEs

I disagree. I love PHP, and don't use any ides for it other than SciTE, which I use for every other language. An IDE makes a language easier to use by providing you with some helpful tools like parameter info and such, but it's not going to help a broken language.

Quote:

Apart from that, language wars are always silly per definition. Use the right tool for the job.

Except for the fact that JavaScript is the only tool for the job.

ReyBrujo

You are forgetting vbscript ;)

Marcello

How can someone love PHP? What's so great about it? The syntax is ugly, the library is convoluted and unorganized, the class system is crap (maybe php5 is ok, but geez!). I'm slowly making the switch from PHP to JavaScript, and every second I am amazed at how much easier and faster it is to develop in.

Marcello

Thomas Fjellstrom

I'll be using ECMAScript in my GUI applications.. TrollTech has a nice library called QSA (Qt Script for Applications) which is an implementation of ECMAScript thats tied heavily into Qt, Anything you can do in C++ with Qt, you can do in QSA, and then some.

kentl
Quote:

Except for the fact that JavaScript is the only tool for the job.

Did I say it wasn't? (Answer: No) :)

BAF

How can you use JavaScript in place of PHP? Unless you're using ASP or something.

Marcello

Like this.

kentl

I would like it to be possible to create a bitmap using JavaScript and set pixels within it, which AFAIK isn't yet possible.

BAF

Marcello - looks interesting... how does it compare with PHP (as far as core functionality goes)?

Matthew Leverton

It looks like it uses Java for library support. For core support, I would assume it is pretty much standard JS.

There is no perfect language. In fact, when it comes to web coding, no language is enough. You need good coding practices and a framework that knows about the internet. PHP doesn't force the former and certainly doesn't provide the latter.

That said, I enjoy working with PHP using my framework and see no reason to switch. I won't gain any measurable productivity using someone else's framework or a different language. But I won't touch another person's crap PHP code for any price (that anyone offers...)

So the nice thing about some of the other web frameworks is that they force a somewhat intelligent design upon the ignorant coder, but I don't really think it's the language itself that provides the main benefits.

Marcello

Kent: it is in firefox 1.5+ with the <canvas> thing.

BAF: Depends how you look at it. It can load any java library, so technically its "core" functionality is quite broad. I haven't played enough with it to really say. I suppose it depends what functionality in PHP you use. All the standard stuff is there (get, post, cookies, sessions, email, image handling, ftp, file access, database access), and it uses OO rather than a c-style api.

As far as I can tell all or most of the core API is actually written in JavaScript itself, to give you an idea how versatile it is.

I haven't used it enough as of yet to give a full report, though.

edit: I think JavaScript on the server-side makes a lot of sense if you're going to be heavily using JavaScript on the client side, you can share code and modules (form validation, server/client based template engine, anyone?).

It's worth noting that Helma does provide a number of framework features for you off the bat, such as database abstraction (which I don't plan on using myself, since I'm using SQueaL as an alternative), template support, and a certain level of hiearchy control (which again I'm not using, thanks to SQueaL).

Marcello

kentl

Marcello: Cool! Something new to play with!

CGamesPlay

What do you mean,

Quote:

a framework that knows about the internet

Matthew Leverton

I mean the web in particular. What is the difference between PHP as a CLI and as an Apache module? Almost nothing. You basically just get a $_REQUEST array. PHP doesn't think outside the box at all. It's just about adding more and more 3rd party libraries and adding a few helpful functions now and then.

PHP doesn't do anything to provide a framework for your web application. It's great for a web page, it is bad for a web site. To be good for a web site, it needs to provide ways to gracefully handle application tasks. The $_SESSION array is about the only thing it does provide.

Now I know that all of this stuff can be done within PHP as layers of classes (because I do it), but considering PHP is supposed to be a "web language," I think it should officially support a standard framework. Also, PHP as a language is not very elegant if you want to add these things yourself.

Some examples: using -> and $this is hideous and the absence of named parameters (by the caller) means you must pass things using an ugly array() syntax. In the case where a function has a huge number of possible parameters, all being optional, which do you prefer?

1function func1()
2{
3 extract(get_named_params()); // there are other ways of doing this...
4 print "$foo $bar";
5}
6 
7func1(foo: "hello", bar: "world");
8 
9function func2($params)
10{
11 extract($params);
12 print "$foo $bar";
13}
14 
15func2(array("foo" => "hello", "bar" => "world"));

For the most part, I like the PHP language. It's not filled with magic and it's quite powerful. (A number is a number and not some stupid object just for the sake of purist OOP...) But it's missing many simple things that even JavaScript does nicely (like short-hand array/object syntax).

I'm not alone with my thoughts... Zend recently announced the "PHP Collaboration Project." Hopefully it begins to seriously address some of these fundamental shortcomings to using PHP for building web applications. To quote from them, emphasis mine:

Quote:

Anyone building industrial-grade PHP applications knows there's more to a well-designed, robust, scalable, secure PHP application than the language itself. The open source Zend PHP Framework is a body of PHP code that provides developers with the essential structure and services for an industrial-grade PHP Web application.

We also think that it's very important this framework embody the "extreme simplicity" mindset that PHP itself exemplifies. We want to deliver a framework that helps solve developer problems and speeds development; not one that's overly complex and heavyweight.

With this framework, PHP developers will have a big "jump start" when developing Web applications, with the ability to focus more on unique functionality and less on the plumbing and infrastructure that all applications share.

I don't know how it will turn out. Hopefully it will remain simple and get people away from writing the standard filthy PHP code. Obviously it won't address some of the shortcomings to the PHP syntax, but maybe it will help standardize the basic tasks.

Marcello

For the record, a number isn't an object in JavaScript either. It's a value, and gets passed by value, not by reference, as objects are.

I find the amount of syntax in a language is a good indicator of how good it is. More is not better. The fact that PHP has $ in front of every variable isn't a good thing, the fact that you can refer to variables in literal strings isn't a good thing. The fact that you have to use -> for class membership isn't a good thing. Hell, even c++ doesn't use -> unless it's a pointer (but shouldn't you be using references anyway?).

The array thing is what really started to bug me though, take, for example:

1/**
2 * Constructs a new SimpleXML file
3 * @param file a URL string in a format that Helma getXmlDocument() prefers
4 */
5function SimpleXML(file) {
6 // Get JDOM document
7 var jdom = (new Packages.org.jdom.input.DOMBuilder()).build(getXmlDocument(file));
8
9 // Recursive function to traverse the hierarchy
10 (function(o, node) {
11 // copy tag name
12 o.name = node.name;
13
14 // Get children
15 var children = node.children;
16 if (children.size() > 0) {
17 // Only make a children array if there are any (good idea?)
18 o.children = new Array();
19 var i = children.iterator();
20 while(i.hasNext()) {
21 var newo = new Object();
22 o.children.push(newo);
23 // Recurse on child element
24 arguments.callee(newo, i.next());
25 }
26 }
27
28 // Get attributes
29 var attributes = node.attributes;
30 o.attributes = new Object();
31 var i = attributes.iterator();
32 while (i.hasNext()) {
33 var attribute = i.next();
34 // Store in associative array style
35 o.attributes[attribute.name] = attribute.value;
36 }
37 })(this, jdom.getRootElement()); // initial values
38}
39/**
40 * toString
41 * @returns a string representation of the SimpleXML object
42 */
43SimpleXML.prototype.toString = function(node,indent) {
44 if (arguments.length < 2) {
45 node = this;
46 indent = " ";
47 }
48 var string = "["+node.name+" attributes = "+uneval(node.attributes);
49 for (var i in node.children)
50 string += "\n" + indent + arguments.callee(node.children<i>, indent+" ");
51 return string+"]";
52}

And my original code in PHP:

1<?
2 
3class XMLFile extends _XML {
4 function XMLFile($path) {
5 if (!($fp = fopen($path, "r"))) {
6 trigger_error("Cannot open XML data file: $path",E_USER_WARNING);
7 return false;
8 }
9 
10 $this->setup();
11
12 while ($data = fread($fp, 4096)) {
13 if (!xml_parse($this->xml_obj, $data, feof($fp))) {
14 trigger_error(sprintf("XML error: %s at line %d",
15 xml_error_string(xml_get_error_code($this->xml_obj)),
16 xml_get_current_line_number($this->xml_obj)),E_USER_WARNING);
17 xml_parser_free($this->xml_obj);
18 return false;
19 }
20 }
21
22 return $this->finishInitialization();
23 }
24 
25}
26class XMLString extends _XML {
27 
28 function XMLString($data) {
29 $this->setup();
30 if (!xml_parse($this->xml_obj, $data, true)) {
31 trigger_error(sprintf("XML error: %s at line %d",
32 xml_error_string(xml_get_error_code($this->xml_obj)),
33 xml_get_current_line_number($this->xml_obj)),E_USER_WARNING);
34 xml_parser_free($this->xml_obj);
35 return false;
36 }
37
38 return $this->finishInitialization();
39 }
40
41}
42class _XML {
43 
44 var $output = array();
45 
46 function setup() {
47 
48 $this->xml_obj = xml_parser_create('UTF-8');
49 xml_set_object($this->xml_obj,$this);
50 xml_set_character_data_handler($this->xml_obj, 'dataHandler');
51 xml_set_element_handler($this->xml_obj, "startHandler", "endHandler");
52 xml_set_default_handler($this->xml_obj, "defaultHandler");
53
54 return true;
55 }
56 function finishInitialization() {
57 xml_parser_free($this->xml_obj);
58
59 return true;
60 }
61 function defaultHandler($parser, $data) {
62 return $data;
63 }
64 
65 function startHandler($parser, $name, $attribs){
66 $_content = array('tag' => strtolower($name), 'attributes' => array());
67 if (!empty($attribs)) {
68 foreach ($attribs as $key => $value)
69 $_content['attributes'][strtolower($key)] = $value;
70 }
71 array_push($this->output, $_content);
72 }
73 function dataHandler($parser, $data) {
74 //$data = trim($data);
75 if (!empty($data) && strlen(trim($data))) {
76 $_output_idx = count($this->output) - 1;
77 $this->output[$_output_idx]['children'][] = $data;
78 }
79 }
80 function endHandler($parser, $name) {
81 if (count($this->output) > 1) {
82 $_data = array_pop($this->output);
83 $_output_idx = count($this->output) - 1;
84 $this->output[$_output_idx]['children'][] = $_data;
85 }
86 }
87 
88}
89?>

They both actually generate the exact same thing, and never mind on the generating part, but once you've created them, it's a hell of a lot easier to do xml.children[0].attributes.name than $xml->output['children'][0]['attributes']['name']

I also ported my SQL Schema class from PHP to JavaScript and it was just kind of a 'wow, what have I been missing' thing.

Marcello

spellcaster
Quote:

Javascript is BS, dude.

Well, if the negative comments would come from other people that our prooven geniuses, I'd probably tempted to explain to them the difference between the scripting language, the host application, the impact of the exposed interfaces and similar related topics.
But taking into account the known talents of the people in question and the excellence prooven in this thread alone ... all I can do is watching them in awe.

/me bows.

Billybob
Quote:

the fact that you can refer to variables in literal strings isn't a good thing.

I find it extremely helpful and it makes the code easier to write, and shorter. Certainly not a necessary feature though.
Just as I find having a string concat operator extremely helpful. I mean:
String(value_x) + String(value_y)
is just fine and dandy, but it's much simplier to write:
value_x . value_y

Ya know, it's things like that that make a language "fun" to use, as opposed to a bore/pain to use. On the string concat thing, if you didn't have that, you'd hit that age old problem of trying to concat two values and ending up adding them instead. Of course what one finds nice is entirely a personal thing, which I guess raises the question; could a language contain all the things 90% of people need? Or are we forever split between PHP/JS, C++/Java? It's kind of hard to say considering that nobody ever improves these languages like they improve other opensource applications.

Personally, I've been thinking about modding a new version of GCC, because I'm getting sick and tired of some things in C++. A static constructor or static class would be wonderful. Truth is, though, I'm scared of GCC! I have no idea how easy it would be to modify. And then of course nobody would be able to compile my code unless they had my version of GCC.
And I think that's the reason why a lot of languages suck. Nobody wants/can get in there and modify it to suit their tastes and therefore improve the language. Maybe not all mods get thrown into the official language, but at least languages would evolve faster.

kentl
Quote:

A static constructor or static class would be wonderful.

Could you explain some more? I'm afraid I'm missing what would be wonderful about it.

Matthew Leverton
Quote:

For the record, a number isn't an object in JavaScript either. It's a value, and gets passed by value, not by reference, as objects are.

I wasn't referring to JavaScript. I don't mind working with it at all. The problem with JS is that most people use it when having to deal with browser incompatibilities, so they stay clear away.

Quote:

xml.children[0].attributes.name than $xml->output['children'][0]['attributes']['name']

Well, you are using PHP4's dated XML handler. There are two better alternatives with SimpleXML and DOM. The latter is very similar to JS's, as it's based on the W3C standards.

Marcello

True. I haven't played with PHP5 much as of yet, but I don't recall SimpleXML making what I said terribly shorter. JavaScript 1.5 (I think that's the version) added E4X, a literal xml syntax which is kind of interesting, but I haven't messed with that either, as Helma is still using the previous version of Rhino (it's not yet compatible with the new one).

Quote:

String(value_x) + String(value_y)

Can't say I've ever needed to do that, but you could just do "" + value_x + value_y In general I'll have a character in there, though, so it'll be more like value_x + "," + value_y.

Marcello

Matthew Leverton

The other direction is more common.

var x = document.getElementById('foo').value; // 42
var y = document.getElementById('bar').value; //  1
var z = x + y;
// z should be 43!
alert(z); // 421 :O

Of course you can avoid the problem with casting, but PHP has the edge here with the . operator. But, then it can no longer be used with objects. :P

Someone wrote a patch to optionally change . to _ and -> to . but it was rejected. I'm actually tempted to see if a "zend extension" shared object could do just that, because I use classes extensively now...

That along with the $this pointer are the two most fundamental annoyances with PHP. When PHP was less about classes, it wasn't a big deal. But it is annoying now.

Marcello

True, but that's an inherent problem with loose type languages. Explicit casting helps, but also, in general you should be storing data in the correct format to begin with, if something is stored as a string no matter what, I think an explicit cast is fairgame (and you might want to go a step further and validate the cast is possible).

Still, overall, I've been preferring JavaScript over PHP. I prefer Java over PHP, as well, though there are some things that are just easier in PHP (but also in JS), such as the Array and associative array types.

Well, that doesn't really matter, and straying from the point. For anyone who is interested, I've got a working version of SQL Schema in JavaScript/Helma (reading xml file, analyzing, validating, and synchronizing with MySQL database), and am currently working on implementing Delight, hopefully I'll have some kind of functionality working soon enough.

Marcello

Thomas Fjellstrom

Perl:

$x = $document->getElementById('foo')->value; // 42
$y = $document->getElementById('bar')->value; //  1
$z = $x + $y;
// z should be 43!
alert($z); // 43 :O

No inherent problem there, except if course some people's dislike for excess "operators".

Marcello

What about people's dislike for Perl? ;)

Fladimir da Gorf

If you love Java and want to get fancy, you could always use Echo. It's a Swing like GUI and the only GUI that I know of which runs mostly with JavaScripts, thus saving bandwidth. But it's mostly for web based applications, though.

Thomas Fjellstrom
Quote:

What about people's dislike for Perl?

That is what I was alluding to ;) No one seems to have a valid reason, except it uses too many $ymbol$. Oh, and allows you to write some really gnarly code.

Marcello

What scares me about Perl is I find it impossible to read or understand anyone else's code. That's a bad sign right there. It's not exactly an accessible language.

Marcello

Thomas Fjellstrom

Thats up to the coder. Its hardly the languages fault a given coder decides to write code thats hard for people to understand. Unless of course you have a major alergic reaction to excess $ymbol$.

Marcello

Actually, I would argue that it is the language's fault. There's too much syntax and too many 'unique' ways of doing things. While that's very fine and well for art or poetry, it's not so useful with coding.

The fact that 95% of Perl is impossible to read or understand tells me that the language is at fault.

Marcello

CGamesPlay

Are you sure it's the language and not the reviewer?

Thread #559748. Printed from Allegro.cc