Please explain the VC in MVC for javascript - javascript

This is really getting me frustrated. I'm trying to build a custom JavaScript app with no libraries. This is mainly for me to learn better core JavaScript and JavaScript patterns. I'm trying to implement the MVC structure and I understand the parts separately, but for the life of me I can't figure out how to connect the views and controllers together. For example if I have this code:
<div>
<button id="button1">Click Me</button>
<button id="button2">Click Me</button>
<button id="button3">Click Me</button>
</div>
How in the world do I write a controller.js file to listen to the clicks of each button and respond. Especially if each button does something totally different from the others. Let's say button1 simply links to google.com, button2 opens a modal box and button3 updates a database table. So each one is doing something totally separate. What I am trying to avoid is using jQuery to do something like this.
$('#button1').click(function(){
//go to google.com
});
$('#button2').click(function(){
//open modal box
});
$('#button3').click(function(){
//update database
});
This doesn't seem very efficient, especially when trying to use the MVC structure. Is there a smoother way, even a few different design patterns I can follow to write this is core JavaScript with no libraries? I scoured the net to find articles but everything I find relies heavily on a library.
Any books, tutorials, blog posts or anything of the like that will clearly explain something like this is much much appreciated. Who knows once I get the hang of it maybe I'll write a book on it for the masses.
Once again the help of the community is always appreciated.

You are writing an application in Javascript, following the MVC design pattern, and it's a great idea to understand core javascript, as you will have to adapt existing design patterns on js :)
I would have parsed the DOM recursively at first, retrieving each tag, and then associated them simple click event code that call a click_event generic (and global) function, with the button id as parameter, to have a single entry point that identify the button.
Then this generic method (event entry point) would have to select and launch the appropriate controller for the action.
You might also go one step further with 2 parameters: objectId or reference, and event type. This is very similar of what you will find on many basic GUI to fire events.

I am not really getting the idea of "MVC JavaScript app". JS is only part of the V of a webapp.
If you want that your code to run on multiple browsers, jQuery is the way to go.
But, I admit that there are valid cases when you can't use libraries and you have to write simple, slim, pure js core code. And also it is a good idea to know the core of the programming language and then learn a library/framework for that language.
Now, I am not sure how much do you already know about js. I always liked w3schools tutorial, you really get the basics there. For js is here: http://www.w3schools.com/js/default.asp
If you know everything from there and your goal is to get more advanced skills of js, then you will have to digg a bit more:
http://ejohn.org/apps/learn/ - nice tutorial with few things that you should know about js (objects, prototypal inheritance, declaration hoisting concept, etc).
http://www.javascriptkit.com/javatutors/ - very practical tutorials about real situations with nice solutions
http://code.google.com/p/jslibs/wiki/JavascriptTips - interesting js tips and tricks
http://www.quirksmode.org/ - not directly related to learning js, but a must know if you intend to work with js in different browsers.
Hope this will help

Related

How to improve the architecture of my website?

The following picture is my web architecture.This is my first website too.This site is a kind of control panel, thus it is composed of many buttons and events.As the requirement becomes more and more, it becomes hard to maintain.
Web Architecture
Let's say if I need to add a new function, I need:
1. UI : design Input & output.
2. create event handler by jquery.
3. create ajax function. (draw the results on success function)
It is just like a chain.The problem is:
1.change one thing = change every thing.
2.Can't manage the output view very well(the output view can be a table, options, label..)
So I'm curious about does there exist any framework or better way can help me?
Thanks.
Your project might be having a "jQuery soup" problem, but to answer your question there's just too many MV* JS "frameworks" around, e.g. Ember.js, AngularJS, Backbone.js to name a few.
IMO Backbone.js is easiest to fit into an existing project in case you want to slowly refactor your existing code. There are others that are more opinionated and do a lot more for you, but you may require more substantial refactorings in your JS code.
All the above "frameworks" will help you with managing models, the views, events, and tying everytihng back to the server.

Why do we need javascript mvc?

