When to use MVC in Javascript? - 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! :)

Related

Questions about MVC in Javascript and in general

First, I would like to ask some very basic questions about MVC in general. Simple questions, but can't find any good answer for them.
Is MVC useful for a one man project, or is it only needed, when more people work on a project to make it easier to co-op?
How big a project needs to be, to make good use of MVC. I hear everywere that I should always use MVC, but even for big projects it looks like an overkill. I can't imagine how big something would need to be, for all this overcomplicating to pay off.
I have made a single player rpg that is pretty short, and I am trying to turn it into massive multiplayer. It is all for educational purpose only. So I was thinking to redo it with MVC, but even though it has a lot of functions and data to process it still looks way to simple and clear, to bother with MVC. Maybe if I am making so small projects that I can't see the benefits of using it, I just shouldn't use it?
Will using all the MVC additional code slow down my app in visible way?
Now about Javascript, there are some solutions for MVC avaliable. Are they worth using?
Thanks
MVC is just a pattern, guidelines to organize your project and decoupling your code, so the size of the team or the project is not relevant. I've made by myself a very simple website with a list and a couple of web forms using MVC and it was pretty faster to develop than other alternatives. If you have the opportunity to work with a powerful IDE like Visual Studio, you will find that most of the common things to do for building a web page/site are already automated. And I also have worked with 12 people in a bigger project using also an MVC approach without noticing differences.
One of the main advantages of using MVC is that you can change the whole front end in the future without having to make changes in your model or controller layer.
Also, using MVC doesn't have to slow down your code, it depends on your implementation. When using ASP.MVC instead of ASP.NET, for example, the code and download times are faster, in fact. With ASP.MVC you get rid of nonsense ViewState pieces of code and the html code generated is cleaner.
In my experience, MVC is an excellent pattern to chose for working in web projects, since the front end technologies are changing very fast and it gives the flexibility to evolve with them without having to annoy about the business logic.
I hope I have helped you.
You can find more info in:
http://www.asp.net/mvc

