Speed comparison of Cappuccinos obj_msgSend() vs. normal JavaScript-call avaiable? - javascript

As you know Cappuccino implements the dispatch mechanism of Objective-C / Smalltalk to send messages to objects (~call their methods) in a special method called objj_msgSend.
[someObject someMethodToInvocate: aParameter];
Obviously this introduces some overhead and therefor speed-loss. I'd like to know if somebody can provide a speed comparison between this Message Sending and the normal way to execute a method in JavaScript…
someObject.someMethodToInvocate(aParameter);

In your comments you say you're wondering 'in general' in the context of Cappuccino applications. In that case the test is easy: run any Cappuccino application, such as GitHub Issues, and judge for yourself if its slow or not. Try scrolling in the main table, select a few entries and so on. That'll tell you if Cappuccino is fast or slow 'in general' as objj_msgSend is used extensively in any use case you can think of in an application like this.
If you're actually thinking of something more specific after all, note that nothing about Cappuccino forces you to use message passing. Just like in Objective-C you can always 'drop down to the metal' - pure JavaScript in this case - when you need to do something more performance intensive. If you have a tight loop, and you don't require the additional functionality provided by objj_msgSend, simply call functions directly. Objective-J won't mind.

objj_msgSend is for my simple tests of pure method calling about 2–2.5 times slower than a direct call.
That is actually quite good, given the advanced features it makes possible.

This is coming two years too late, but this is a slightly invalid question (in no way saying that makes it a bad question). There is really no point questioning the speed of objj_msgSend, not when you are assuming that it is a Smalltalk/Obj-C/Obj-J specific feature.
Javascript has ALWAYS had this ability.
Lookup: the call() AND apply() methods... (a quick google search will bring up articles like this -> http://vikasrao.wordpress.com/2011/06/09/javascripts-call-and-apply-methods/ )
It is the same issue with jQuery/Prototype/etc..., they are all fine and dandy and useful. But they hurt the development community because everyone relies on these frameworks instead of learning the core language features that make any language useful.
Do yourself and the development community a favor and LEARN YOUR LANGUAGES, NOT FRAMEWORKS. If you know the languages you use, the frameworks you use are irrelevant, use them or just build them yourself, because at that point you should be able to.
Hope that came off as helpful and not condescending, thats not my intention. :)

Related

Is Jquery *compiler* possible?

