Real world webapp structure with Spine.js - javascript

I've been diving into JavaScript MVC for quite a while using Spine.js and CoffeeScript. I develop Ruby on Rails since a while so I understand what the models, the views and the controller should handle respectively (based on my moderate experience with it). But in Rails we already know that (generally speaking) each controller is basically something that controls a bunch of views (or pages) and deals with one or more Models at a time. (Maybe, so correct me if I'm wrong as I'm not a pro yet I have to confess).
However I found a whole different concept with Spine in terms of architecture. I read its documentation and dove into its sample apps. Unfortunately all the Spine sample apps are showing how to deal with a single page app, something that in a real world "larger" application would not be the case anymore. (Correct me if Spine should only be used for "single page apps").
Assume there is a website (or app) that consists of many pages/sections/modules as follows:
1 - A home page, displaying for example, a thumbnails based list
2 - A contact page
3 - A profile management page for the current user (normal CRUD)
Each page has the same main structure (or layout) as in a header with links to the above pages, a search input field and a log out link (I already know the log in page should be separate, so I won't ask about authentication in here).
The tricky part here is I can't really figure out how to tie the whole parts together and I've been asking myself some questions, searched on Google and StackOverflow but without clear answers.
1 - "Must" a spine app application be in one page only? I mean, having header and footer fixed but with a dynamic content DIV which loads and unloads views based on which tab the user clicks on the header? Or should I treat each page as a standalone spine app?
2 - Do I have multiple controllers in one page? For example, the app main controller and navigation controller (header)?
3 - Is it true that each controller should be dealing with one Model, or the one associated with it? (In the samples there was always a 1 to 1 relationship between them, like Task Model and Tasks Controller).
4 - Where should I store interface related state variables in my app. Should I create a model that "remembers" the current user, or for example which tab is highlighted for further reference? Or should I store them into the controller(s)?
5 - If it's going to be a single page app (but with many sections or modules), should I have a controller for each loaded section inside of this page?
I know these might be trivial questions for more experienced programmers but I really don't know where to start. So it would be awesome if someone could guides me to the right track.
Thanks in advance!
DD

I think that this is a very good question. My answer will be quite broad, so bear with me.
The essence of my answer is that you need to get familiar with other frameworks in order to understand what the one you chose is trying to solve. Your problems are understandable. Other people have struggled with lack of one "proper" way of doing some common things. Solutions were created in terms of examples, wrappers/extensions and alternative frameworks. Perhaps, you should seeks information related to Backbone, which inspired Spine and is still similar to it.
As you said, you're familiar with Rails' MVC. And then comes Spine's MVC approach and it is totally different. This should give you a hint that MVC (or MV* in general) is broad idea that has very different implementations. OK, you might be thinking that Rails is a request-based server-side framework after all and that Spine is a client-side event-based framework - so the difference is understandable. Well, there is no uniformity amongst client-side JavaScript frameworks either. For example, the mentioned Backbone has so-called Views, which actually play the role of controllers. So I guess that one thing that Spine's creator did was renaming Views to Controllers for clarity. MV* for JavaScript is explained in detail by Addy Osmani. There is also a good overview of JavaScript frameworks.
So one "problem" with Spine and Backbone is that they do not dictate any architecture. In other words, they are not opinionated enough. You can use them as your want and this fact makes frustration. Below I try to answers your questions:
With Spine, application is not required to be a single-page application (SPA).
You may create an app that has multiple pages, each loading it's own Controller. In this case, your views can be rendered on server and your models can be bootstraped from generated JavaScript. This is good when you don't want a SPA, but still would like to organize JavaScript or have some reusable components.
However, judging from the feature set of Spine (e.g. routes), it was created with SPA in mind.
For SPAs and complex UIs in general it is good to have parts of UI (widgets) separated. In Spine, Controllers are the means of such separation. So yes, use multiple controllers and use controller nesting. Perhaps, there should be a topmost application controller.
That's not true (no technical limitation), although single responsibility principle makes things easier.
Store those variables in the controller of corresponding level. Store them is models if you need to observe those values, otherwise store them as controller properties.
You can have an App controller, that holds a header, footer, sidebar controller and an active page. In Routes, you create a corresponding controller and pass it to App controller, which replaces the main area content with the element of that controller. This is one possible approach.
Once again:
People have struggled with lack of concreteness in terms of application architecture in Backbone/Spine. They have created some solutions like application controllers, layout managers and so on. For Backbone, you can take a look at Marionette, Chaplin or Thorax. By learning from them you will be able to come up with an architecture for your Spine application. Good luck!

Related

Using AngularJS for Multiple Page Application [duplicate]

We are looking at options to build the front end of an application we are creating and are trying to evaluate a tool that will work for us and give us the best platform to move forward.
This is a Node.js project. Our initial plan was to use Express and go down that route, but we decided that before we kick off this stage it might be best to review what is out there. Our application has several areas which we don't believe fit the single-page model in that they are related from an application perspective, but not from a view one.
We have seen a few of the frameworks we could use to build out the client like Backbone.js, Meteor, etc. and also AngularJS.
This may be a fairly obvious question, but we cannot seem to decipher if AngularJS is purely for single-page application or it can be used for multi-page applications like Express for instance.
UPDATE 17 July 2013
Just to keep people in the loop, I will be updating this question as we go through the process. We are going to build everything together for now, and we will see how well that performs. We have reached out to a few people who are more qualified with AngularJS than us and posed the question regarding splitting up larger applications that share context, but may be too large working on a single page.
The consensus was that we could serve multiple static pages and create AngularJS applications that work with only those pages, effectively creating a collection of SPA and linking those applications together using standard linking. Now our use case is very specific as our solution has several applications, and as I said we are going to try the single code base first and optimise from there.
UPDATE 18 June 2016 The project fell of a cliff, so we never got round to getting too much done. We have picked it up again recently, but are no longer using angular and are using React instead. We are still using the architecture outlined in the previous update, where we use express and self contain apps, so for example, we have a /chat route in express that serves up our React chat app, we have another route /projects that serves up the projects app and so on. The way we are kinda looking at it is each app is an aggregate root in terms of its feature set, it needs to be able to standalone for it to be considered an app in itself. Technically, all the information is out there, its just basic express and whatever flavour of client side app building goodness you want to use.
Not at all. You can use Angular to build a variety of apps. Client-side routing is just a small piece of that.
You have a large list of features that will benefit you outside of client-side routing:
two-way binding
templating
currency formatting
pluralization
reusable controls
RESTful api handling
AJAX handling
modularization
dependency injection
It's crazy to think that all of that "could only be used in a single page app". Of course not.. that's like saying "Jquery is only for projects with animations".
If it fits your project, use it.
I struggled with the "how" at first with Angular as well. Then one day it dawned on me: "It is STILL javascript". There are a bunch of examples on the ins-and-outs of Angular (one of my favorites along with the book https://github.com/angular-app/angular-app). The biggest thing to remember is to load in the js files just like you would in any other project. All you have to do is make sure the different pages reference the correct Angular object (controller, view, etc.) and you are off and running. I hope this makes sense, but the answer was so simple I overlooked it.
Maybe my experience will be useful to someone. We split our project logically. One SPA we use for feed, another one to work with the map, another one for editing a user profile and etc. For example we have three apps: feed, user and map. I use it in the separated urls, like this:
https://host/feed/#/top/
https://host/user/#/edit/1/
https://host/map/favorites/#/add/
Each of these applications has it's own local routing mappings between states in the application.
I think it is a good practice because each application work only with its own context and load dependencies that it really need. Also, it's practice very good for debug and integration processes.
Indeed, you can very easily make a mix of SPA apps, for example the feed will be url with the angularjs application, the user app with the reactjs and map to the backbone.js application.
In response to your question:
Angular not just for SPAs, Angular play good and fast for SPA applications, but no one bothers to build MPA application of a variety of SPA applications. But thinking about your url architecture don`t forget about SEO availability of your applications.
I also support the idea:
What’s the difference between a project and an app? An app is a Web
application that does something – e.g., a Weblog system, a database of
public records or a simple poll app. A project is a collection of
configuration and apps for a particular website. A project can contain
multiple apps. An app can be in multiple projects.
If all you need is a few pages with client databinding, I'd go with Knockout and Javascript Namespacing.
Knockout is great, especially if you need uncomplicated backward compatibility and have fairly straight forward pages. If you're using 3rd party components, Knockout's custom bindings are straightforward and easy to work with.
Javascript namespacing allows you to keep your code separate and manageable.
var myCo = myCo || {};
myCo.page = {
init: function(){ ... },
...
}
And in a script tag after your other scripts are loaded
<script>
myCo.init();
</script>
The key is, you use whatever tool you want for when you need it. Need databinding? Knockout (or whatever you like). Need routing? sammy.js (or whatever you like).
Client code can be as simple or complicated as you want it. I tried integrating Angular into a very complicated site with an existing proprietary framework, and it was a nightmare. Angular is great if you're starting fresh, but it has a learning curve and locks you into a very tight workflow. If you don't follow it, your code can get really tangled really fast.
I'd say Angular is overkill if you're just looking to develop a SPA. Sure, if you're already comfortable developing with it, go ahead. But if you're new to the framework and only need to develop a SPA, I'd go with something more simple with a number of its own perks. I recommend looking into Vue.js or Aurelia.io.
Vue.js uses two-way data binding, MVVM, reusable components, simple and quick to pickup, less code to write, etc. It combines some of the best features of Angular and React.
Aurelia.io, in all honesty, I don't know much about. But I've peeked around and it seems an alternative worth looking into, similar to the above.
Links:
https://vuejs.org/
http://aurelia.io/

best practice controller / services

I have built an Angular app that consumes data from different sources (SharePoint lists). I setup a controller for each source.
What is the best practice for this? Use only one controller for the app and different services? Or one service and one controller? Or multiple services and controllers?
In the app I do not use routing.
First I'd recommend reading these articles. Also, go through their angular implementation and see how they've achieved some of their effects. It will throw you in a world of problems that you'll feel like "Why? I mean, why? why did I ever got into this mess?" But, grit your teeth and get through it. Then you'll see how much you can achieve. Learning Angular JS is a never-ending cycle of this.
angularjs-best-practices-directory-structure
Angular Style Guide
Advanced Design Patterns and Best Practices
The Top 10 Mistakes AngularJS Developers Make
Ok, and to answer your question: your way isn't wrong.
But controllers are not designed to be used like that. Controllers are a unit of code which co-ordinates your data into the UI, handle UI events, etc. generally of a certain view - i.e. a portion of your UI (navigation bar, home page, edit form, etc.). Of course this can be your entire page as well. But it's best to break it down so that it's easier to manage.
Use services for what you described. Create a service for each data source or type of data (users, equipment, roles, etc.). I recommend that latter, since sometimes you need to pull data from multiple ends and tie them together. This can be done inside your controller as well, but having services will enable you to re-use that functionality in another part of your application.
To summarize a long answer, I'd say go through these articles, code and tips. Then build a structure that will help build your application. Just don't over-engineer it.
I would say: use a controller for every "piece" of HTML in your app, (and it depends on the scale of your app how big that piece is, it could be just one controller if your app is really small). And use a service for each data source. Then you can use the services your need in your controllers. You could also use one service if you don't need a lot of behavior. It all depends on how big your application will be.

Is AngularJS just for single-page applications (SPAs)?

We are looking at options to build the front end of an application we are creating and are trying to evaluate a tool that will work for us and give us the best platform to move forward.
This is a Node.js project. Our initial plan was to use Express and go down that route, but we decided that before we kick off this stage it might be best to review what is out there. Our application has several areas which we don't believe fit the single-page model in that they are related from an application perspective, but not from a view one.
We have seen a few of the frameworks we could use to build out the client like Backbone.js, Meteor, etc. and also AngularJS.
This may be a fairly obvious question, but we cannot seem to decipher if AngularJS is purely for single-page application or it can be used for multi-page applications like Express for instance.
UPDATE 17 July 2013
Just to keep people in the loop, I will be updating this question as we go through the process. We are going to build everything together for now, and we will see how well that performs. We have reached out to a few people who are more qualified with AngularJS than us and posed the question regarding splitting up larger applications that share context, but may be too large working on a single page.
The consensus was that we could serve multiple static pages and create AngularJS applications that work with only those pages, effectively creating a collection of SPA and linking those applications together using standard linking. Now our use case is very specific as our solution has several applications, and as I said we are going to try the single code base first and optimise from there.
UPDATE 18 June 2016 The project fell of a cliff, so we never got round to getting too much done. We have picked it up again recently, but are no longer using angular and are using React instead. We are still using the architecture outlined in the previous update, where we use express and self contain apps, so for example, we have a /chat route in express that serves up our React chat app, we have another route /projects that serves up the projects app and so on. The way we are kinda looking at it is each app is an aggregate root in terms of its feature set, it needs to be able to standalone for it to be considered an app in itself. Technically, all the information is out there, its just basic express and whatever flavour of client side app building goodness you want to use.
Not at all. You can use Angular to build a variety of apps. Client-side routing is just a small piece of that.
You have a large list of features that will benefit you outside of client-side routing:
two-way binding
templating
currency formatting
pluralization
reusable controls
RESTful api handling
AJAX handling
modularization
dependency injection
It's crazy to think that all of that "could only be used in a single page app". Of course not.. that's like saying "Jquery is only for projects with animations".
If it fits your project, use it.
I struggled with the "how" at first with Angular as well. Then one day it dawned on me: "It is STILL javascript". There are a bunch of examples on the ins-and-outs of Angular (one of my favorites along with the book https://github.com/angular-app/angular-app). The biggest thing to remember is to load in the js files just like you would in any other project. All you have to do is make sure the different pages reference the correct Angular object (controller, view, etc.) and you are off and running. I hope this makes sense, but the answer was so simple I overlooked it.
Maybe my experience will be useful to someone. We split our project logically. One SPA we use for feed, another one to work with the map, another one for editing a user profile and etc. For example we have three apps: feed, user and map. I use it in the separated urls, like this:
https://host/feed/#/top/
https://host/user/#/edit/1/
https://host/map/favorites/#/add/
Each of these applications has it's own local routing mappings between states in the application.
I think it is a good practice because each application work only with its own context and load dependencies that it really need. Also, it's practice very good for debug and integration processes.
Indeed, you can very easily make a mix of SPA apps, for example the feed will be url with the angularjs application, the user app with the reactjs and map to the backbone.js application.
In response to your question:
Angular not just for SPAs, Angular play good and fast for SPA applications, but no one bothers to build MPA application of a variety of SPA applications. But thinking about your url architecture don`t forget about SEO availability of your applications.
I also support the idea:
What’s the difference between a project and an app? An app is a Web
application that does something – e.g., a Weblog system, a database of
public records or a simple poll app. A project is a collection of
configuration and apps for a particular website. A project can contain
multiple apps. An app can be in multiple projects.
If all you need is a few pages with client databinding, I'd go with Knockout and Javascript Namespacing.
Knockout is great, especially if you need uncomplicated backward compatibility and have fairly straight forward pages. If you're using 3rd party components, Knockout's custom bindings are straightforward and easy to work with.
Javascript namespacing allows you to keep your code separate and manageable.
var myCo = myCo || {};
myCo.page = {
init: function(){ ... },
...
}
And in a script tag after your other scripts are loaded
<script>
myCo.init();
</script>
The key is, you use whatever tool you want for when you need it. Need databinding? Knockout (or whatever you like). Need routing? sammy.js (or whatever you like).
Client code can be as simple or complicated as you want it. I tried integrating Angular into a very complicated site with an existing proprietary framework, and it was a nightmare. Angular is great if you're starting fresh, but it has a learning curve and locks you into a very tight workflow. If you don't follow it, your code can get really tangled really fast.
I'd say Angular is overkill if you're just looking to develop a SPA. Sure, if you're already comfortable developing with it, go ahead. But if you're new to the framework and only need to develop a SPA, I'd go with something more simple with a number of its own perks. I recommend looking into Vue.js or Aurelia.io.
Vue.js uses two-way data binding, MVVM, reusable components, simple and quick to pickup, less code to write, etc. It combines some of the best features of Angular and React.
Aurelia.io, in all honesty, I don't know much about. But I've peeked around and it seems an alternative worth looking into, similar to the above.
Links:
https://vuejs.org/
http://aurelia.io/

javascript frameworks: What are UI bindings and composed views?

I'm reading this:
http://codebrief.com/2012/01/the-top-10-javascript-mvc-frameworks-reviewed/
I'm using backbone.js. I love it, though it requires too much boilerplate. Anyway.
The author of the post seems to put great importance on UI-bindings and composed view.
I think I know the basic advantage of ui bindings, you can change small parts of the view as the model changes without re-rendering the entire view. I don't necessarily see the point though. If your view is huge maybe you should make smaller views? I've seen knockoutjs's code and it's littered with ugly data-bind stuff. How does emberjs handle it? Is there an example?
I have no idea what he means by composed views, could someone elucidate?
Composed Views - Like all software developers, I enjoy creating modular reusable code. For this reason, when programming UI, I would
like to be able to compose views (preferably at the template layer).
This should also entail the potential for a rich view component
hierarchy. An example of this would be a reusable pagination widget.
Is there an example?
Thanks
Edit:
Would this help make something like composed Views?
https://github.com/tbranyen/backbone.layoutmanager
Composed views are used to divide the view into small blocks which can be reused or adapted to different scenarios.
For example, in a form where you are editing a user, you could create a view for the address field and just call it from the main page/template. The author mentions pagination as an example too, in this case you could create a model that knows how to handle retrieving data as you switch between pages and just apply it to a table in your page.
Regarding the "ugly" data-binding code, backbone needs to know how to attach itself to the existing markup and how to modify it when an event occurs.
Maybe this example will help:
http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/
Traditional web pages are monolithic. User calls a page and server constructs the page and browser renders it. Here author is referring to breaking down that kind of code in to a set of views. So your page is made up of multiple parts. And each part gets rendered and updated independently. Or one model change can trigger a series of updates on some or all parts.
Basically this allows you to create 'desktop' kind of applications on web. And you don't have to resort to iframe hacks to do this.
Gmail and Google Reader are good examples of web applications built with composed views.
I created LayoutManager for Backbone.js because I too wanted to composite views.
http://tbranyen.github.com/backbone.layoutmanager/
Let me know if you find this approach helpful.
It sounds to me like the author is talking about server-side code here. Building a system of reusable page templates, that generate pages from a common set of widgets, html snippets, etc...
Apache's Tiles is one way of doing this.

Is Backbone.js only for single page applications?

I'm searching for a simple architecture for my UI that will have some basic javascript functions in like: select all checkbox's, image crop, some pop-ups and some other plugins.
I found this article: Organizing Your Backbone.js Application With Modules
My application is not a SPA (Single Page Application). I want to know if Backbone.js with jQuery will help me even if my application is not a SPA.
The strength of Backbone is really in its ability to manage many models (even complex ones) and keep the rendered page in sync with their current values. It provides an interface to getter/setter functions so that the changing of a model value (there are many different flavors of "change") will call render on the corresponding view and the page will correctly reflect the underlying models. Furthermore, it provides interfaces to saving, paging, and routing actions on models.
I have used Backbone extensively for both SPA's (where it shines) as well as more traditional, multiple page applications. It has no special support for UI and DOM manipulation, but combined with jQuery/Prototype/Zepto it manages their rendering/manipulation.
Basically, backbone works best to untangle elaborate chains of rendering logic and model updating. If you feel that your application has a lot of view elements that need to stay in sync with models that the client will be updating on the page, Backbone is a wonderful solution. If you just need to select and manipulate DOM elements, it's overkill. jQuery alone can handle that.
Backbone is really not about the things you mentioned, but I wouldn't say it is strictly for single-age apps (SPA) either. I'd say it is for any case where you've got quite complicated pages and it would benefit you to break them up into multiple pieces (for example, several views that all pull data from one model).
However, I would say the strength of Backbone.js is in the SPA realm.
You could probably find some jQuery pieces that answer some of your needs if you're not already using jQuery as part of your app. However, jQuery is all about the parts you mentioned (easy DOM manipulation, popups if you use jQuery UI, etc.) and not about structure or organization.
I believe that the principal idea of backbone, is organize you JS code in complex app using the MVC concept.
This way your app becomes easier to mantain and add new features, It get easy to use frameworks tests like jasmine.
Backbone also make possible (and very good) work based on SPA approach, using ajax request to server. It is completely based on Restful concept, to get a code using backbone, is important to understand what is Restful.
Basically Backbone have a Router (that can work like a controller. but is not a controller).
Model that is where you can manage all the data logic of your application.
Collection that is like a list of models.
View that is where you will react accordingly the model changes.
There are other things, but basically, is this.
But as I said before, you can use it without have a SPA.
The most important thing to have in mind is that the concept of MVC must be followed when using backbone. If you don't do that, it doesn't make sense use backbone.

Categories

Resources