Best practice to create Custom UI framework in JavaScript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want to create a custom UI framework in JavaScript for web applications (like Google Docs ui) (do not confuse with web application that deploy using languages like PHP, Python, etc.). However, after reading several books about web development, I understand that the best website is layered as follows:
Structure in HTML
Presentation in CSS
Behaviour in JavaScript
So there are several approaches to creating my own HTML document and control it in JavaScript. However in this approach HTML and CSS will be mixed, like in case of extJS UI. I am confused now, and I need some answers from experienced developers on how to write this kind of framework.
If HTML, CSS, and JavaScript is mixed.
What was advantages?
What was disadvantages?
Is there are other methods?
What was the usual type of creating UI frameworks?
I apologize that this answer is extremely long and at times may seem somewhat off-topic, but please keep in mind that the question was not very specific. If it is improved, or made less general, then I will gladly remove the superfluous parts, but until then, just bear with me. This is somewhat of a compilation of the other answers here, in addition to my own thoughts and research. Hopefully my ramblings will be at least somewhat helpful for answering this question.
General Tips for Frameworks
Frameworks are a ton of work, so don't spend all of that time for nothing. Work Smarter, Not Harder. In general, you should remember these things when creating a framework:
Don't Reinvent the wheel: There are tons of great frameworks out there, and if you create a framework that does the exact same thing as another framework, you've wasted a ton of your time. Of course, understanding what goes on inside another library is a great way to make your own library better. Quoting #ShadowScripter, "knowledge -> innovation." However, don't try to rewrite jQuery by yourself. :)
Solve a Problem: All good frameworks (and programs) start with a problem they are trying to solve, then design an elegant solution to solve this problem. So don't just start writing code to "create a custom UI framework," but rather come up with a specific problem you want to solve, or something you want to make easier. jQuery makes selecting and manipulating the DOM easier. Modernizr helps developers identify the features supported by a browser. Knowing the purpose of your framework will make it more worthwhile, and may even give it a chance of becoming popular.
Fork, don't rewrite: If the problem you aim to solve is already partially solved by another framework, then fork that framework and modify it to fully fit your needs. There's no shame in building of the work of others.
Optimize and Test: This is kind of a no-brainer, but before publishing version 1.0 on your website, test every single part of the function, under every single possible scenario, to make sure it won't crash and burn in production. Also, another no-brainer, minify your code (after testing) for performance benefits.
DRY and KISS: Don't repeat yourself, and keep it simple, stupid. Pretty self-explanatory.
Stick to Stable: (This is mostly my personal opinion) Unless you're trying to create a framework specifically targetted to HTML5 in Chrome 31, using experimental features and unstable code will make your framework slower, uncompatible with older browsers, and harder to develop with.
Open Source: (Another of my opinions) It takes years for huge companies like Google with thousands of dollars invested to create frameworks (e.g. AngularJS) so it is an excellent idea to make your source openly available. Having a community of developers contributing to your project will make development faster, and will make the end product faster, bug-free, and better all around. Of course, if you're going to sell it, that's another story...
For more information about best practices when making libraries, take a look at these links:
Javascript Library Design
Javascript Module Pattern: In Depth
Best Practices in Javascript Library Design
Building a Javascript Library
Types of Frameworks
The first thing you need to think about, as mentioned above, is what functionality you want your framework to provide. Here are is the list of types of frameworks/libraries (thanks to #prong for the link). For a much more comprehensive list, see jster, which has 1478 libraries, put into 8 categories, each with several subcategories.
DOM (manipulation) related
GUI-related (Widget libraries)
Graphical/Visualization (Canvas or SVG related)
Web-application related (MVC, MVVM, or otherwise)
Pure Javascript/AJAX
Template Systems
Unit Testing
Other
As you can see from the link, there are already dozens of libraries and frameworks in each of these categories, so there's not exactly much room for something new. That being said, I don't want to discourage you- who knows, you could create the next bootstrap or jQuery. So, here are some resources about each type of framework.
Note: you can't say that any type is better than the others, they simply are designed for different goals. It's like comparing apples and oranges.
DOM (manipulation) related
These types of libraries are designed to interact with, modify, and control the DOM of a website. Here are just a few of the things they do:
Select Elements in the DOM ($("div#id .class"))
Add/Remove Elements in the DOM ($("div#id .class").remove())
Edit Attributes of Elements in the DOM ($(div#id .class).height("30px"))
Edit CSS of Elements in the DOM ($(div#id .class).css("property","value"))
Add listeners for various events taking place in the DOM ($(div#id .class).click(callback))
The most notable of these, of course, is jQuery, and it has one of the largest user bases of any Javascript library. However, it is by no means perfect, and if your library wants to compete, the best thing to do would be to make it excel in the areas that jQuery fails- speed, fragmentation, and "spaghetti" code. (The last two aren't completely in your control, but there are certainly things that you can do to make it easier for users to use the most update version, and keep their code maintainable)
GUI-related (Widget libraries)
I think that this may be the type of framework you're looking to create. These types of libraries provide widgets (datepickers, accordians, sliders, tabs, etc.), interactions (drag, drop, sort, etc.) and effects (show, hide, animations, etc.). For these, people are looking for quantity- the best frameworks out there have several useful widgets/effects that work well. This is one case where it's "the more, the merrier," of course, if it works properly.
Graphical/Visualization (Canvas or SVG related)
The purpose of these libraries is to control animations on the page, specifically on an HTML5 Canvas. These feature animations and sprites for games, interactive charts, and other animations. Again, successful graphical libraries have many, many sprites/animations. For example kineticjs has over 20 different sprites available. However, make sure that quantity does not compromise performance and overall quality.
Web-application related (MVC, MVVM, or otherwise)
Basically, the idea is to provide a layout for the users to put their code in, typically separating the model (data) from the view(what the user sees), with a small controller to provide an interface between these two. This is known as MVC. While it is by no means the only software pattern to base a framework off of, it has become quite popular recently, as it makes development much easier (that's why Rails is so popular).
Pure Javascript- AJAX
This should really be two categories. The first, AJAX libraries, are often paired with a server side library and/or database (though not always) and are designed to make connections with a server and get data asynchronously. The second, "Pure Javascript" are designed to make Javascript easier to program in, as a language, provide helpful functions and programming constructs.
Template Systems
This might also be the type of framework you're looking to create. The idea is to provide components that developers can use. There's a thin line between Template Frameworks and Widget Frameworks (which twitter bootstrap, one of the most popular template frameworks, crosses a lot). While widget frameworks just give a bunch of little elements that can be put in a site, template frameworks give structure to a website (e.g. responsive columns), in addition to making it look good.
Unit Testing
This type of framework is designed to let developers test, or systematically ensure the correctness, of their code. Pretty boring, but also really useful.
Other
This type of framework is for really specific purposes that don't really fit into any of these other categories. For example, MathQuill is designed for rendering math interactively in web pages. It doesn't really fit into any other category. However, these types of frameworks aren't bad or useless, they're just unique. A perfect example is Modernizr, a library for detecting a browser's support for features. While it doesn't really have any direct competitors, can't be put into any of the other categories, and does a very small task, it works very well, and is very popular as a result.
More Types
There are a bunch of other types of libraries. Below are the categories (I'm not listing subcategories because that would take half an hour to copy down) that JSter puts their 1478 libraries into:
Essentials
UI
Multimedia
Graphics
Data
Development
Utilities
Applications
It depends on what you really want. The first distinction that needs to be made is between a Javascript UI framework (which provides structure to the app), an HTML UI Framework (Presentation) and Widget Libs.
Javascript Frameworks such as backbone, angular, ember, and knockout provide MVC-like structure to the app.
UI frameworks such as YUI, bootstrap, and Foundation provide a consistent HTML and CSS base.
Widget Libraries such as jQuery UI, Fuel UX, and Kendo UI provide ready made widgets.
There are also fully-fledged frameworks which provide things across the board, such as Google Closure tools, Dojo with Dijit.
This Wikipedia list pretty much sums it up, and here is the comparison.
In order to find the best way to create a framework, first ask this question: Can any of the above frameworks/libraries solve all or some of the problems/requirements I have?
If something solves all the problems, you can use it right away.
If something solves your problem partially, you can start by extending/forking that project/framework.
Follow DRY and KISS rules. Only solve a problem which nobody has solved as of now.
Fortunately, there is already a good solution: Google Closure Library. This is what Google uses. It shows the approach of mixing HTML, CSS and JS. I wouldn't say it's perfect, but I believe it's one of the best ones at this moment. Its architectural principles rely on proven component based and OOP concepts, and it's accompanied with a static compiler for Javascript. It's definitely worth of studying before baking your own solution.
I'd like to say that cloudcoder2000's answer sums it up nicely. I'm just writing this answer because it didn't seem right in the comment section :P
If you are thinking of making another framework, my suggesting is to stop thinking.
First find the thing in current implementations which troubles you the most, and try to find how you can improve it. Contribute to existing projects, nearly all of them are open source anyways. Also, you don't really need to be a JS-ninja to get into their midst. Take a fork, and get started. Once you're done, and feel that you're code is good enough, make it known to the original repo's maintainers that you have done improvements, and are looking for it to be merged into the project.
Keep in mind here that I'm not discouraging you from solving the problem at all.
I'm just pointing out that there are so MANY frameworks out there, wouldn't it be better if you went ahead and contributed to one of them instead of going for complete glory and implementing a full framework yourself? Making a framework is hard, but getting people interested in your framework is HARD. Really Really HARD, even for Google! Only once Angular got a very good documentation (which itself took quite some time, and resources, of Angular evangelists), that it has gathered so much steam. So, I'm just saying that instead of creating your own monument, perhaps lending a hand to others would be a more worthwhile exercise.
Most importantly though, is the fact that since you are just starting out, I presume you wouldn't have much experience designing frameworks, or thinking in those design terms even. It would of immense value if you contribute to existing projects. Then you will be gathering knowledge and experience of how things are built. Then, you'll be more confident. Then, you can go ahead and make your own framework! Then you'll be more equipped to tackle mammoth projects such as designing a framework. And Then, my friend, will you make something which would be worth the time of countless developers.
Short answer
Build a skinny DOM and only focus on JS code to make it more efficient.
Long answer
A good architect always replies with "it depends." You can't have one single framework that enjoys all others' benefits and suffers from no disadvantages, all at once. There's always a trade-off.
In order to create a framework that is really lightweight, you would probably want the lightest DOM (HTML) structure. However, having a skinny DOM might have the cost of more JS code. So you would probably try to write the most efficient code. You can start here.
Needless to say, you should be keeping the open-close principle, and have the stylesheets separated from HTML, using only classes and never inline styling. I would suggest using less. It makes the implementation faster, and the result is pure css so you suffer from no performance issues around it.
I must respectfully disagree with cloudcoder2000,
From a young age I have been being told don't re-invent the wheel, but why?
During the last 3.5 years, I have re-invented almost all of my web controls using javascript/html/css. From the extremely complex; for example a grid, rich text editor, tree view, dialog. To the very simple, like a progress bar, dropdown. What I gained is a better understanding of html/js/css.
No pain, no gain. I'm so happy with what I was doing these years as I learned more than others.
Some of the controls I re-invented, I think, are much better than the popular ones, like telerik, jquery mobile, extJS. For example, my tree view is fully customizable, with it one can build very complex trees.
So, I encourage you re-invent the wheels, and you will definitely get more than you expected. But also, from the beginning, you need to learn the source code of the popular controls, and re-invent them. You will be very happy when you find yourself be able to make the controls better.
Then the tips on creating HTML controls:
1. use jquery;
2. write jquery plugins(jQuery.prototype...) for simple controls, while define classes for complex controls;
3. separate css from html and js files. Define the html template in js, don't use html files, which make using the controls hard.
Regards,
Leo
For best performance in your UI design, you need to use a lightweight JavaScript framework like angular or backbone, Twitter Bootstrap for the UI, AJAX for base script load and use gzip compression in your app to make it lightweight and help the UI render faster.

CakePHP developer tries out JavaScript MV*. Gets confused

I have a few years' background with server-side MVC app development using CakePHP and a few more with vanilla PHP. Sadly I can't say the same about JS apps, although I do have experience in spicing up static pages with Mootools.
So now I'm trying to study client-side app building and my success so far hasn't been so great. Since the only MVC I've touched is CakePHP, every JS MV* framework seem incomprehensible at best. It doesn't help at all that I've grown so accustomed to writing neat CakePHP and Mootools Class code that big blocks of JS code feel just disorderly.
I've even tried to write my own simple MVC-like lib by imitating CakePHP for mostly academic use. I guess it's needless to say that I haven't really gotten anywhere with it.
Some things I realised while studying and writing my own MVC:
Js is asynchronous. CakePHP works the way it does because PHP is synchronous. In JS there's an endless list of things that need to be implemented differently and about just as long list of things that can be done differently thanks to async. What are the most important differences between server-side MVC(or CakePHP implementation of it) and client-side MV*?
I still don't quite get the concept of client-side models. In Cake they handle data validation and database connections. Client on the other hand is an unsafe environment, so client-side models can only do basic data filtering, pre-validation and default values. Am I completely wrong here?
Some apps require a server counterpart. Should Server also be MVC?
It seems that in client-side MV* you can have multiple controllers simultaneously. Although I kind of understand that it has its uses, my knowledge at this point is so little I can't even think of a better question than "What good does it do?"
I've also downloaded TodoMVC and tried to examine the different frameworks with little success. The main problems with it are that it's only single-page(actions happen at different urls but the layout stays the same) and the implementations are so different that I'm having hard time even comprehending the basics, let alone finding the best suited framework for me. Also, it doesn't communicate with the server in any way, which is a huge disappointment since I'd wanted to see how different frameworks do that.
So, the optimal answer to this question would be a link to a book called Client-side JavaScript MV* For Dummies (Who only have experience in server-side MVC), which would earn you somewhere around 500 internets in addition to the regular StackOverflow rewards.
I would be extremely thankful for any insight(ful links) on any of my ramblingly written question's topics. You will be rewarded with the standard +1s and as a further incentive I promise to write your nickname on a post-it note and keep it on my monitor for the next month. The person with the most helpful answer of course gets an Accepted and additionally may provide a picture to be printed along their nickname to be attached to my monitor.
I'm interested to know where you ended up on this one. PHP was my first love, and while I still enjoy the ease of the language, it's hard to really take it seriously when it so clearly is being phased out for faster, more scalable technologies.
You hit it on the head that javascript's asynchronousness complicates things, but it definitely opens the doors for performance increases. There are quite a few libraries (more for node.js than client side work) that aim to make javascript written as if it's synchronous - again I don't see it helping with your current ask, but it's good to know other's share your pain.
I think MVC in javascript can be thought of like this:
M: the models are simply an explanation of your data. So if you have a person, you can say that every person has a first name that's a string, an age that's an int and so on. Now whenever you create a new person, you can have validation. Models, client side, tend to be very simple, I've found.
V: views are another interesting thing. Some like to have a big set of render functions that contain strings of HTML (ew). Other's like to have the views just be a wrapper for a templating engine like handlebars.js (probably a better solution).
C: functions pretty much identically to a controller in PHP.
My advice for you would be to NOT write you own, but rather take Backbone.js (quicky becoming the industry standard), learn it inside and out, and perhaps build on top of it.
Good luck!

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/

What is better, One javascript framework, or multiple frameworks

I am an avid user of the YUI framework (http://developer.yahoo.com/yui/). It has its' strengths and weaknesses both performance wise and syntax wise. I have seen a bit of JQuery and I have worked a little with prototype as well but I have stuck mainly to YUI. My question is, is it better to stick with one Javascript library per application, or leverage the abilities of multiple javascript frameworks in your application?
I think it is better to use one framework for at least two reasons:
1. Code is easy to maintain because there is no syntax mix.
2. Application loads a little faster and I think should execute little faster.
My guess is that multiple frameworks is better as long as each has its purpose. If I'm building an ASP.Net web application with AJAX functionality, there may be some built-in ASP.Net AJAX Javascript libraries being used automatically that can be combined with JQuery to handle some situations. Alternatively, one could have third-party controls like Telerik's RAD controls that also bring in more Javascript code possibly. The key is to understand what each framework is adding in terms of rolling your own.
Sure less frameworks in the same website will make your life easier, so try as you can to use one framework, and if you are going to use more than one, take care from conflicts and redundancy.
If i am in your place, i will start searching the framework i have for some plugins and updates, if didn't find will add the new framework.
One more point: don't panic from using more than one framework, the big and famous frameworks such as jquery has its implementations to solve conflicts and work side by side with other javascript libraries
Also... if you use 2 diffrent frameworks at the same time, some functions in one framework could override an function in the other framework, and make ugly conflicts.. e.g the $() could be implemented in diffrent ways, and make something crash, if other functions of the framework is using it. (and they sure do!)
I think its better to use 1 framework in your development, for consistency of API and loading speed. the problem sometime is no framework is comprehensive enough to have all of our development needs.
This is just came into mailbox, their advertisement saying it's a comprehensive framework, with plenty of widget: grid with grouping, charts, forms, tab, fields and so. I haven't play it long, but it seems very promising. check here

Categories

Resources