I know that MVC is highly acclaimed for PHP applications, but I am not sure at all that it fits in JavaScript. If you think otherwise, then please explain how and where you handle common scenarios like AJAX requests, data saving (offline storage), presentation, how do you handle controller logic (do you have a front controller?), and so forth.
What about Model-View-Presentation?
I am using ExtJS and using the server only for permanent data storage.
If you're planning on coding your UI purely with JavaScript, you could think your PHP end of things as more of a web service or an API.
Basically your View would be the Ext JS stuff you write in JS. To work with your data, the Ext frontend would perform requests to your "service". Basically you would have a sort of model-controller architecture on your server, where the job of the controller would be to process requests and output JSON (for consumption by your Ext frontend)
Essentially, the "view" in your backend would simply be output from json_encode, which is then consumed by your actual Ext based view.
In JS, you can have controllers depending on what sort of stuff you're doing. If you're just displaying data from the server, you may not require much separate logic. If you're doing some more complex processing, it may be useful to separate the code into a separate controller and view.
It's mostly up to how much you want to separate the logic.
When writing almost complete javascript applications you can think of MVC as:
View: The DOM
Controller: Your JavaScript
Model: Combination of JavaScript Ajax Calls and their PHP (or whatever) backend counterparts
PureMVC is an extremely cool MVC framework. You should check it out.
I'm using the same architecture: predominantly ExtJS on top of a PHP back-end.
My solution:
Strict JSON-RPC communication with the server. The server-side API is clean enough that it's also our third-party interfacing API. Forcing the API to be the same one that third-party interfaces use makes you keep the server-side code clean and minimal, which is good for security and performance.
Heavily componentized architecture, split into modules that group components (Ext.Panel derivatives usually). Each component knows how to request its initial configuration and data via JSON-RPC calls, render itself, and save its state if necessary. I try to keep the communication between components clean and documented.
On-demand architecture, loading in additional components via javascript files as needed. The entire code is designed to be initialized via callbacks, so that components can load their dependancies from the server and render only an empty placeholder before they initialize themselves.
Individual components may employ an MVC pattern, where it makes sense. Ext tends to encourage MVC anyway, separating data out into stores and having a separate rendering infrastructure (although it does blend controller logic with the rendered components).
I'm not sure I understand where you are going with your question, but I'll give it a shot.
MVC is an architectural pattern which in its essence means keeping the data model, the controller and the UI loosely coupled as much as possible.
You are trying to boil it down to the technological level, and it's not really making any sense. You can do proper MVC with a good framework. Just to make things clear, plain-vanilla PHP does not give you good MVC support. A good framework, such as CakePHP or CodeIgniter - will.
JS is just a nice way to enrich the client-side experience. Meaning that unless you are doing server-side JS, the only place you will have JS is in the view itself. AJAX requests have nothing to do with MVC, per-se. Neither does data persistence. Unless you are implementing your own controller (and you better have a damn good reason to do so yourself), you shouldn't be worried about its internal logic.
Bottom line, if you want to do proper MVC, use a proper framework, and all will fall into place.
Related
So I'm afraid I might be missing something pretty fundamental here, but I really can't get my head around this - Why? Why would we want to use those JS MVC frameworks, instead of sticking with Rails, Django, PHP and so on?
What do these JS frameworks give us that can't be achieved by the old web frameworks? I read about SPA, and there's nothing I couldn't do there with ASP.NET MVC, right?
I'm really baffled by hearing all the people at work wanting to leave our current framework for these new ones, and it's much more than just for the sake of learning something new.
I am totally up for that, and I've always tried playing around with other frameworks to see what I'm missing, but perhaps these new technologies have something really big to offer that I simply cannot see?
Single page applications provide a better experience by having all page transitions be seamless. This means you never see the "page flash" between user actions, in addition to a few other user experience improvements.
Front-end frameworks also generally provide a common way to interface with APIs. So instead of writing an AJAX wrapper for every page in your site, you just say 'This page has this route (path), hooks data with this schema from that API endpoint and presents it with these templates and helpers.' There are many proponents of APIs, because there are many good reason to write you applications from a service standpoint. This talk sums up a lot of the points in favor of APIs. To summarize:
Orchestrating your web offerings as services makes them inherently decoupled. This means they are easily changed out. All the reasons behind strong Object Oriented design principles apply equally to the larger parts of an application. Treat each piece as an independent part, like a car, and the whole platform is more robust and healthy. That way, a defect in the headlights doesn't cause the motor to blow up.
This is very similar to how a SOAP WSDL works, except you have the auto creation tools right out of the box.
Having well defined touch points for each part of your application makes it easier for others to interface with. This may not ever factor into your specific business, but a number of very successful web companies (Google/Yahoo, Amazon AWS) have created very lucrative markets on this principle. In this way, you can have multiple products supported by the same touch points, which cuts a lot of the work out of product development.
As other point out, the front end framework is not a replacement for the backend, server technologies. How could it be? While this may seem like a hindrance ("Great, now we have two products to support!"), it is actually a great boon. Now your front and back ends can be changed and version with much less concern over inadvertently breaking one or the other. As long as you stick to the contract, things will "Just WorkTM".
To answer your additional question in the comment, that is exactly correct. You use a front end framework for handling all the customer interaction and a completely separate back-end technology stack to support it.
I'm forgetting a few good ones...
Angular, Ember, and Backbone are client-side JavaScript frameworks. They could be used interchangeably with a Rails, Django, or PHP backend. These JavaScript MVCs are only responsible for organizing JavaScript code in the browser and don't really care how their data is handled or persisted server-side.
Django/Rails etc are server-side MVC frameworks. Angular/Backbone etc are client-side Javascript MVC frameworks. Django/Rails and Angular/Backbone work together - in a single-page app, usually the server-side MVC will serve the initial HTML/JS/static assets once, and then once that is done, the client-side router will take over and handle all subsequent navigations/interactions with your app.
The difference here lies in the concept of what a "single-page application" is. Think about how a "regular" web Django/Rails website works. A user enters your app, the backend fetches data and serves a page. A user clicks on a link, which triggers the server to serve a new page, which causes the entire page to reload. These traditional types of websites are basically stateless, except for things like cookies/sessions etc.
In contrast, a single-page application is a stateful Javascript application that runs in the browser and appears to act like a traditional webapp in that you can click on things and navigate around as usual, but the page never reloads, instead, specific DOM nodes have their contents refreshed according to the logic of your application. To achieve a pure Javascript client-side experience like this in a maintainable fashion really requires that you start organizing your Javascript code for the same reasons you do on the server - you have a router which takes a URL path and interacts with a controller that often contains the logic for showing/hiding views for a particular URL, you have a model which encapsulates your data (think of a model as roughly one "row" of a database result) which your views consume. And because it's Javascript there are events going on, so you can have your view listen for changes in it's associated model and automatically re-render itself when the data is updated.
Also keep in mind that you don't just have one view on the client side, there are usually many separate views that make up a page and these views are often nested, not only for organizational purposes but because we want the ability to only refresh the parts of the UI that need to be refreshed.
The intro to Backbone is probably a good starter on the topic: http://backbonejs.org/#introduction
Check this article, there is well explained how a modern web application should looks like in the client side, server side and the communication between them.
By the way:
Client side -> Ember, Angular, Backbone, Knockout.
Server side -> Django, Node, Rails
I am developing a standard rails application, and so far I haven't used any AJAX, just good ol' HTML. My plan is to iteratively add "remote" links and all that kind of stuff and support for JS responses, because I know that generating JS server side is very very evil, but I find it to be very handy as well, easy, fast and it makes the application snappy enough and i18n comes out-of-the-box.
Using a pure JSON approach would be lighter, but needs lots of client-side coding.
Now imagine that in this application users have a mailbox, and since the idea is that they will be able to do most or even all of the actions without reloading the page, the mailbox counter will never change unless they refresh the page manually.
So, here comes the question: Which is the best way to handle this?
I thought about using Ember (for data binding), and sharing views with rails, via some sort of handlebars implementation for ruby. That would be quite awesome, but not very transparent for the developer (me). Although I guess that I only need to write handlebars views that will be used by ember, the rest can still be written in their original format, no?
Another option might be to use some sort of event system (EventSource maybe?), and just go with handy the JS views approach, and listen to those events. I guess those should be JSON objects, and the client must be coded to be able to handle them. This seems a bit cumbersome, and I need a solution for heroku (faye?), which is where my app is hosted. Any hints?
I think that the ember approach is the more robust one, but seems to be quite complex as well, and I don't want to repeat myself server and client side.
EDIT:
I have seen this, which is more or less the option #2.
One of the advantages of using a JavaScript framework is that the whole application can be concatenated and compressed into one JavaScript file. Provided that modern browsers aggressively cache JavaScript, the browser would no longer need to request those assets after initial page load.
Another advantage of using a JavaScript framework is that it requires you to be a consumer of your own API. Fleshing out the application's API for your own consumption might lend to less work in the future if there is a possibility of mobile applications or 3rd parties having access to it.
If you do not need your application to respond to every request with an equivalent HTML response, I think a compelling case could be made for using a JavaScript framework.
Many of those benefits might be lost if your application needs to respond to every request with an equivalent HTML template. The Ember core has been relatively vocal and in opposition to supporting this style of progressive enhancement. Considering the tools for using a JavaScript framework in this way are relatively unstable and immature, I might be prone to using option 2 to accomplish this.
Until now I was mainly using Struts 2, Spring, JQuery technology stack for building web applications. The point is, that mentioned stack uses server side MVC pattern. The main role of web browsers was limited to a request/response cycle (+ client side validation). Data retrieval, business logic, wiring and validation were mainly responsibilities of the server side.
I have few questions regarding AngularJS framework that were inspired by following quotes I've read:
From the AngularJS tutorial:
For Angular apps, we encourage the use of the Model-View-Controller
(MVC) design pattern to decouple the code and to separate concerns.
From the Wikipedia Model–view–controller:
Model–View–Controller (MVC) is an architecture that separates the
representation of information from the user's interaction with
it. The model consists of application data and business rules,
and the controller mediates input, converting it to commands for the
model or view
AngularJS uses client side MVC pattern. So I guess there is no other option then to include validation logic also to the client side in some way?
What would be the best way to write a robust AngularJS application? MVC on client side and some kind of MC (model, controller) on server side?
Does that mean, that MODEL and CONTROLLER are in one way duplicated (client/server)?
I know my question is somehow weird, but I think the reason is, that I am somehow acustomed to traditional server side MVC pattern. I am sure there is someone, that have already done same transition.
Not at all a weird question - I've been trying to sell Angular to a lot of java developers and they ask this. I asked it myself when I was learning (I'm still learning, btw)
If you take a 'conventional' java webapp as you've described and Angular-ize it, you've got to first take your server and make it a RESTful API. Remove the JSPs, etc. This is actually the hard part, IMO, of writing an Angular app - getting the REST API right. The key for me to deciding what logic needed to go into the server was thinking of it as a pure api and forgetting for the moment that it will have a front end.
That question really helped me - if someone tries to save a given resource and that resource doesn't have valid data there's no front end to tell them - they're hitting the API directly so the API needs to reject it. So, the back end is responsible for the deep validation. This applies to your business logic as well. Assume someone is using just the API and it will become clear what your server needs to do.
The server needs also to vend data in (probably) json format (I use Spring MVC + Jackson), so it's responsible for exposing the model to Angular, and communication with the database.
So what's the MVC then on the Angular side?
Model: The data that comes from the REST API. If the API is vending JSON, then these objects will already be 1st class javascript objects.
View: HTML, and directives when you need to manipulate the DOM
Controller: (and custom services that you've factored out of your controllers..)
Queries the REST API and puts what's necessary for the View on the $scope
Provides callbacks for directives to respond to events that might then require calls back to the server.
Validation: usually via a callback to a directive. Will likely overlap some of the validation you've already put in the server, but you don't want your user to wait for the server to validate everything - the client should know something about the validation to give the user immediate feedback.
Business logic: Pretty much the same story as validation.
But why the duplication of logic in the client and in the server? Mostly because you're not writing one app, you're writing two independent things:
a REST API that needs to be robust and usable without a front end
a GUI that needs to give immediate feedback to a user and not necessarily wait for a server.
So, short answer - get the REST API right by forgetting that there will be a UI, and what goes into Angular will be much clearer.
I think the term "business logic" is a bit of a misnomer here. The "business" of a clientside app is the business of handling the user interface. It's not going to be things like security rules and proprietary logic or other sensitive intellectual property.
So in Angular the division is (generally):
Controller (controller): for manipulating the data (scope) behind your UI.
Directives : for setting up the DOM to communicate with the controller via scope, and for manipulating the DOM.
Templates (view): To assign directives to elements of the DOM.
Scope (model or viewmodel): for carrying data between all pieces of the system.
Services : Injectable, reusable bits of code. Usually for dependencies like handling Ajax, cookies, or other I/O.
It's really almost MVVM and not MVC.
As for your "business" logic or rules... anything requiring security must always be secured at the server level.
It's important to understand that in some versions of the MVC pattern, the data as well as the logic that manipulates the data both reside in the "model" layer (with the "controller" layer doing nothing but binding). In AngularJS, however, the data ($scope) alone resides in the "model" layer, while the logic that manipulates the data ($scope) resides in the "controller" layer.
I love what #Roy TrueLove says. But let me say that this is the ultimate way of using angularjs. Of course, you have to learn to do your applications this way, if you want to get the most benefit of angular. I pray to be there some day.
In the meanwhile, during your learning, and during your transition to fully using angularjs as your client side main way of doing things, you can start using it for some small mission here and there, and gradually get accustomed to it and to its way of thinking.
I encourage to gradually embracing it and to go slowly slowly, but surely, I guaranty, sure.
Angularjs is designed to serve this approach, as it can work on the smallest task as good as it can do the biggest one. For example, this first time I used angular was just to show names while the user types ids.
I agree with the answers here. Some more comments. When you write an applicacion, you first need to concentrate on the problem domain. And create a software model of some real business. For example, if your problem domain is a shopping, some requirements that you need to model might include:
The credit card should be valid.
If you pay with a credit card of brand X, you will receive a 10% of discount.
The shop cart should contain at least one item to perform the checkout
The items must have stock before allow users to add them to the shop cart
The implementation of these requirements will model your problem domain, this is your business logic.
Angular is a frontend framework and toolkit. It is a web frontend. If you implement this in a web frontend, you will miss the oportunity to reuse your model from other frontend or interface, like a mobile or a desktop application.
So, ideally, your business logic implementation needs to be decoupled from any user interface framework and decoupled from any persistent framework also. Then, you will have your interface objects that will deal with user interface problems and will comunicate with your business logic objects. This can be a Spring MVC controller, and/or an Angular controller or service.
There is a sample application you can take a look at, that follow the principles mentioned here.
I seems to be having this question as well, as some organizations just craze for new technologies - "I want cloud...wait, I want lightweight", its hard to justify whether it deserve for the switch to a lighther framework.
I develop webapplications using Spring/JBoss seam/JSF and on MVC framework all the time. Most of the time java scripts will reside for the presentation layer validations and the main action classes/entities and business logic will reside in Java code. After some basic hands-on on Angular, I started to get what they meant by MVC as they abstracted another level on the presentation layer, where we can have our own views and controllers on the front end. To answer your question, just like everyone's comment the best way is to lay it on the presentation layer.
As for security point of view, I believe heavy or sensitive business rules should reside on the server side as we do not want to expose it to the world. If the business logic is developed poorly, one can easily find the weakness on our code and exploit it.
Here's my thought for framework like Angular is like a small shop/SOHO handling customer, and they have a few people and really efficient and fast.They cater well for customers facing business and delivery/receive goods efficiently(REST, JSON). They do have designated roles and tasks, but some worker perform more than a tasks. The shop also vulnerable to thief or robbers as usually they don't emphasize heavy security.
As for server side framework like Spring/Struts 2, imagine a modern corporation(CMM Level 5) with different level of management and capable of handling bigger business(batch jobs, web services, enterprise bus). They do handle customer, but not directly, often go through brokers or even retail shops. Security wise a corporation is more robust, and often securities on the front door, or important information are protected in a safe(encryption/sign-on).
My approach is always the bottom-up approach. Starting from the Database Design, with properly constructed / related tables, stored procedures when needed, then add the Entity Framework to the solution or use ADO.Net if EF is not an option. Then develop the Business Logic, and the Models to get the data in and out the database.
With the Models established, we can now go two routes: Developing MVC Controller, and / or developing WebAPI controller. Both controllers can have access to the Models, it's just a matter of instantiating the classes and invoking the methods.
You now have the option of setting up MVC Views that are controlled by the MVC controller, or, entirely separate set of HTML pages or SPA (Single-Page Application hosted on NodeJS).
With the entirely separate set of HTML page, you will need to use WebAPI controllers, with Get, Post, Put, and Delete methods, and be sure to include token back and forth to identify your client, and enable CORS (for Cross Origin Request)
With MVC Views, you can identify your clients using the controller attributes, and / or sessions and no need to worry about CORS, and, you can even make your Views Strongly-Typed if needed. Unfortunately if you have a set of UI developers they will have to work on the same MVC solution.
In both cases, you can use AngularJS to transport data back and forth from / to the controllers.
IMHO the concept of AngularJS controller is not the same with C# MVC or C# WebAPI controller. AngularJS controller house all the javascript logic as well as the calls to endpoints via the "ApiFactory", whereas C# controllers are nothing but Endpoints in the server side that accept and respond to UI requests.
I am just starting to look at MVC structure, first i looked at how backbone.js worked, and now I have just completed rails for zombies, by Code School. I know that I haven't delved too far into any of this, but I had a question to begin with.
Can you use these libraries together?
I have learned how to create models, views, etc in both, but when creating a real application do you use both backbone and rails?
If so...
When do you use a backbone.js model vs. a rails model?
Maybe I am just getting ahead of myself and need to keep practicing and doing tutorials but I couldn't seem to find anything directly on this.
Thanks!
Before anything else I'd suggest taking a look at thoughtbot's Backbone.js on Rails book, which is a great starting point, although aimed at an intermediate to advanced audience. I bought this book having already worked with rails but as a total backbone.js beginner and it has served me very well.
Beyond that, there are some fundamental issues with combining these frameworks which go beyond the details covered in this book and other books. Below are some things I'd suggest you think about, from my own experiences pairing RoR and backbone.js. This is a long answer and strays a bit from the specifics of your question, but I hope it might help you out in the "big picture" sense of understanding the problem you're facing.
Rails: Web Framework vs API
The first thing you confront when using backbone.js on top of a rails application is what to do about views, but this is really just the surface of a much deeper issue. The problem goes to the very heart of what it means to create a RESTful web service.
Rails is set up out of the box to encourage its users to create RESTful services, by structuring routing in terms of a set of resources accessed at uniform URIs (defined in your routes.rb file) through standard HTTP actions. So if you have a Post model, you can:
Get all posts by sending GET request to /posts
Create a new post by sending a GET request to /posts/new, filling out the form and sending it (a POST request) to /posts
Update a post with id 123 by sending a GET request to /posts/123/edit, filling out the form and sending it (a PUT request) to posts/123
Destroy a post with id 123 by sending a DELETE request to /posts/123
The key thing to remember about this aspect of Rails is that it is fundamentally stateless: regardless of what I was doing previously, I can create a new Post simply by sending a POST request with a valid form data to the correct URI, say /posts. Of course there are caveats: I may need to be logged in (have a session cookie identifying me), but in essence Rails doesn't really care what I was doing before I sent that request. I could follow it up by updating another post, or by sending a valid action to whatever other resources are made available to me.
This aspect of how Rails is designed makes it relatively easy to turn a (Javascript-light) Rails web application into an API: the resources will be similar or the same, the web framework returning HTML pages while the API (typically) returns data in JSON or XML format.
Backbone.js: A new stateful layer
Backbone is also based on RESTful resources. Whenever you create, update or destroy a backbone.js model, you do so via the standard HTTP actions sent to URIs which assume a RESTful architecture of the kind described above. This makes it ideal for integrating with RESTful services like RoR.
But there is a subtle point to be stressed here: backbone.js integrates seamlessly with Rails as an API. That is to say, if you strip away the HTML views and just use Rails for serving RESTful resources, integrating with the database, performing session management, etc., then it integrates very nicely with the structure that backbone.js provides for client-side code. Many people argue that there's nothing wrong with using rails this way, and I think in many ways they are right.
The complications arise though from the issue of what to do with that other part of Rails that we've just thrown away: the views and what they represent.
Stateful humans, stateless machines
This is actually more important than it may initially seem. HTML views represent the stateless interface that humans use for accessing the RESTful resources your service provides. Doing away with them leaves you with two access points:
For humans: a rich, client-side interface provided by the backbone.js layer (stateful)
For machines: a resource-oriented RESTful API provided by the rails layer (stateless)
Notice that there is no longer a stateless (RESTful) interface for humans. In contrast, in a traditional rails app with an API, we had something closer to this:
HTML resources for humans (stateless)
JSON/XML resources (API) for machines (stateless)
The latter two interfaces for accessing resources are much closer in nature to each other than the previous two. Just think for example of rails' respond_with, which takes advantage of the similarities to wrap various RESTful responders in a unified method.
Working together
This might all seem very abstract and beside the point, I know. To try to make it more concrete, consider the following problem, which gets back to your question about getting rails and backbone.js to work together. In this problem, you want to:
Create a web service with a rich client-side experience using backbone.js, with rails as the back end serving resources in JSON format.
Use pushState to give each page in the app a URL (e.g. /posts/123) which can be accessed directly (by entering it into the browser bar).
For each of these URLs, also serve an HTML page for clients without javascript.
These are not unusual demands for a modern web service, but they create a complex challenge. To make a long story short, you now have to create two "human-oriented" layers:
Stateful client-side interface (backbone.js templates and views)
Stateless HTML resources (Rails HTML views)
The complexity of actually doing this leads many nowadays to abandon the latter of these two and just offer a rich client-side interface. What you decide to do depends on your goals and what you want to achieve, but it's worth thinking about this problem carefully.
As another possible reference for doing that, I'd suggest having a look at O'Reilly's RESTful Web Services. It might seem odd to be recommending a book on REST in a question about Rails and Backbone.js, but actually I think this is the key piece that fits these very different frameworks together, and understanding it more fully will help you take advantage of the strengths of both.
Yes, you can use both side by side. Backbone is for storing and manipulating data within the client browser. It generally needs a server to talk to and fetch the data from. This is where Rails comes in. You can have a web application without heavy client-side code. Backbone is for building out sites that feel more like apps--think of Gmail or Pandora.
I advise just learning Rails first. Once you can get static pages loading and styled as you wish, then understanding Backbone's place will make more sense
I've used rails as a backend server to serve a fairly large website, which included a few one-page apps (built in backbone).
I'd suggest the backbone-on-rails gem. The idea is that your rails server will serve up the backbone app as a script tag in one of your views. You keep your backbone app itself in the rails app/assets folder.
Backbone understands rails routing conventions, and you just need to give it a path to a json api that rails can almost generate for you with rails generate resource.
Other than the syncing between the models, your backbone apps and rails apps are fairly separate. Backbone and Rails don't have quite the same MVC model, but getting them to cooperate is pretty easy.
This is a pretty generic question, but I come from a few years with Flex, and I am not so much experienced with pure web development.
My question is: if you need to build an AJAX app, which one of the two approaches you would prefer:
classical server-side MVC, where controllers return views supplied with model data. Views can be full-blown or partial. Basically, there will be only a small number of full-blown views, which work as the containers, and javascript will help fill-in the gaps with partial HTML views asynchronously. This approach is one step further the traditional web development, as javascript is used only for maintaining the overall control and user interactions
A full-blown js app, such as the ones built with Cappuccino, Sproutcore, or Backbone.js, where the client side is thick, and implements a client-side implementation of MVC that handles model as well, as controlling logi, and view interactions. Server-side in this case plays the role of a set of JSON/XML services with which the client exchanges data. The disadvantage in this case is that view templates have to be loaded at the beginning, when the initial application is bootstrapped, so that javascript can layout the markup based on the data. The advantages are the reduced weight of the server response, as well the better control within the client, which allows for stuff like view-model binding to be applied.
A somewhat mixed approach between those two.
I am favoring the second one, which is normal, since I come from a similar environment, but with that one I a mostly concerned about issues such as url routing (or deeplinking as we call it in Flash), state management, modularity, and view layout (when do the view markup templates get loaded? Should there be specific server endpoints that provide those templates upon being called, so that the template data does not get loaded in the beginning?)
Please, comment
I prefer #2 myself, but I dig javascript :)
Unfortunately, I have never even seen what flex code looks like. My experience is with rails, so I will talk in those terms, but hopefully the concepts are universal enough that the answer will make sense
As for client side templates, the best is when your server side platform of choice has a story for it (like rails 3.1 asset pipeline or the jammit plugin for pre 3.1). If you are using rails I can give more info, but if you aren't the first thing I would do is look into finding an asset management system that handles this out of the box.
My fallback is generally to just embed templates into my server side templates inside of a script tag like
<script type='text/html' id='foo-template'></script>
To retrieve the string later, you can do something like this (jquery syntax)
var template = $('#foo-template').html();
In my server side templates, I will pull those script tags into their own files as partials, so I still get the file separation (rails syntax)
<%= render :partial => 'templates/foo.html.erb' %>
I much prefer just using jammit, and having my client side templates in seperate files ending in .jst, but the second approach will work anywhere, and you still get most of the same benefits.
I would recommend the second approach. The second approach (thick client thin server approach ) which you are already familiar with is the preferred approach by an increasing number of modern developers because The rendering and management of widgets is done on the client and this saves computational and bandwidth overhead on the server. Plus if you have a case of complex widget management then using server side code for widgets can become increasingly complicated and unmanageable.
The disadvantage pointed by you :
view templates have to be loaded at the beginning, when the initial
application is bootstrapped, so that javascript can layout the markup
based on the data.
is not correct. You can very well load static templates on the fly as required through ajax and then render them using javascript into full blown widgets.
For example if you have an imagegallery with an image editor component then you may not load the files required for image editor (including images, templates and widget rendering code) until user actually chooses to edit an image.
Using scriptloaders (eg. requirejs, labjs) you can initially load only a small to medium sized bootstrapping script and then load the rest of the scripts dynamically depending on the requirements.
Also, powerful and mature server side widget libraries are only available for java backends (eg vaadin). If you are working on php,python or ruby backend then writing your own server side ui framework can be a serious overkill. It is much more convenient to use client side server-agonistic javascript ui frameworks eg. dojo, qooxdoo etc.
You seem to have an inclination towards towards client side mvc frameworks. This is a nice approach but the dual mvc architecture (on server as well as well as client) often has a tendency to lead to code duplication and confusion. For this reason I wont recommend the mixed approach.
You can have a proper mvc framework in the frontend and only a server side model layer that interacts with the application through a restful api (or rpc if you are so inclined).
Since you are coming from flex background I would recommend you to check out Ajax.org ui platform http://ui.ajax.org . Their user interface framework is tag based like flex and though the project is new they have a powerful set of widgets and very impressive charting and data-binding solutions. Dojo and Ample SDK also adopt tag based widget layout system.
Qooxdoo and extjs advocate doing everything from layouting and rendering through javascript which might be inconvenient for you.
I am an architect of one mobile Web application that has 100,000 users with 20,000 of them online at the same time.
For that kind of application (e.g. limited bandwidth) #2 is the only option I think.
So server side is just a set of data services and client uses pure AJAX RPC.
In our case we use single static index.htm file that contains everything. Plus we use HTML5 manifest to reduce roundtrips to the server for scripts/styles/images on startup. Plus use of localStorage for app state persistence and caching.
As of MVC: there are many template engines out there so you can use anything that is most convenient for you. Templates by themselves are pretty compact as they do not contain any data so it is OK (in our case) to include them all.
Yes, architecture of such an application needs to be well thought upfront. #1 option is not so critical - entry level is lower.
I don't know what platform you are targeting but as I said #2 is probably the only option for mobile.