How would you implement this app in JavaScript using principles of MVC?
As you can see, the app basically has 3 views: "Sidebar", "Visualization" & "Timeslider". The underlying model must keep track of selected countries and year.
When initing the app, it should load a json file that populates the model with data. With some sort of event system (please advice), the controller should be notified of a stable model, and corresponding views should be set.
For example, adding a country in the sidebar should trigger data reload, followed by updating of x/y scales of the visualization view to accomodate for more countries etc.
How would you separate the logic from the views (what would go in the model, view & controller respectively) and what libraries would you use? (especially re. event handling).
Code is much appreciated ... Thanks.
For this kind of application I suggest you to look into backbone.js.
Which basically is:
Backbone supplies structure to
JavaScript-heavy 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 application over a
RESTful JSON interface.
You can take a look at Views on the backbone.js documentation; they have a huge amount of examples for you available, which will be more helpful than me providing a complete solution using backbone.js. They also have several demos with fully built apps ready fo you to base off.
Update: Also take a look into spine.js which is really similar to backbone but it's not the same, from their F.A.Q the difference is:
Whoah - your API looks really similar to Backbone. Why should I use this Instead?
Well, it's true that Spine
was inspired by Backbone, an excellent
library, and its controller API is
very similar. However, the
similarities end there. Internally the
library works very differently. For
example, Spine has no need for
Collections, which are required for
pretty much every model in Backbone.
Spine provides a class library, and
has very different ideas when it comes
to server sync. Lastly, Spine is much
simpler and half the size, go and
check out the source.
Related
I'm a semi-senior react and JavaScript developer, I've made several Universal react application.
Today our CTO told me: Do you use a software architectural pattern for your application?
I've no answer, He points to the Android team which use MVVM for their applications.
I'm searching greedy but not found a trend methodology or example for this situation. I've used Redux, Redux-Saga, React-Context and etc.
I don't know how to explain to our CTO or what is his answer?
Hence: Does a react app really need a software architectural pattern?
React itself is not particularly opinionated about software architecture. It is a library that facilitates the reusable component paradigm alongside guidelines for managing things like state and data sharing (props). At some point, Facebook described this as the V in MVC but have since moved away from that marketing to call it more abstractly A JavaScript library for building user interfaces.
Of course, the typical tooling associated with React apps does lend itself to something of an architecture when used together.
A couple of potential ways to think about it:
Simple React apps might be just "VVM" or "VC"
MVC is probably the better-known of the two in the development world. The key conceptual difference between a controller (C) and view-model (VM) could be boiled down into: a controller can have many diverse responsibilities, like listening for events and routing them in the right direction. It's the glue that facilitates the functionality of an entire application. A view-model, on the other hand, is simply responsible for gluing the current state of the data to the model.
So Facebook's original use of "V in MVC" could probably just as easily have been "V in MVVM" - the term controller makes more sense in backend development world.
A barebones React app, without Redux, that pulls data directly into components (e.g. fetch's in componentDidMount or leveraging GraphQL) with limited data wrangling of any kind could be called a simple "VVM" model.
View-Model (VM): Component-related code that manages simple state, passes data directly onto View, potentially passes data directly back from View
View (V): How the visuals look (JSX, CSS)
Add some complexity, and you could call it "MVVM"/"MVC"
If you toss in Redux, redux-saga, or even start doing crazy things with simple React component state, you're introducing model operations. There're at least two things this Model (M) can represent:
Actual business logic for your application
Storing and managing complex behavior in your client
Business logic is sometimes undesirable in practice: for example, if you have control over the server, it might be worth keeping all your business logic in one place (on the server) and just feed the UI what it needs to interact with the user. But if you have limited REST endpoints and need to do some wrangling (e.g. in your sagas, or within components), that'll be business logic.
Client behavior management is likely, especially in complex applications where you might be doing things like displaying different things to the user based on their session (e.g. they're an unregistered user vs. user vs. admin). You're probably doing this in any redux store interactions that are contained to use by only the client.
Disclaimer: discussing MVC, MVVM, etc. is likely to lead to many different opinions of exactly what they mean [1]. Above, I tried to draw parallels between common patterns I've seen and how they fit into MVC/MVVM, but there's so many different ways to approach it or more granular ways to think about it. I wouldn't get too hung up on putting a label on it as long as your system is easy to understand: modular, DRY, abstracted, etc. at levels that make sense for your use case and scale of development.
[1] Discussed in the some more length in answers and comments to this question
Vue 3 is MVVM:
Proxy Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
And React:
setState Update
Model → ViewModel → View
Model ← ViewModel ← View
Update Event
The difference is only how the frameworks notify Model changes to the ViewModel.
A simple Web App does not require MVC, MVVM, does not require even React IMO.
Possible evolution of a simple ReactJS App that may see the need of MVVM/MVC/ if it tries to be PWA (Progressive Web App). In other words - if it tries to do some (application/domain) specific logic - offline and some other - online. This is natural point of thinking for mobile app development. Then, the information may be retrieved from the Local Storage or the IndexedDB (for the Web) or the Back-End/Rest/. Then, the separation of Model, Storage/Repository/Source Of INfo/ ViewModel/ or Controller/ and View will be natural and actually needed for all stuff to work correctly...
I know this topic is likely to become subjective, therefore it is not about my particular web application I am working on.
For JavaScript, I haven't worked with MVC libraries like Backbone.js but I see the advantage in decoupling logic and views. On the other hand, it may just not be worth the time to learn the framework and adapt the application to make use of it. Moreover, handling all views in JavaScript makes SEO much harder, I guess.
So how should I decide whether it makes sense to use Backbone.js or a similar framework given the concept of a web application? On what depends the decision?
Any help to make the question more objective is welcome.
There are many client side javascript MVC (or MV*) frameworks out there. Most seem to have a different idea of what MVC is and how it should work together with your web application.
You should consider an MV* framework if the complexity in your client side javascript is becoming difficult to manage. If you have a team building a highly dynamic single page application (SPA) that does a lot of asynchronous communication with the backend then you will want to consider it. It's easy to end up with very messy javascript code otherwise.
An MV* framework will help you in one or more of the following ways:
by defining how the code should be structured. This is done to various degrees depending on how opinionated the framework is. Backbone for instance considers itself a library rather than a framework and thus leaves more of the decision making up to the user
by binding html to model. So if your data changes the page will be automatically updated (and vice versa)
by providing useful features such as URL history (for single page apps) and validation
I think it depends on your project. Here is a checklist which can help you in deciding whether you should use frontend MV* framework or not.
Lots of ajax request to backend
Many of your functionality doesn't require full page reload. Like adding a comment, pagination or infinite scroll.
You have models/REST API at backend. You can just replicate/use same structure at front end.
You are sharing logic/dom manipulation functions across different pages.
I will add more if I find any more points. This is what I can think right now and this is not a complete list. Any suggestions are welcome.
As You Know MVC structure can be included in javascript by using
backbone.js with
underscore.js and other similar libraries mainly focusing on each form field as property in an entity such that entities can be used different purposes MVC structure is maintained for easy manipulation in javascript
These structure good for event binding,dom manipulation ,serialization,etc
It depends on application's purpose for choosing which structure suitable whether its mvc or mvvm structure for javascript. MVVM structure can be included in the javascript through angular.js or knockoutjs or other libraries for dynamic binding to view component Javascript can be used
MVVM architecture will be usefull for maintaining form field binding without reloading or ajax There are a lot of application by maintaining the architecture in js and i have pointed out only a few .
for eg : Serialize form inputs to JSON using Backbone.js
In this example the form values are retrieved as model and then it can be manipulated and can add business logic and can be serialized or event binding and can do print or any thing
We need to change/rewrite an existing series of pages/workflow screens into one standard page. The project in itself will essentially be to build a single web page app inside the context of a larger existing application.
Our goal is to leave the server side implementation the way it is as much as possible. This means we won't be using a REST model, but rather just some form submissions to a java backend. Each end point will point to a JSP.
Each form will be created as a widget. When one widget submits it may affect the value of the other widgets which need to change their values on the fly.
It seems the 2 main options for single page web apps are Backbone.js or Ember.js.
Given our requirements, which of these 2 (or any other frameworks) will fit best? Or is there some other approach all together we should take?
Did you have a look at AngularJS? It is more comparable to EmberJS.
I would recommend you EmberJS for the moment, as it is more mature in term of ecosystem (Routing, Data, ...)
Backbone is lower-level than both precedents.
There are probably a bunch of things you should look into.
Emberjs is 42k minified+gzip while Backbone.js is just 5.6kb. Emberjs packs a lot of power in it which the barebones Backbone doesn't give you.
Analyse if you even need all those features. If your requirements are covered by just Backbone, IMO you should give Emberjs a pass. Shipping all those extra bits for no use is foolish.
With Emberjs, you will have to use jQuery as well. Not sure if you are already using it or not.
IMHO, I would use Emberjs if the single page web app is super complex with lots of feature requirements else Backbone should suffice.
Either will accomplish what you want.
I am partial to Ember as it provides a Routing/statechart framework which really helps lock an application's behavior down. Not to mention that it is MVC, which will help you separate your concerns. Each form or widget in your app will be a view that you define, binding inputs to your model layer.
I want to build a contact list in js, but there are so many js technologies like backbone.js, spine.js, knockout.js, etc. that I dont really know which one is best for me.
My contacts have a few overarching types: FacebookUser, User, and UserList. The catch with userlist is that it is a collection of users or UserLists. Furthermore, it itself may or may not have its own contact information (like a company or a team).
I want to display this list in a tree-view where you can drill down into UserList (and have the group members lazy loaded).
Lastly, the entire contact list is an instance. What I mean is that you have have 0-n number of contact lists open in the same window at a time.
What framework should I use for this situation?
All three of the libraries that you mention (backbone.js, spine.js, knockout.js) are aimed at single-page browser apps.
But your description of your problem sounds more like a formatting issue, not data management. Ie, you want your page to show the data. You don't need to save changes from your page back to the server; your users will refresh to the page to show new or different information.
If my understanding of your goal is correct, I'd go with jQuery or YUI. The libs you mention would be overkill.
Added YUI has a nice treeview widget that supports lazy-loading of branches. I use it for that.
If you do decide to use a model layer, YUI 3 includes Model and ModelList. They're based on Backbone api.
Re: MVC comment In a comment, the OP mentions "multiple views on the same data, change propagation, and edit detection (if a user changes a number) and updates from the server"
For those cases, yes, these days many cool kids are using a complete MVC framework on browser itself. If you wish to go in that direction, then you could use any of the three you mentioned. Notes:
Backbone, and probably the other two, do not provide complete MVC. Rather, Backbone supplies the Model & Controller portions, especially the Model. It is common to use Mustache for the View. In addition, it is common to use underscore or jQuery to supply basic facilities. If you Google for backbone examples, many of them include jQuery.
Checkout YUI new y.App. It includes all of the MVC parts in one well documented lib. y.App is in hot development and is based on the Backbone api. A video-cast
MVC Frameworks on the browser are brand new. Don't be surprised by quickly changing library code, inconsistent docs, few examples, etc. You should also consider documenting and posting your investigations. For extra credit, get it working well on mobile browsers.
49 Signals was rumored to be working on a browser-side MVC framework, but we haven't seen anything yet.
I believe that backbone is the most senior of the Model libraries. But it has proven to be confusing to many new users, hence some of the other libs based on its concepts.
Based on my experience with YUI, their Y.app will have the most consistent and complete api set and the best docs.
If we take your specific case, I would strongly go for Knockout.js
Knockout is built for UI i.e. that your data model can be binded to HTML elements and then any changes in the model manipulate the UI accordingly.
In your case the additions/deletions to the contact list will be automatically tackled by Knockout. All you need would be to define the how the changes in the tree view are to be tackled (either by code or by HTML templates) and Knockout will take care of that.
Saying that, defining the treeview of your contact list is still different task altogether and you may need to you use some CSS/JS library for that.
I know Model-View-Controller well, have known about it for years and used it in terms of server-side development with languages like PHP.
However, I am now working with JavaScript and building a big application with it utilizing SVG, Canvas among other great features modern browsers support. The project is big, so, the architecture behind it must not be fragile.
JavaScript and MVC do not get on like a house on fire, because JavaScript is event-driven by nature. So, are there any architectures or anything else I should definitely learn, understand and implement?
The software will have to deal with data. It already utilizes local storage and web SQL database. I need a Models, right? There is an UI, so I have Views? However, do I have Controllers? What about events? How do I structure everything?
Architecture, architecture, architecture -- that's what I'm interested in. I'm fine with the language of my choice.
First, I'm the author of JavaScriptMVC, so I'm extremely biased in a whole variety of ways. First, there are 6ish things you will ever do in a JS application:
Load Scripts
Respond to user events
Update the DOM
Request data from the server
Convert that data into something useful for JavaScript
Organize your front-end business logic
Your choice of architecture might depend on what tools you want / need.
For general architecture, I do think it's important to separate concerns.
I strongly encourage you to find some way of doing dependency management, and client side templates. They will make your life a lot easier.
JavaScriptMVC uses a tiered MVC approach that's based heavily around custom UI events and OpenAjax events.
I build my low-level widgets with $.Controller in a similar way to how you would build jQuery widgets. The big difference is that the widgets produce a non-ui event that top level controllers can listen to. For example, a tabs widget might produce a "tab.activate" event like:
$('.tab').trigger('tab.activated')
Then, my higher order controller might listen to tab.activated events, and a the model to update the tab content like:
".flickr tab.activated" : function(tabEl, ev){
Flickr.findAll({type : "rainbows"}, function(images){
tabEl.html("//path/to/view", images );
}
}
Flickr.findAll essentially does a query for flickr messages, then calls back with a list of images. Wrapping the service/ajax functionality with models makes them a lot more reusable.
You'll notice that in the callback I update the html of the tab element with the rendered content from a view. This probably isn't the 'best' way of doing it, but I wanted a quick example. Better would be passing the tabs controller the rendered output, for it to do what it will with it. That way if your tab wants to fade in content someday, it will be able to and your master controller won't have to know about the tab's implementation.
The most important thing is to break down your app into the smallest pieces you can. Have them individually testable (and flexible), and combine the little parts into bigger parts as you work your way up to your application.
Take a look at Ext JS. It has a clean architecture that is well-suited towards highly complex javascript applications.
Data handling and server communication is done via stores. Data rendering is done via grids (with in-cell editors), and forms (with a rich set of form controls), which can both talk to the stores. There's also a set of layout classes to abstract away CSS positioning (border layout, box layout, table layout, form layout, ...).
It is however not MVC in the typical sense. The library encourages a programming style that avoids dealing much with HTML and CSS, letting you live (mostly) in pure JavaScript land. You end up thinking in terms of components and data, instead of individual dom elements and style rules. If you don't like that approach, be warned, you won't like this library.
MVC is still the way to go, in my opinion. If you're looking for a good framework to help you achieve that a little less painfully, I would look at JavaScript MVC, it has models, views, controllers, unit testing, jQuery support, etc.
You should learn the Event Based nature of client-side JavaScript and how it blends with MVC based server-side applications.
You should also learn how to properly program inside of the Prototype based inheritance structure of Javascript.
Both of those things will allow you to write you JavaScript so that it meshes with your server-side application framework and is extensible and re-usable.
One thing i have learned over the years of javascript programming is writing UnObtrusive Javascripting which basically means seperating as much as possible structure(HTML) and style(CSS) from Behaviour(JAVASCRIPT).
Althogh not a raw javascript solution, take a look at CoreMVC, the jQuery architechure of MVC.
CorMVC is a jQuery-powered
Model-View-Controller (MVC) framework
that can aide in the development of
single-page, web-based applications.
CorMVC stands for client-only-required
model-view-controller and is designed
to be lowest possible entry point to
learning about single-page application
architecture. It does not presuppose
any server-side technologies, or a web
server of any kind, and requires no
more than a web browser to get up and
running.
If you want a ready-made reference architecture that combines soem industry leading JS libraries with some good JS design patterns for large scale development, have a look at:
http://boilerplatejs.org/
I'm the main author of it and thought of sharing knowledge we gained after developing few large scale javascript products. It addresses following main concerns:
Solution structuring
Creating complex module hierarchy
Self contained UI components
Event based inter module communication
Routing, History, Bookmarking
Unit Testing
Localization
Document Generation