I'm referring to this article here
http://codebrief.com/2012/01/the-top-10-javascript-mvc-frameworks-reviewed/
In my current application I have two views. The first is the overall view which renders a table. The second view renders an individual row and is used by the main view. My row view could be separated into a separate file and used in any other component. In what way is this not composable? Perhaps I'm misunderstanding the terminology used in the article.
The author of that article is specifically referring to composable view templates, like Handlebars, in combination with the backbone view object.
He is essentially wanting to take a view-first approach to composition, where a template would define which views are composed in to the final view. This composition would also determine which objects are used to run the view.
For example, in EmberJS, you can configure a view template to be associated with a specific controller. Doing this, you can compose views in the template itself and the correct controller will be used. This is not possible with Backbone, even when using Handlebars - at least, not without some heavy customization. Backbone takes a "presenter-first" approach (to use the old Model-View-Presenter language) or a View-object first approach, where the view object itself controls which template is rendered.
Related
I am new to Angular, watched a number of videos and read docs, but not sure for i have it all compiled in my mind. I've seen a bunch of small simple pieces of code but never saw something complex. Do you know of docs/tutorials/examples to help me implement the following?
I want to make a SPA forum web application. The forum consists of numerous topic groups, each of which has topics inside, and each topic has multiple comments.
So this is a hierarchy of nested entities like this: Forum -> Topic Group -> Topic -> Comment.
In my SPA I'll need to CRUD any of them or load from server either a single entity (say Comment) or a complex view (a topic with all comments) depending on what user/admin wants.
I can't find an example dealing with the complex hierarchies. Should their controllers and models be nested or separated? How should I separate their CRUD methods? Do I put them all into the top level of $scope? How do I separate parent/child entities of the same $scope that are used in different controllers? What is the better way to substitute View and Edit templates for data being edited by user? Etc...
Or better, is there a sample for the task like mine?
Thanks
I avoid nesting controllers (making controllers depends on scope of their parent controllers), and instead make custom services through which controllers communicate.
Routing of controllers was the biggest issue for me. I've initially started by using ngInclude and handling routing manually, because AngularJS doesn't allow multiple ngViews. Solution was Angular UI Router. They have a simple example that can give you an idea on how to structure your navigation.
Basic principle is:
Any view can have sub view (and it's controller therefore contains sub-controller)
Controllers in hierarchy don't communicate directly through their $scopes. Rather they should use services or events ($scope.$emit, $scope.$on)
Any level of depth can be routed to (e.g. http://myforum.com/#/help-category/how-do-i/msg1)
Take my view with a grain of salt because I'm fairly new to Angular.
Since you're interested in scope inheritance here's an example, but this is discouraged for communication between controllers.
When a controller has a parent controller, then it's scope has a parent scope:
Parent controller:
$scope.Breakfast = 'eggs';
alert($scope.Breakfast); // Shows eggs
Child controller:
alert($scope.Breakfast); // Shows eggs, inherited value
$scope.Breakfast = 'muesli';
alert($scope.Breakfast); // Shows muesli, new value
Parent controller:
alert($scope.Breakfast); // Shows eggs, value remained same
$scope.Breakfast = 'burek'; // Child doesn't see this change anymore
You can get better description and illustrations in Angulars developer guide.
One quick note: don't forget that angular is all about your custom directives, so ideally your html for topic template should look like this:
<div ng-controller="TopicCtrl">
<comment ng-repeat="comment in topic.comments"></comment>
</div>
Angular really allows to write code unbeliavably DRY, so don't be afraid of directives, they will help you with achitecturing your application structure very much.
i want create one div ( basically it will containt listbox) , and i want to use the div in different pages,
which is the best option to use in duarandal.js?
Composition
http://durandaljs.com/documentation/Using-Composition/
Widget
http://durandaljs.com/documentation/Creating-A-Widget/
In general, think of using the compose binding as templates, and widgets as user controls
There's not quite enough information in your question for me to offer a suggestion on which is the right choice for you, but I'll provide some comparison for the two below, which should make it easier for you to choose.
Durandal's compose binding can be used to render, or inject, one view as part of another. For example, a menu.html may be defined that can be used to display menu items. This is similar to the concept of a jQuery template, or a "partial view" in ASP.Net MVC. A composed view can either use the parent's view model as its data source, or it can have its own view model.
The compose binding is most useful when you have a view and/or view model that can be used as is in multiple places.
Durandal's widgets, on the other hand, use composition internally, but are designed to abstract the "parts" of the widget so that one widget can be configured differently on each view where it is rendered. A widget can have parts, and these parts can be exposed through the widget interface.
Durandal widgets are most useful when you want to create some functionality that can be used across multiple views, but the implementations may differ.
I have an application built on Backbone. Since it is getting more complex I am evaluating a migration to Marionette but I am not sure on how to structure my views.
The existing application views are structured in this way:
BaseView = Backbone.View.extend({ ... })
The BaseView is the root of all views. It basically has a render function with basic stuff like: template rendering, page localization, active menu selection, etc
ListView = BaseView.extend({ ... })
Here the render method contains common code for all lists like loading and use of DataTables plugin, common events for edititem, additem, deleteitem, etc
FormView = BaseView.extend({ ... })
It manages generic forms using the Backbone.ModelBinder plugin and handles the form validation.
All my application views extend from one of the above to improve code reusability. For example I have an AccountFormView that extends from FormView where I have just the specific logic (a few lines of code) to handle account information. All the common logic is inherited from the parents views.
How can I obtain something similar using Marionette Views?
Thanks,
Fabrizio
Marionette's views are set up to handle the most common situations, and remove all the boilerplate code from solving these common problems:
View: a base view that can be used to build other views
ItemView: render a single model with a template
CollectionView: render every model in a collection, using the specified itemView
CompositeView: render a template as a wrapper around a collection view. supported nested / hierarchy structures
In your situation, it sounds like you'll be using a combination of these view types, depending on the specific scenario you're in. Instead of having a single view type to always extend from, though, you'll pick the one that makes the most sense for the current scenario and extend from that.
If you're looking for a way to add your own custom functionality to all views, that's also very easy - just add that feature tothe base Marionette.View or Backbone.View and it will be available to all Marionette views.
Be sure to check the documentation and code (it's split up in to many small files, so it's easy to read and understand) to see what methods Marionete provides for you, and what extension points it provides as well.
Hope that helps.
I'm trying to implement a MVVM based Single Page Application and currently am using the framework Knockout.js to handle the viewmodel/view portion of MVVM. I'm confused though, as every example I've looked at for implementing Knockout involves saving an entire viewmodel to the database. Aren't these examples missing a "model" step, where the viewmodel syncs with the data-layer model and the model does validation / Server synchronization.
I would like to have multiple different templates/views on the single page each with a different viewmodel. Another thing that I find is missing with knockout.js is synchronizing a single model (not viewmodel) across different views. I don't think it makes sense to have one giant viewmodel that every view shares, so I was thinking that each view would have its own viewmodel but each viewmodel would sync with the fields of just a few application-wide models that are needed for each view.
The page I'm working on fetches a giant model (30+ fields, multiple layers of parent/child relationships) and I think it makes sense to just have all of my viewmodels sync with this model. I have investigated Knockback.js (which combines knockout.js and backbone.js) however I ended up re-writing the majority of the functions such as fetch, set, save, because the page is getting data from an API (and I can't just sync an entire model back and forth with the server) so I decided against it.
visual example of my application:
(model layer)
M | M
(viewmodel/view layer) VM-V | VM-V | VM-V | VM-V
another example
An example model would be User = {firstName: "first", lastName: "last", ... }
one viewmodel only needs first name, another viewmodel only needs last name
ViewModelA={firstName: app.User.firstName()}ViewModelB={firstName: app.User.lastName()}
Is the only way to do this to define a pub/sub system for Model and Viewmodel changes? Is this even good/maintainable architecture? Am I missing a basic concept here? All advice welcome.
If I read this correctly, there's a lot of questions in here all focused on how to build a MVVM / SPA with Knockout. There are a few things to tackle, as you pointed out. One is how to communicate between viewmodel/view pairs.
Master ViewModel
One way to do that is to have a master viewmodel as the answer from #Tyrsius. Your shell could have a viewmodel that binds more available data. The master viewmodel could orchestrate the child view models, too. If you go this route then you have to be careful to bind the outer shell to the master viewmodel and the inner ones to specific HTML elements in the DOM. The master viewmodel could facilitate the communication between them if need be.
Decoupled View/ViewModel Pairs
Another option is to use viewmodel/view pairs and no master viewmodel. Each view is loaded into a region of the DOM and bound on its own. They act as separate units and are decoupled from one another. You could use pub/sub to then talk between the, but if all you need is a way for the data to be synched through observables, Knockout provides many options. The one I like is to have each viewmodel surface model objects. So a view has a viewmodel which surfaces data (from a model) that is specific for the view. So many viewmodels may surface the same model in different ways. So when a view updates a viewmodel property (that is in a model) it then ripples to any other loaded viewmodel that also uses the same model.
DataContext
Going a bit further, you could create a datacontext module that manages the data in the models. You ask the datacontext for a model (ex: list of customers) and the datacontext checks if it has them cahced already and if not, it goes and gets them from an ajax call. Either way that is abstracted from the view model and models. The datacontext gets the data and returns a model(s) to the viewmodel. This way you are very decoupled, yet you can share the data (your models) via the datacontext.
I could go on and on ... but please tell me if this is answering your question. If not, happy to answer any other specifics.
** Disclaimer: I'm building a Pluralsight course on SPA's (using Knockout and this strategy) :-)
This is a popular field of interest right now, so I expect you will get some better answers, but here goes.
The Model
Yes, you should absolutely have a server-side representation of the data, which is your model. What this is depends on your server, and your database. For MVC3, this is your entity model. For Django or Ruby, your will have defined db models as part of your db setup. This part is up to your specific technology. But agian, yes you should have a model, and the server should absolutely perform data-validation.
The Application (ViewModel)
It is recommended that your views each have their own viewmodel. Your page could then also have a viewmodel, an App Viewmodel if you will, that keeps track of all of them. If you go this route, the app viewmodel should be responsible for switching between the views, and implementing any other application level logic (like hash bashed navigation, another popular single page tool). This hierarchy is very important, but not always simple. It will come down to the specific requirements of your application. You are not limited to one, flat viewmodel. This is not the only possible method.
Ad Hoc Example:
​var ThingViewModel = function(name, data){
this.name = ko.observable(name);
//Additional viewmodel stuffs
};
var AppViewModel = function(initialData){
//Process initial data
this.thing = new ThingViewModel(someName, someData);
};
I am working on a similar project right now, purely for study (not a real world app), that is hosted here on GitHub, if you would like to take a look at some real exmaples. Note, the dev branch is quite a bit ahead of the master branch at the moment. I'm sure it contains some bad patterns (feel free to point them out, I am learning too), but you might be able to learn a few things from it anyway.
I have a similarly complex solution in which I am reworking a WPF application into a web version. The WPF version dealt with complex domain objects which it bound to views by way of presenter models.
In the web version I have implemented simplified and somewhat flattened server-side view models which are translated back and forth from / to domain objects using Automapper. Then those server-side view models are sent back and forth to the client as JSON and mapped into / onto corresponding Knockout view models (instantiable functions which each take responsibility for creating their children with sub-mapping options) using the mapping plugin.
When I need to save / validate my UI, I map all or part of my Knockout view model back to a plain Javascript object, post it as JSON, the MVC framework binds it back to server-side view models, these get Automapped back to domain objects, validated and possibly updated by our domain layer, and then a revised full or partial graph is returned and remapped.
At present I have only one main page where the Knockout action takes place but I anticipate that like you, I will end up with multiple contexts which need to deal with the same model (my domain objects) pulled as differing view models depending on what I'm doing with them.
I have structured the server side view model directories etc in anticipation of this, as well as the structure of my Knockout view models. So far this approach is working nicely. Hope this helps.
During a project i developed a framework (which uses KnockoutJS) which provides decoupled View/ViewModel pairs and allows to instantiate subviews in a view. The whole handling of the view and subview instantiation is provided by the framework. It works like MVVM with XAML in WPF.
Have a look at http://visto.codeplex.com
I am using Backbone.js for an applciation involving a lot of different views, some nesting other views, and these other views could further nest other views.
Also view presentation depends on certain attributes in the model, for instance, some content is only shown if the user has been authenticated, or another type of an if-check
Coming from the world of Adobe Flex, I am used to declaring my views almost completely using markup, even deeply nested, or composite ones. Flex makes component declaration in markup a piece of cake.
I was kinda hoping that I could achieve the same kind of separation between the pure view presentation and the view logic in Backbone, but so far I've been struggling with that.
The reason for this is that in no way can I manage to declare a composite view using templates only. Thus, I have to resort to using BB's render() method to instantiate subviews and append them to the parent. This is OK ... but if the views get really granular, declaring them using JS is an overkill, because I literally end up appending pure HTML strings, which is a complete mess. This means that it is much better to use templating for those ones, and then just render the template instead of doing all the stuff using JS.
Using both approaches simply breaks any consistency in the application, but I push myself to be OK with it, because I've read a lot of (even professionally written) Backbone code, and I 've seen other people struggling with the same thing.
If I cannot avoid this separation of rendering approaches, then at least I will have to put any certain boundaries of which views should be rendered with a template, and which not, or just partially. The question is what will those criteria be.
My methodology is to have all markup contained in templates.
My conception of Backbone Views is that they are actually Controllers. If you consider a Controller in a more traditional web app framework, their job is to receive events, marshal models, fetch and render templates, passing in models, and to return the resulting output.
In Backbone, the Views are the elements responsible for this task. But, instead of http being in input/output medium, the DOM is the input/output medium.
So, I consider Views to be controllers for a specific area of UI on the screen. They listen for events, marshal models, fetch and render templates, and modify the DOM as a result.
The decision of when to go to the trouble of generating a sub-view vs. perhaps rendering a template in a loop, is fairly loose for me.
If it has the possibility of being used in multiple views, I'll make a View out of it.
If it has any events or user interactions which affect itself, but not really anything in the "parent" object I'll make a view out of it.
If it has any real logic, I'll make a view out of it.
If its a related model, or collection, I'll make a view out of it.
But, in any of these cases, the view does not directly generate HTML - I'll always store the markup in a template.