When would one go for using Javascript MVC ? I mean why there was a
need for JS-MVC ?
Is it only because this design pattern was famous in other languages, for code maintenance,readability and many web apps are shipping client side ?
How does it helps a developer, tester and end-user easing their
tasks ?
Any use-case where JS-MVC is suited best and any case where it is
not at all required ?
Question 1,2,4
My view is that you should apply any kind of design pattern only and only if you really need it. Simply because design patterns aren't easy after all. They will add complexity to your solution, but they'll also provide you the benefit of (normally) being established and working solutions for specific kind of problems.
Whether to use or not use them really depends on what you are going to construct and how complex it is. That said, I'm probably not going to structure my 200 lines jQuery plugin using the MVC pattern, maybe...
But at work we create single page applications where we have 2-5 devs working on a project the same time, projects of the amount of 500 days. In such environments things can get complex very quickly and if you don't follow any kind of proper structuring you're lost.
I hope that should answer your question 1 and 2.
For question 3:
The end-user hopefully gets a better quality app with less bugs, but usually he shouldn't even notice (nor does he care) about the underlying architecture of an app.
MVC helps the developer
as an orientation when navigating in the app's source code. Consider an app of 3000 lines of code in a single source file and then when having 4 devs working on it at the same time. A mess, right? When having an MVC app which normally also use routings etc...you normally already know by looking at the route in the url where the corresponding controller lies in the source code and where you should put your hands on
for easier testing. Separation of concerns is always beneficial when applying unit testing practices because you can much easier test your controller because it isn't directly couple to data or presentational stuff (like HTML code etc). And just as a side note, you should definitely unit-test your JavaScript code, definitely!!
maintenance: which is the result of the previous points somehow
I'm not sure which kind of figure you intend by "tester". If he writes automated tests at the unit or acceptance level, then the benefits from before pretty much hold as well. If he's testing the app as a whole in the sense of navigating around, taking the app as a black box by testing its reaction to different kind of inputs, then MVC doesn't really play a big role for him. It's like for the end-user.
So I hope I was able to clarify some things for you. But as said, never just follow a pattern because people follow it but only 'cause it gives you any kind of benefits.
MVC is used to structure your code especially if you are working a lot with client side rendering. Without structure your code gets complex very fast.
User experience for end user is much better when you don't have to wait for the whole page refresh if you only need partial update.
It helps to navigate through the code much faster if you have well defined structure of your code.
JS MVC frameworks are best used where you have complex systems and you want to provide better user experience by using AJAX and partial page reloads or updates. Usually you would not use MVC for Personal website, blogs or stuff like that...

When to use MVC in Javascript?

Im working on a framework based off bootstrap that will be used across multiple websites. At the moment im just writing a ton of jQuery functions for different events and doesn't seem scalable at all. I been reading up on MVC for js and not sure when it should be used or if its what I need to start applying.
Any suggestions on when its needed?
The answer to this is simple ... use MVC when your project gets large enough to warrant it. Many patterns can end up being overkill when you're writing a small project, or simple feature. But there will come a time when not using something like MVC to organize your code will result in an unmaintanable mess. It sounds like you're already hitting that point, so it could definitely make sense to put some thought into how you structure your application.
I actually wrote an article on how you can easily use the pattern from javascript without having to bring in any heavyweight external dependencies:
http://codecube.net/2009/06/mvc-pattern-with-javascript/
MVC stands for "Model View Controller" and it is a coding paradigm. You can quite easily apply it on the client using JS for webapplications. Models are just plain old JS objects. Views can be implemented using templates (jQuery has templates, but others such as Mustache, Handlebar or Dust are arguably better). And the Controllers are triggered by events and handle the dataflow and processing.
Take a look at some of the other libraries which help create this sort of structure.
My personal favourite is Backbone.js its pretty lightweight but extremely functional.
IMO the best time for structure is from the start, its easier to add to a code structure from the beginning than it is to make code fit into a structure after the fact.
Personally I think structure whatever the choice is, is important especially in JavaScript (Since its so damned mutable) for maintainability, scalability and just plain old helping other people understand what's going on when they have to do a bug fix in code they didn't write! :)

Where can I get advice on how to build completely ajax web apps?

