I'm trying to understanding what MVC is, why it's useful, and if I should use it or not.
In the context of dynamic websites, what are the models, views, and controllers? I've seen these as examples before, are they all right or is only one of them right?
Model: HTML, view: CSS, controller: Javascript
Model: database, backend processing; view: HTML, CSS, Javascript;
controller: HTTP (GET/POST), URLs
Model: database; view: HTML, CSS, Javascript; controller: backend
processing
Are there other examples of MVC in web development?
This is a mega-vague question, but here's one generalization...
Controller (JavaScript): Listens to clicks and notifies methods on your model/view-model.
Model (JavaScript): This encapsulates methods for serializing/deserializing data from sources like a database, public API, whatever.
ViewModel (JavaScript): This handles formatting data in your model for display by your view (e.g. pretty-formatting names, emails, numbers, etc)
View (HTML+CSS): This is what the user sees. It shows information that's described by your view-model and dispatches events that are listened to by your controller.
Related
I'm working on an application that is using both Angularjs and Asp.net MVC. One thing that I'm confused about is how exactly I should handle URL's and where should I put my partials?
For example, if I'm trying to create a modal pop up with angularjs like below:
$scope.popup = function (feedback) {
var modalInstance = $modal.open({
templateUrl: '/what/path/goes/here',
controller: 'angularjscontroller',
size: 'lg',
});
}
Do I put my html partials in the regular view folder for my serverside app?
If I need a particular partial can I use the same /Controller/controllerfunction pattern that I would use if I was strictly using a server side mvc application?
How does angular handle something like a layout.html file if I only want a specific partial?
Everything that I've found so far seems like they strictly use one or the other and not both.
Do I put my html partials in the regular view folder for my serverside
app?
I do. I create a separate controller for serving up the views, separate from the controller that serves up the data.
If I need a particular partial can I use the same
/Controller/controllerfunction pattern that I would use if I was
strictly using a server side mvc application?
Sure. As long as that controller only returns a partial view.
How does angular handle something like a layout.html file if I only
want a specific partial?
I may not understand the question here but it doesn't handle that. You need to give it the appropriate template.
Does Angular JS support having multiple ng-view sections each with its own templates on the same page? When setting up its configuration you need to wire up the different url path to different controllers and templates. But when you have multiple views on the same page, then they will each need to adjust their template and controller using the #path value from the url, and to change the view template we'll be need to switch as the #path value changes.
So how would the different ng-view sections play with each other - as each would need to append its own unique #path value to the url. Or is the url path and #value somehow kept as a private construct within each ng-view and therefore allowing multiple ng-view sections on the same page.
Multiple views is a limitation in angularjs and the documentation does not make it clear how to structure an application with complex views properly. Please have a look at Jan Varwig's posts on this topic
How to do nested views in AngularJS (Hint: Don’t)
AngularJS: Views vs. Directives
Relevant Sections:
"Views are not what you use to structure your application!
In fact, views are more of a crutch, a shortcut, to create structures similar to traditional websites, only with angular as a driver. When developing a web application, the way to deal with complex interfaces is to use, in combination:
Scope objects/variables that store your desired view state explicitly
ngSwitch directives on this view state
Directives to include custom templates/perform complex DOM manipulation behavior
Stop thinking of your application in terms of views that need to be loaded. That kind of thinking aligns better with imperative frameworks but doesn't work well in angular."
"View-Containers are meaningless, separated from their semantics through the routes.
The other, secondary gripe that I have with UI-Routers nested views is that they violate another core idea of AngularJS: Your DOM is the main place to describe the structure of your app. Reading a template should give you an idea of what goes where. If you want to edit a user, put a directive into your template:
A reader will immediately see what that directive does and what data it depends on.
If you write the directive correctly it will be location independent, you can place it somewhere else in your app, as long as you pass in a user through the attribute it will work.
Using views litters you templates with meaningless containers, outsourcing the actual purpose of every view into the routes/states defined elsewhere. If you nest routes, the context of every view becomes implicit, it is harder to move them around and the only way to pass data into a view is through the scope."
ng-route does not support multiple ng-view inside ng-app.
You can take a look at ui-router as a project which provides some support for having multiple layouts (including nested layouts) tied to the URL.
Caveat Emptor
Note: UI-Router is under active development. As such, while this
library is well-tested, the API may change. Consider using it in
production applications only if you're comfortable following a
changelog and updating your usage accordingly.
Use ui-router instead of the canned ng-route! ui-router totally has nested views, and its awesome and really easy to learn. I would reccomend using ui-router instead of ngRoute to anyone.
Having done further reading on this, it appears that although functionality for multiple ng-view has had number of requests it was not able to make it into the Angular release, but there is possibility of something in future releases.
In this discussion Misko Hevery pointed out another approach, which is to use ng-include.
Then there is also the custom directive approach in Jan Varwig's posts which Vikas has already cited.
Also found this Angular Multiple View project on github which can be a further approach.
For this sort of thing you can use templates.
Create a file e.g. firstNavigation.html which has your snippet of html. Then call it in the controller like so.
$scope.nav = 'src/partials/firstNavigation.html';
I have a canonical model with an associated view:
var Item = Backbone.Model.extend({
url: function() {
return "/item/123"
}
});
var ItemView = Backbone.View.extend({});
However, on the server-side, at url "/item/123", my Django application does not render JSON-formatted content, but an HTML template that is designed to be directly inserted inside the main page. How can I render the model without drastically changing how my server serves dynamic content? Is it even possible or am I misunderstanding the whole philosophy behind Backbone.js?
Just to give you a little background: I am in the process of refactoring the JS code of a Django web application by integrating Backbone.js. The app itself is not very large, but it makes heavy use of Ajax calls.
I don't think you should be loading templates in a model. The loading and rendering of templates would usually be the job of the view. Try loading the HTML directly with AJAX in the render method of your view:
var ItemView = Backbone.View.extend({
render: function(){
var that = this;
$.get('/item/123', function(html){
that.$el.html(html);
});
return this;
}
});
If you havent already, have a look at the django-app Tastypie, its the go-to solution for backend to backbone and similar apps.
Without seing the code its hard to tell how much work it would be to move it all into Tastypie vs rolling your own solutions on a per-case basis, look over the documentation.
Basically, if you have a purely JS app (that get info from socket.io, or from a server with ajax request), and you need to show this data after processing it, what technique are you using?
Currently i'm creating the elements manually with code like
var myDiv = new Element('div',{ /* options */);
And injecting it where I need making all the DOM structure. I find this hard to maintain and especially for those designers that can code html, but they can't code html from JS.
Is there any way that will improve this process? Is it better to get the html from ajax? or just make html code in a string?
I'm looking for the most optimal in terms of maintenance and resources.
What you're looking for is a "template".
You have an HTML template (some divs, etc) and you bind this with the datas you provide in JS. Then, with whatever template engine you're using, you can get the full HTML.
Here are some template engines out there:
https://github.com/flatiron/plates
http://embeddedjs.com/
And a code sample using plates:
var Plates = require('plates'); // specific to node.js, see for client-side use
var html = '<div id="test">Old Value</div>';
var data = { "test": "New Value" };
var output = Plates.bind(html, data);
console.log( output ); // '<div id="test">New Value</div>'
You can store your templates either in a single file ("templates.html") loaded through ajax, or by storing it in the HTML page (not really recommended for maintenance matters).
If you store them all in an external file, you can do something like this:
templates.html:
<!-- text/html isn't parsed by the browser so we can put anything in it -->
<script type="text/html" id="template1">
<!-- put your template in there
</script>
And you can get its content through getElementById( 'template1' ).
Easiest way for you if project is in late stage to add something like jQuery.template plugin and create templates in separate files. Then, use backend to combine those peaces in single page and on DOM Ready fire up your client side app.
If your project is in early stage use AngularJs or BackboneJS frameworks. Believe me it is worth every cent :)
I would recommend you take a look at Backbone.js.
Backbone.js gives structure to web applications by providing models
with key-value binding and custom events, collections with a rich API
of enumerable functions, views with declarative event handling, and
connects it all to your existing API over a RESTful JSON interface
I use backbone even if I am not over a RESTful interface. It's pretty easy to separate the structure from the behavior ... You can achieve the same using jQuery but it wont be as neat and clean. It's one of the MV* framework. You have:
Models containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.
Collections are ordered sets of models.
Views: The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page
Routers provides methods for routing client-side pages, and connecting them to actions and events
It's getting attention recently. Apps that were created using Backbone include:
FourSquare
LinkedIn for Mobile
This is a great resource if you're starting to work with Backbone.
Distal Templates http://code.google.com/p/distal/ :
<table id="a">
<tr><th>OPINIONS</th></tr>
<tr data-qrepeat="m keywords"><td data-qtext="m.name"></td></tr>
</table>
Then call:
distal(document.getElementById("a"), {
keywords: [
{name:"Brilliant"}, {name:"Masterpiece"}, {name:"Witty"}
]
});
will become:
<table>
<tr><th>OPINIONS</th></tr>
<tr><td>Brilliant</td></tr>
<tr><td>Masterpiece</td></tr>
<tr><td>Witty</td></tr>
</table>
And injecting it where I need making all the DOM structure. I find this hard to maintain and especially for those designers that can code html, but they can't code html from JS.
Another option is modest. As you can see from the documentation, it obviates the need for HTML chunks in javascript. The designers can change the HTML structure without needing to look at the javascript, and javascript coders can use parameters defined by the designers to fill in the data (all in javascript).
This example is from the readme:
HTML:
<div>
<contact>
<name>Casey Jones</name>
<phone>123-456-7890</phone>
</contact>
</div>
Javascript:
var contact = {
name : "Casey Jones",
cell : "123-456-7890"
};
var out = modest.render('contact',contact);
I heard of mvc in javascript many times,however I have no idea about how the mvc work in js.
Since I have used the goolge map v3,and I found the MVCObject.
It seems that this is a helper class used for register and listener the property chang event of the object.
I thinks this should be the "Model", Howver I have not found the "MVCView" there.
I am really confused with that.
Anyone can give me more details?
In javascript the view is mostly some html template that is rendered by some view class in js. The model is a class that is bound to that view so that, when it renders, the data from that model is being loaded on the correct positions in the templates. Take a look at backbone.js for example.
Here's a brief overview at a high level on how the MVC Pattern works:
Controller:
Listens on some kind of interaction/event stream.
Controller can send the model that type of interaction/event.
Controller can also communicate with the the view.
Model:
Models will listen in on the interaction/event from the controller.
Is an abstraction of a data source.
Handles data logic and manipulation.
After it is done with logic, it then sends to controller which will then communicate with the view.
View:
View can communicate with the controller.
Knows how to render data from the Model to the browser visually.
The Controller tells to View to do something with something from the
Model.
A couple of things to note is that models can't communicate with views directly and vise versa. Only the controller can communicate with the view and model, so the controller acts as the delegator for the interaction/event retrieved from users interaction on the browser.