When I saw this question I thought it would be helpful if a jQuery compiler could be written. Now, by compiler, I mean something that takes in jQuery code and outputs raw javascript code that is ultimately executed.
This is how I vision a block of jQuery code execution:
a jQuery function is called and parameters are passed to it
the function calls a raw javascript function and passes the parameters it received to it
the newly called function performs the intended action
I understand that this is a very simplified model and it could be much more complex, but I think the complexity is reduced to steps 2 and 3 being repeated with different raw js functions being called and each time fed with all or a subset of parameters / previous results.
If we subscribe to that model, then we might come up with methods to make the jQuery functions perform double-duty:
What they already do
Logging what they did in form of raw_function(passed_params)
Am I making some wrong assumptions that would make this impossible?
Any ideas how Firebug's profiler attempts to get function names? Could it be used here?
Edit
What I was thinking was making a black box with input / output as:
normal jquery code → [BB] → code you'd write if you used no library
I called this a compiler, because you compiled once and then would use the resulting code.
I argued that it could have at least educational use, and probably other uses as well.
People said this would take in a small amount of code and output a huge mass; that does not defy the intended purpose as far as I see
People said I'd be adding an extra, needless step to page rendering, which, given only the resulting code would ultimately be used (and probably be used just for studying), is not correct.
People said there is no one-to-one relation between javascript functions and jquery functions, and implied such a converter would be too complicated and probably not worth the effort. With this I now agree.
Thank you all!
I think what you mean is: if you write
var myId = $("#myId")
it will be converted to
var myId = document.getElementById("myId")
I think its possible, but the problem is, jQuery functions return jQuery objects, so in the above example, the first myId will be a jQuery object & the second will be a node object(i think) which will affect other functions that needs to use it later in the code after compilation. Especially if they are chained
secondly you will have to be sure that the conversion actually has performance benefits.
However if you are aware of all this and you can plan you code accordingly, i think it will be possible
If the purpose of the compiler to convert Javascript (which may be jquery or anything) to better Javascript (which I understood from you saying "ultimately executed"), then Google has already done that. They made closure compiler and some have tried it with JQuery in this post. Isn't this what you are suggesting ?
jQuery code is "raw JavaScript code" so I'm not sure what a compiler would really buy you. That's like writing a C# compiler which takes C# 4.0 code and emits C# 1.1 code. What's the benefit?
jQuery isn't a different language which replaces or even sits on top of JavaScript. It's a framework of JavaScript code which provides lots of useful helpers for common tasks. In my view, it's greatest benefit is that its distinctive structure helps to differentiate it from the more "Java-like" languages.
JavaScript by itself is deceptively similar to other languages and this tends to be one of its biggest faults as a language. People try to think of it in terms of Java, even though the similarities pretty much stop at the name. Structurally, JavaScript is very different in many ways (typing, scope, concurrence, inheritance, polymorphism, etc.) and I particularly like how jQuery and other modern JavaScript projects have brought the language to stand on its own merits.
I guess to get back to the question... If you're looking to turn jQuery-style JavaScript into Java-style JavaScript, then that's something of a step backwards. Both versions would be interpreted by the browser the same way, but one of the versions is less elegant and represents the language more poorly than the other.
Note that jQuery isn't the only framework that does these things, it's just the most popular. Would such a compiler need to also handle all the other frameworks? They all do different things in different ways to take advantage of the language. I don't think that homogenizing them to a "simpler" form buys us anything.
Edit: (In response to the various comments around this question and its answers, kind of...
How would you structure this compiler? Given that (as we've tried to point out) jQuery is JavaScript and is just a library of JavaScript code, and given how browsers and JavaScript work, your "compiler" would just have to be another JavaScript library. So essentially, what you want is to go from:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
to:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
Your "compiler" library
Some more JavaScript code which sends the previous JavaScript code through your library somehow
Your "jQuery-equivalent" library
Some more JavaScript code which replaces the original JavaScript code with your new version
in order to make things simpler? Or to somehow make debugging tools like FireBug easier to use? What you're proposing is called an "obfuscator" and its sole purpose is to make code more difficult to reverse-engineer. A side effect is that it also make code more difficult to understand and maintain.
Now, by compiler, I mean something
that takes in jQuery code and outputs
raw javascript code that is ultimately
executed.
I think that statement may indicate what's going wrong for you.
jQuery is a library implemented in the Javascript language. jQuery isn't a language separated from Javascript. jQuery is a collection of Javascript code that you can use to make Javascript development easier. It's all Javascript. A "jQuery compiler" to convert "jQuery code" to "raw Javascript" would be quite useless because jQuery is raw Javascript.
What you probably actually want is a Javascript compiler. In that case, it's certainly possible. In fact, some web browsers nowadays actually "compile" on the Javascript code in some kind of bytecode to enhance performance. But development workflows involving Javascript typically don't involve a compiler tool of some kind.
Apparently what you actually want is to "inline" jQuery code into your code, sort of like this:
var myfoo = $('#foo'); → var myfoo = document.getElementById('foo');
This is actually something a C++ compiler would do to optimize performance, but Javascript is not C++ so it doesn't apply here.
I don't see how this is useful. The point of jQuery is to simplify Javascript development by providing a consistent interface like the $() function. By performing this "inlining" procedure you produce code that is even harder to read and maintain.
And why add an extra step? Why not just deliver the application javascript code and the jQuery library to the browser? Why add an extra step involving an extra tool to convert Javascript to Javascript that doesn't provide any substantial extra benefits?

Prototype to jQuery: Mindset migration?

This isn't about a side-by-side technical comparison, rather about how to "think in jQuery" versus "thinking in Prototype".
I've used Prototype heavily for several years, and jQuery somewhat less heavily until about a year ago when I started doing a lot with it.
With Prototype, I can write some fairly elegant code; my boss once reviewed a large amount of my code and remarked that it was the first Javascript he'd ever found a pleasure to read. I understand - and understood pretty much from the beginning - almost instinctively what Prototype's trying to do, and know how to work with it.
My jQuery code is a lot more, how can I put this, "workmanlike". I feel as if I'm fighting jQuery every step of the way. I have to (try to) force myself to stick with it and not drop down into "native" JS, where I know I could bash out clean cross-browser code more quickly. Working with it more makes it more, not less, frustrating.
It's not (or at least not entirely) a lack of familiarity with the functions available. I'll often know I need to use a given function, but the way in which it's used seems truly bizarre. That's usually a sign that I'm coming at something entirely the wrong way.
The more I think about this, the more I think I'm trying to use jQuery in a Prototype way.
There has to be some blinding flash of light that hasn't happened to me yet. Especially if you've worked a lot with both, what do you find are the most fundamental differences in approach? How do you need to adjust your mindset when switching from one to the other?
Don't be afraid to state the blindingly obvious, because it may just be that blinding flash...
I went through that transformation. The main thing to tell yourself over and over again is that jQuery is, first and foremost, about making DOM manipulation easier and more cross-platform safe. There's no "reduce" (Prototype used to call it "inject", I think) in jQuery. Why? Because the maintainers don't consider it important for the primary task of jQuery.
Thus, the way that Prototype's base object extensions creep into your coding style as you write your code to get your own work done, well, that pretty much doesn't happen in plain ol' jQuery. (See, however, the lovely Underscore.js library for a way to get some of that functionality in a jQuery-friendly way.)
For me, that's made it easier to figure out how to build on jQuery. It's just a different sort of thing. Now, jQuery is very solid and it really does make DOM manipulation and HTML wrangling a lot nicer than what you get from plain Javascript. (I think Prototype does an OK job too, but jQuery is super-focused on the problem.)
The best advice i can give is "Embrace this". In jQ, you're nearly always talking about iterating over a set that is wrapped in the jQuery object. Invoking one of the set's methods performs the method on all the elements of the set, whether its 1 or 100. That method is always going to return the same instance of the set (aside from accessors that get a property). In the context of the interation this is the value of the item in that set youre manipulating - usually the raw DOM Element, but it could be the value of an object property or array item.
Why do you need to think differently? Instead of adapting your style to every framework or language that comes along, why not adapt the framework or language itself to your liking. Then all you'll have to do is be open to the idea that there might be better ways of writing or structuring code than you already know, and when those ways present themselves, objectively analyze and then include them in your repository.
The choice is almost never all or nothing. Both frameworks have great offerings, and you can use techniques from both in harmony for building a great application.

How can I get better at OOP? [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.
This might come as a strange question to many of you, and I don't actually know if it is correct to say OOP in this context, because OOP (object-oriented programming) is usually associated with programming languages like C++ and Java, and not lightweight programming languages, or scripting languages. My question, however, is in the category of JavaScript, which is also object oriented. I do know about objects, properties, methods, prototypes and constructors, I just can't seem to get into my mind when to use objects.
When I am writing my web-applications, I, for some reason, never use objects. This annoys me, because when I read about objects in a variety of books and online articles, objects make everything so much simpler and, just to put it out there, I HATE repeating myself, and this is why I wish I knew when to use objects.
I really want to become better at using objects and when to use objects.
Can you please mention a few situations objects would be good? It would be really nice to have written down something you know you can go back and look at when you get confused about when to use these darn objects :)
I would love simple answers explaining why and when objects are to prefer.
I would also like if you could tell me if I am to use objects when I am in some special situations generally suitable for objects i.e. every time you want to _________ then you use an object...
I really hope you understand my question and you will consider that I'm somewhat new to this site and new to JavaScript
Thanks!
You probably use objects without even realizing it.
If you're writing Javascript that interacts with the DOM, you're using objects.
If you're using any of the Javascript frameworks out there (jQuery, MooTools, etc.), you're using objects.
Using objects will be useful when you need to encapsulate some commonly used code so that it can be easily re-used (within a single application or across multiple applications like jQuery plugins...which are objects in and of themselves).
And to answer the question in the title of your post...the only way to really get better at OOP is to practice! Reading and studying the subject can only get you so far.
First, you don't need to use objects to avoid repeating yourself. If you need to do the same thing at two points in your code, you can write a plain vanilla non-OOP function to do that and call it twice.
To summarize the advantages of OOP without writing a book here, OOP basically does three things for you:
Group related data together. Non-OOP programs often have a whole bunch of variables floating around in the main program that are only loosely related. With OOP, you put related variables into an object.
Associate functions with data. By putting functions in an object with the data they operate on (purists will say they are then "members" rather than "functions"), you make it clear to the reader that these go together.
Combining #1 and #2 lets you hide implementation details from other objects. You create the "public interface" for a class, the set of functions that other objects should call and that represent the logical things that this class does, and then any other functions you need can be hidden. (More explicitly in some languages than in others, but that's not the point here.)
Classes can inherit and mutate. If you have two similar classes A and B that should be mostly the same but with some minor differences, you can make a superclass C with all the common stuff and then A and B inherit from that and each adds in its own unique stuff. This is what is usually advertised as the power of OOP. Frankly, yes, it's way cool, and in some situations can be very handy, but I only use its true power occasionally, and I suspect the same is true of most programmers. (OOP enthusiasts feel free to jump in with how and why you use inheritance all the time.)
When to OOP it? Any time you have several pieces of data that logically go together, it makes sense to create a class to hold them. Like X and Y coordinates; or customer name, address, and zip code; or phaser range and phaser power consumption; or whatever.
Any time you have functions that logically operate on this related data, put them in the the class with the data. Like "capitalize customer name", "compute distance of this point from the origin", etc.
How and when to use inheritance is more complicated. I'll leave that for another time.
The first thing to remember, is that a lot of simple Javascript code really doesn't need to define objects (using them is inevitable, as all the stuff the DOM gives you are objects). Don't panic too much.
One of the good things about Javascript is that it supports a lot of different styles; OOP, imperative and functional.
One of the bad things about using Javascript is that because it supports a lot of different styles, it's hard to learn another style, at least until you are forced to an "a-ha" moment by something else.
Spending time in languages that are more inclined to force you into OOP (even when some would argue they shouldn't) is helpful here. C# and Java force one along OOP lines, though C++ does not (with the same strength and weakness here as with Javascript).
Try to think about the "things" in your program. Some of these things will already be modelled by objects (those the DOM gives you). Some really will just be numbers and strings and not worth composing beyond that (though learning how to add functionality to those types through prototype is a good idea too). Some will be "things" more complicated than a simple type and naturally suited to modelling as an object.
Do also look at functional programming in Javascript (e.g. passing a function as a parameter to another function is about the simplest example), as the interaction between this and OOP is one of the strongest elements in Javascript, and essential in defining methods on objects given the prototype-based OOP model it has.
My personal experience with OOP in JavaScript is a positive one, once I figured out to get it to do what I wanted of course, I usually use it in combination with jQuery so the resulting code can seem a bit.... odd.
function BlogPost(id,title,content)
{
this.id = id;
this.title = title;
this.content = content;
function display()
{
var post = $('<div class="blogpost"></div>');
$(post).append('<h2>' + this.title + '</h2>');
$(post).append('<p>' + this.content + '</p>');
var deleteButton = $('<span class="deletePost">delete</span>')
$(post).append(deleteButton);
$(deleteButton).click(this.delete)
$('#postcontainer').append(post);
}
function delete()
{
$.post('some/xhr/handeler',{id:this.id});
}
}
This is a quick (untested) class that can be used to dynamically add blogposts to a div with id postcontainer' and handles clicks on a delete button.
Think about how you can use objects to organize and simplify your application. I have found two metaphors useful:
A mechanical watch is made up of a number of gears, each of which serves a single purpose in the overall operation of the machine. If you think of your application as a watch, then objects are its gears.
A workgroup is made up of a number of people, each of whom performs a specific job. The people communicate with each other in performing their jobs, and the jobs fall along two lines--those that perform tasks (workers), and those that organize and direct the work of other people (managers).
You can use these metaphors to organize the work your application does. Start by dividing the app into functional layers; UI, business layer, and persistence, for example. Take each of your use cases, and distribute the work it does among these layers. That should give you a starting point for the classes you will need.
Make each class as self-contained a possible. you want to seal it off when it is done, like a .NET control. Classes should communicate with each other only through their interfaces, which are made up of properties and methods. These interfaces should have the smallest footprint (fewest public properties and methods) you can come up with. The idea is to isolate the side effects of a change to any class to that class alone.
If you do these things, you will be ahead of 80% of all programmers. You will find it much easier to develop and maintain even large applications, because you will be able to break complex problems down to simple components.
Javascript is just a terrible language to learn OOP in. I would recommend learning OOP in another language (like Java or C++) and then learn Object Oriented syntax in Javascript. At that moment you have all the ingredients.
That's when you can decide whether or not you want to be using an object for a task in Javascript or if it is enough to use just functions.
Personally, I mostly write non-object javascript and leave objects for when a task feels object oriented to me. For example, I used an object oriented design for a drag and drop script, in which you simply made a DragNDrop object with the correct parameters and the items in your page would be dragable from that moment on, or when I wanted to simplify some javascript xml handling functions, I wrote an object that wrapped the normal xml objects.
Justin Niessner said it and I can only add to his answer...
In addition to practice, I find reading other people's code very instructive. You need to be cautious because not all code is exemplary (to say the least) but developing critical skills is part of getting better.
In my opinion I think it's better to think about OOP in the context of a particular domain or business problem. For example, JavaScript uses objects to model browser behavior and attributes, e.g., Window, Frame, History...
A domain model of a business problem will contain objects that will be reflected in the programming code written OOP. For example, a university student application will have objects for students, professors, courses, curriculums, rooms and so on. Consequently, begin with your business problem and model the domain. Your OOP code should have objects modeled from your domain.
Source:http://csci.csusb.edu/dick/samples/uml0.html
You might be interested in design patterns (Book, Wikipedia), which tell you, how to solve common problems using OOP.
Many classical design patterns may not be so relevant for JavaScript, since in JavaScript there are other non OOP elements (e.g. functions), which can solve some problems even more elegant.
Some simple design patterns I can recommend to start with:
Abstract factory: Defer the instantiation of objects. In JavaScript in most cases a function will do the job.
Decorator: Transparently add functionality to an object at runtime. Can also be nested. Usage example: Logging
Composite: Treat a tree/graph of object like a single object.
I think that using classes in general and OOP principles, makes your code neater, more readable and makes you more productive .
Recently I worked on a web application that would require heavy client side Javascript.
Coming from C#/Java background I realized that Javascript would require a change of thinking, however I still wanted to apply good OO principles if possible, in particular to control the likely complexity of the application.
After a bit of searching I found a great book called Object Oriented Javascript by Stoyan Stefanov. It truly opened my eyes to power of this often called "toy language". Some sections on functional programming concepts, variable scoping and closures may even be a bit more advanced than you want.
However reading and applying many of these concepts from this book (closures, anonymous functions etc) in Javascript, has actually even helped me back in C# land where these concepts are only now becoming more mainstream.
Given your stated situation and goal I can highly recommend this book as one of the best ways to learn about doing OO in Javascript.
Javascript is much, much less object oriented than C# or Java; don't worry if your Javascript doesn't look object oriented.

Why am I finding Javascript/jQuery so difficult to get right?

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue.
But I'm finding Javascript/jQuery surprisingly difficult to get right.
Very frustrating.
Why?
It seems to violate a number of traditional programming principles (e.g. variable scope)
Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs):
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API?
There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)
Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)
Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.
It seems like everyday there's some random JS "rule" that comes up that I've never seen before in any of my JS books or tutorials.
What do I need to do to make Javascript/jQuery more deterministic, controlled, and logical to me?
Are there any resources that explain Javascript's quirks/gotchas?
Thanks!
1) It seems to violate a number of traditional programming principles (e.g. variable scope)
You need to declare variables using var, else it will go into the global scope.
2) Undefined variables seem to appear out of nowhere and already have values associated with them (how did this happen?)
This is possibly related to 1) and/or 4).
3) There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)
You need to let the handler return false as well. E.g. form onsubmit="return functionname()". You also need to return from the "main" function, not only from a closure (a function inside a function), referring to your previous question. It would only return into the "main" function and continue on.
4) Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)
Probably the code was executed before the HTML DOM was finished populating. You need to hook on window.onload or $(document).ready() whenever you want to execute stuff during page load.
5) Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.
I bet that you're talking about jQuery source? It's just a large library. You should after all not worry about this when debugging. Rather worry about your own code. However, make sure that you're looking at the unminified version of jQuery's source code.
See also:
JavaScript: the bad parts
What should every JavaScript programmer know
Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource. Javascript plays a lot more like Lua, Lisp, or Python than C, it just happens to LOOK like C.
Link provided to Amazon; I snagged mine from O'Reilly.
To be honest, I think you have a good understanding. Some of my hangups were similar. The way that I have been moving on is "well, if that's the way it is, then that's the way it is". Just accept the idiosyncrasies and plow forward. PHP does some of the same things (variables can show up out of nowhere, etc...). Just code the way you want to code and if it works, then great!
Then after you get to that point start breaking out the profiler and see if there's anything that you can optimize.
Here are a couple of things:
If you understand CSS, then jQuery selectors should be easy. As far as the code goes, that's straightforward too if you can deal with chaining and JSON. EDIT: also, the jQuery documentation on everything is EXCELLENT! And There is no shortage of jQuery experts here on SO to help us noobs (and hopefully we can return the favor for newer noobs).
There is a scope to work with. (Basically) anything written outside of a function or object is in global scope. If you are inside of an object or function and use var then that sets the variable's scope
Javascript isn't like a C-based language (C++ or PHP even). It uses prototypes to deal with class/object relationships rather than a subclassing scheme.
The #1 thing that threw me for a loop is that any JS that appears anywhere on the page or that was included in <script> tags is fair game. If you have a global variable in one script, you can use that same variable in a completely different script and it will work. That may be what you mean about variables showing up out of nowhere. Also, there are some DOM based variables that can just "show up" too.
Anyways, I think that if you just plow ahead, you'll get some "AHA" moments. I'm a relative noob to programming, but I continually grow as long as I don't hang up on something that doesn't have too much of an impact on actually making the code run.
It's a language based on prototypal inheritance and is influenced by functional programming languages and the paradigm so it isn't completely just OO/Procedural like other languages. Variables are implied globals unless declared with var.
Please include an example?
return false exits out of the function as with any language's return statement. preventDefault() would be the DOM method to cancel the default behaviour of a link
Javascript is used primarily on the client side. Since there are many user agents, each of them have a different implementation of the DOM, which is very inconsistent, moreso than JS itself. Again, please include a real example to get a definitive answer.
You'll find messy looking code in any language, and maybe your lack of understanding perceives the code as messy, when in fact it isn't so bad. Or maybe you're looking at some minified/obfuscated code.
I recommend http://eloquentjavascript.net/ for learning aspects of Javascript.
Things you'll learn from the link above
lambdas
closures
Prototypal inheritance
Event based programming
Debugging
DOM
"JavaScript: The Good Parts" by Douglas Crockford is a good start
In your case, the appendices ("the bad parts" and "the awful parts") might be the most interesting :)
Crockford's "Javascript: The Good Parts" gives some common JS patterns that help with variable privatization and scoping. This is for javascript in general. For jQuery I just use the API. Also the Yui Theatre videos on javascript are quite good
Javascript can be a little tricky and some of it's functional aspects confuses people. If you actually learn and understand the language you'll find it really useful, most people just randomly start using it and then just hate.
Read javascript the good parts by crockford, it's really helpful: http://javascript.crockford.com/
Also make sure you understand closure. It's a fundamental that people don't get but often use.
In terms of variable scope, there are local and global variables. One of the gotchyas of variable scope can be seen in this example:
var thisIsAGlobalVariable
function anon () {
var thisIsALocalVariable
thisIsAGlobalVariable = 5; //if you don't use the var prefix inside a fn, it becomes global
}
You are finding it difficult because:
javascript has another kind of syntax.
javascript is dificult to debug
javascript has no autocompletion like c# etc) ?or does it
javascript has illogical rules (they become logical once you are known with them)
everything can be done in 1000 ways, and when you search for a solution, you will find 2000 answers :) where c#, php mostly have a good practice function u "should/could" use
However, I started using js/jquery a half year ago, with the same reasoning as you do, and I stuck to it, and now I use it daily to enhance my webapps.
I just love it (especcially jquery). It is a life saver, I know what and where to look, I can do about anything with it.
Everything seems logical.
If I can give you one advice: javascript/jquery is a sour apple, but just hang in there, bit trough and you won't regret it.
also, a loooot of people use it and are always willing to lend a hand if needed (I know I do)
Javascript is tricky. You don't have a compiler watching your back. To compensate, unit testing becomes more important. I've been doing my unit testing with jQuery/QUnit, but I recently started using Jasmine (http://github.com/pivotal/jasmine) and I recommend it 200%. Its a great testing framework.
If you're not familiar with testing, or testing with javascript, I'd highly recommend finding unit tests for other OSS javascript projects (hopefully for code you could use) and seeing how they test it.
With unit tests, you'll make the same mistakes, but catch them much sooner and with less grief. And if your tests are good, the mistakes won't come back after you fix tham.
I don't know how much UI design you have done in C, but the event variable only shows up when it is sent by the caller and the handler needs to, well, handle the object. If you do reading on event object, the confusion in q #2 should go away.
There is no event handling in PHP, so I think you have not came across this issue in the past. JavaScript is a programming language with its own purpose, so it was designed to work for that specific purpose.
Maybe you have to link your code to an HTML onclick="event()" button to fire off as the event.

Alternative "architectural" approaches to javaScript client code?

How is your javaScript code organized? Does it follow patterns like MVC, or something else?
I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with jQuery, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":
The 'model' is a JSON tree that gets extended with helpers
The view is the DOM plus classes that tweak it
The controller is the object where I connect events handling and kick off view or model manipulation
I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + <generic web service-y thingy here>"
Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.
..but Javascript has many facets that are OO.
Consider this:
var Vehicle = jQuery.Class.create({
init: function(name) { this.name = name; }
});
var Car = Vehicle.extend({
fillGas: function(){
this.gas = 100;
}
});
I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes).
This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate.
JavaScriptMVC is a great choice for organizing and developing a large scale JS application.
The architecture design very well thought out. There are 4 things you will ever do with JavaScript:
Respond to an event
Request Data / Manipulate Services (Ajax)
Add domain specific information to the ajax response.
Update the DOM
JMVC splits these into the Model, View, Controller pattern.
First, and probably the most important advantage, is the Controller. Controllers use event delegation, so instead of attaching events, you simply create rules for your page. They also use the name of the Controller to limit the scope of what the controller works on. This makes your code deterministic, meaning if you see an event happen in a '#todos' element you know there has to be a todos controller.
$.Controller.extend('TodosController',{
'click' : function(el, ev){ ... },
'.delete mouseover': function(el, ev){ ...}
'.drag draginit' : function(el, ev, drag){ ...}
})
Next comes the model. JMVC provides a powerful Class and basic model that lets you quickly organize Ajax functionality (#2) and wrap the data with domain specific functionality (#3). When complete, you can use models from your controller like:
Todo.findAll({after: new Date()}, myCallbackFunction);
Finally, once your todos come back, you have to display them (#4). This is where you use JMVC's view.
'.show click' : function(el, ev){
Todo.findAll({after: new Date()}, this.callback('list'));
},
list : function(todos){
$('#todos').html( this.view(todos));
}
In 'views/todos/list.ejs'
<% for(var i =0; i < this.length; i++){ %>
<label><%= this[i].description %></label>
<%}%>
JMVC provides a lot more than architecture. It helps you in ever part of the development cycle with:
Code generators
Integrated Browser, Selenium, and Rhino Testing
Documentation
Script compression
Error reporting
MochiKit is great -- and was my first love, so-to-speak, as far as js libraries go. But I found that while MochiKit has very expressive syntax, it didn't feel nearly as comfortable to me as Prototype/Scriptaculous or jQuery did for me.
I think if you know or like python, then MochiKit is a good tool for you.
Thank you all kindly for your answers. After some time, I'd like to post what I've learned so far.
So far, I see a very large difference the approach using something like Ext, and others like JQuery UI, Scriptaculous, MochiKit, etc.
With Ext, the HTML is just a single placeholder - UI goes here. From then on, everything is described in JavaScript. DOM interaction is minimized under another (perhaps stronger) API layer.
With the other kits, I find myself starting by doing a bit of HTML design, and then extending the DOM directly with snazzy effects, or just replacing the form input here, an addition there.
The major differences start to happen as I need to deal with event handling, etc. As modules need to "talk" to each other, I find myself needing to step away from the DOM, abstracting it away in pieces.
I note that many of these libraries also include some interesting modularization techniques as well. A very clear description is contributed on the Ext website, which includes a fancy way to "protect" your code with modules.
A new player I haven completely evaluated is Sproutcore. It seems like Ext in approach, where the DOM is hidden, and you mostly want to deal with the project's API.
Tristan, you will find that when you try to architecture JavaScript as an MVC application it tends to come up short in one area -- the model. The most difficult area to deal with is the model because the data does not persist throughout the application, and by nature the models seem to change on the client-side pretty consistently. You could standardize how you pass and receive data from the server, but then at that point the model does not really belong to JavaScript -- it belongs to your server-side application.
I did see one attempt awhile back where someone created a framework for modeling data in JavaScript, much like the way SQLite belongs to the application. It was like Model.select( "Product" ) and Model.update( "Product", "Some data..." ). It was basically an object notation that held a bunch of data to manage the state of the current page. However, the minute you refresh, all that data is lost. I'm probably off on the syntax, but you get the point.
If you are using jQuery, then Ben's approach is really the best. Extend the jQuery object with your functions and properties, and then compartmentalize your "controllers". I usually do this by putting them into separate source files, and loading them on a section-by-section basis. For instance, if it were an e-commerce site, I might have a JS file full of controllers that handle functionality for the checkout process. This tends to keep things lightweight and easy to manage.
Just a quick clarification.
It is perfectly feasible to write GWT apps that are not server-oriented. I am assuming that from Server-Oriented you mean GWT RPC that needs java based back-end.
I have written GWT apps that are very "MVC-ish" on the client side alone.
The model was an object graph. Although you code in Java, at runtime the objects are in javascript with no need of any JVM in either client or server-side. GWT also supports JSON with complete parsing and manipulation support. You can connect to JSON webservices easily, see 2 for a JSON mashup example.
View was composed of standard GWT widgets (plus some of our own composite widgets)
Controller layer was neatly separated from View via Observer pattern.
If your "strongly-typed" background is with Java or similar language, I think you should seriously consider GWT for large projects. For small projects I usually prefer jQuery. Upcoming GWTQuery that works with GWT 1.5 may change that though not in near future because of abundance of plugins for jQuery.
Not 100% sure what you mean here, but I will say that after doing ASP.NET for the last 6 years, my web pages are now mostly driven by JavaScript once the basic page rendering is done by the server. I use JSON for everything (have been for about 3 years now) and use MochiKit for my client-side needs.
By the way, JavaScript is OO, but since it uses prototypical inheritance, people don't give it credit in that way. I would also argue that it is functional as well, it all depends on how you write it. If you are really interested in functional programming styles, check out MochiKit - you may like it; it leans quite a bit towards the functional programming side of JavaScript.

Categories

Resources