I am building a completely ajax web app (this is the first web app I have ever created). I am not exactly sure if I am going about it the right way. Any suggestions or places where I can go to find suggestions?
Update:
I currently am using jQuery. I am working on fully learning that. I have designed a UI almost completely. I am struggling in some parts trying to balance a good UX, good design and fitting all the options I want to fit in it.
I have started with the design. I am currently struggling with whether to use absolute positioning or not and if not how do I use float etc. to do the same type of thing. I am trying to make it have a liquid layout (I hate fixed-layout pages) and am trying to figure out what I should use to make it look the same in most screen sizes.
Understand JavaScript. Know what a closure is, how JavaScript's event handling works, how JavaScript interacts with the DOM (beyond simply using jQuery), prototypal inheritance, and other things. It will help you when your code doesn't work and you need to fix it.
Maintain usability. All the AJAX magic you add is useless if users cannot figure out how to use it. Keep things simple, don't overload the user by giving him information he doesn't need to know (hide less important information, allowing the user to click a link to show it), and if possible, test your app with actual users to make sure that the interface is intuitive to them.
Code securely. Do not allow your server to get hacked. There are many different types of security flaws in web apps, including cross-site scripting (XSS), cross-site request forgery (CSRF), and SQL injection. You need to be well aware of these and other pitfalls and how to avoid them.
One starting point is to look at the Javascript Libraries and decide which one to use:
http://code.google.com/apis/libraries/
http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks
You probably don't want to do raw Javascript code without any library. Once you decide on a library to use, then you can look at its documentations online or the books about using them. jQuery does have pretty good documentation.
Define "right way."
There are many "right ways" to code an app.
Things to keep in mind are trying to design a nice interface. The interface can make or break an application and studies show that it can even make it seem faster if you do it right. jQuery is good for this.
Another thing to consider going in is what browsers do you want to support? Firefox is really doing well and Google Chrome's market share is growing so you will want so support those for sure. IE is a tough one as it doesn't have the best support for standards, but if you are selling a product you will really want this.
One of the best articles that I've ever come across about the structure of an ajax web application is this one. A little outdated because it refers to XML as the primary data-interchange format, now JSON. jQuery, a javascript framework, contains excellent functionality for both DOM manipulation and AJAX calls. Both are a must in any AJAX-driven web app.

YUI and/or jQuery for a new project?

If I am starting a new project how should I pick between using YUI 2, YUI 3 and jQuery?
I know there are a bunch of questions/answers already about can you use them together, but I am trying to figure out what criteria I should be thinking about to make my decision.
Are they overlapping?
Is one better at GUI and the other better at internals?
Do they play well together? My understanding from other questions is that they can live in different namespaces, so they can live together, but that doesn't necessarily mean that it is good to use both.
Thanks!
If you are familiar with neither, I personally have found jQuery's documentation and API easier to understand than YUI's, at least for simpler things. It also appears there is more jQuery related information than YUI on stackoverflow.
YUI does have its users and supporters though, so check it out in case you end up finding it suitable for you. It's got a huge library of additional modules you can use for complex web applications.
My usual advice would be to go with whatever you're familiar with, and I say this because I don't think it's worth dropping one to start learning the other from scratch. But if you are familiar with neither, then you should check out how easy the documentation for both is to understand.
PS I would not recommend YUI2 if you're starting anew as it has been superceded by YUI3, which is much better designed.
We need more information about the type and size of the project before a proper library can be suggested.
For example, if you're building a semi-complex/large-ish web app, I would suggest Dojo or ExtJs. Otherwise, for smaller projects, jQuery might be more appropriate. I cannot comment on YUI as I have not used it.
Impossible to say without knowing more details about the project. Use jQuery or Prototype for things like DOM manipulation and making autocomplete, etc. If you need a more powerful Javascript implementation take a look at ExtJS, which is basically a full stack framework for Javascript.
Both are JS frameworks and there to help you. YUI is known to be more natural in them and more closer to the original Javascript while jQuery is known as more easy and you find more jQuery users and support around then YUI. However, as said earlier, it depends on the project, if it is likely that you will be making your own custom widgets, I will suggest you to go with YUI but if it's like a simple e-commerce website in which you just need some fancy galleries and shopping cart, go with jQuery, you will learn and implement that quickly. I am not saying that you can not go more in depth with jQuery but my impression is that jQuery is more of a CakePHP for PHP like of framework which gets you off the grounds quickly.
In my opinion there is no need for you to use them side by side in a single project, that will just produce the over-head as both do whatever you want to do in them i.e creating dialog panels, autocomplete quick searches, event related utilities etc.
I am writing down a series of beginner and mid-level tutorials for YUI users, let me know if you find them useful or if there is anything else where I can help.
http://ciitronian.com/blog/tag/yui/

Categories

Resources