What problem does backbone.js solve? - backbone.js

When I gloss over the backbone.js site, I'm not sure what is it trying to do.
It seems somewhat popular, but why should I want to learn it? What will it do for me? Why was it made? What problem does it solve?

I find the question perfectly valid and from my point of view there is nothing wrong with inquiring about the potential use cases of a library/toolkit.
What Backbone.js does (so do several other javascript mvc implementations) is that it provides a means of organizing the code into a modular pattern known as MVC pattern which is all about separating your code into three loosely coupled layers:
Model layer dealing purely with data and associated operations
View layer being the presentational aspects
Controller layer being the binding glue layer
(different frameworks deal with this differently : Backbone implementation of controller layer comprises of client side routing capabilities).
So, on the whole backbone provides you an infrastructure using which you can deal with data through models which contain encapsulated within them the data and associated validations, which can be observed ie. you can bind events to change events.
The View layer is mostly left for the user to separate the ui into manageable isolated sections.

Here are some problems that Backbone solves for me in the JS/HTML space:
Separation of Concerns (SoC)
Composability
Testability
Component Model
Abstraction
That is not to say that this is the ONLY system that does this. There are others. Backbone does a pretty good job of helping with these things, though.

From backbonejs.org
It's all too easy to create JavaScript applications that end up as
tangled piles of jQuery selectors and callbacks
And that's exactly what backbone does, a series of callbacks on model changes and jQuery selectors to bind events.
So to answer the question, it solves nothing only to provide a way (the backbone way) of structuring code with some slight automation in the REST side of things.

Related

Backbone js app structure

Currently am writing all my business logic inside the view class which make my view class unmanageable. Am planning to create Backbone object and move all the business logic there and invoke it from view class. Please correct me with right way of thinking
Backbone in general does not provide an entity named Controller, this is one of the reasons which Backbone called MV*. Generally user interact with views, you know well this interact means change and update over models.
"So does Backbone.js have controllers? Not really. Backbone’s views typically contain
controller logic, and routers are used to help manage application state, but neither are
true controllers according to classical MVC." (Addy Osmani Book's)
so i think your way is not incorrect, but you can improve your project structure through this solutions:
Marrionette (and also Thorax ) is a excellent framework that provide such a excellent structure for your app. You can read this annotated code and get some tip from it.
You know certainly AMD a nice api to provide modular pattern in js. Require.js a nice tool for organize your code. For more information i recommend check TodoMVC + Backbone+Require code.

Backbone.js modular setup

I am new to backbone, and I'm here to ask for a little bit of help understanding how I would go about building my current webapp project. I'm developing a modular administration panel for servers. Every single "page" of the panel should be a packaged "module" including controllers, models and views.
The panel will consist of a main layout view being loaded initially, with a basic navigation. When a user clicks on a link on the navigation, a page gets loaded via AJAX into the layout.
(And if this sounds stupid / there is a reason not to do so please tell me :) )
Since others will develop these pages too, and since they are modular, I won't know what models, views and controllers I will be presented with inside the page i load via AJAX.
How would I best go about doing this with backbone?
I'm especially wondering about how I would extend Backbone models etc. dynamically, and how I would manage (for example) the user leaving the page and / or revisiting it later.
Does Backbone provide something I can work with, will I need to hack myself something together, is there a better way of doing things I am missing?
Your thinking around the problems sounds very correct. Make your UI components self contained as possible. Watch this 10 min video to get some more information on UI component best practices.
If you are interested about other important concerns of JavaScript application development, look at BoilerplateJS reference architecture which I published to share my experiences. That contains a similar sample application as you described (menu with component activation).
my recommendations for your UI component activation, deactivation are:
Do not remove/create DOM components. Reuse with hide/show, as your elements will recide in memory even after removing from DOM
Minimize keeping 'state' information on client side. When an user revisit the component, refresh it with a server call and then make it visible (use server as the single truth of state information).
See BoilerplateJS sample component implementations for more details. I know few who use it with BackboneJS (currently it ships with knockoutJS). We will ship a example of it using BackboneJS in v0.2 which is due in a week.
A common modular script loading framework that is used in conjunction with Backbone would be require.js. It might be what you're looking for. Require.js is all about AMD modules, asynchronous modules. Usually each model, collection, view is it's own module that defines the dependencies that particular module needs then loads those modules as needed. It's particularly well suited for large projects where you have lots of individual pieces that need to be mish-mashed together at different points of your application.
You could of course combine multiple backbone elements in a single module (usually I reserve this for Views and specific subviews that would only be used with the parent view) but it's really up to you.
With Backbone, usually the intent is to create single page applications - meaning all the page scaffolding is usually wrapped up as a single file and completely loaded onto the client-side at the get go. The data for each page is then called via ajax and populated as the user navigates and loads different aspects of the application. Is this what you intended in your description?
If you're looking to load different pages that are each individually grabbed form the server, then I'm not sure Backbone is the answer. There are other server-side MVC frameworks that help to accomplish that.
That generally touches on how Backbone is used for this sort of thing.
As for how to extend Backbone models and such, Backbone uses Underscore as a dependency and underscore provides a nice _.extend() function that can easily extend all your objects in pretty much any way you desire. Overriding default functionality, throwing in mixins, it's all pretty painless as far as Backbone goes. As a framework, Backbone is very agreeable when it comes to altering, modifying and customizing every little bit and piece.
As for handling users visiting and revisiting pages, Backbone.router allows you to create URLs that not only point to specific "pages" in your app but also to execute arbitrary code that needs to be executed to get there. Something like a logged in user visiting "mysite/#account" would trigger the router to load certain scripts that bring up that particular view as well as perhaps fetch() necessary data to get that view up and running for the user.
I'm not sure if there are resources out there that give you some kind of basic structure to start with. Most experiences I know of tend to go through the basic tutorials like "Todo List" and work their way up from there. I'm not sure what your experience level is with javascript or programming in general but I started with Backbone AND require when I knew really pretty much nothing. Only a vague notion of what JSON was and a low level understanding of HTTP as in, "it's that thing that gets web pages." That said, I think Backbone was really easy to get for me to start with and it's deepened my knowledge a lot about the whole client-side RESTful type app structure.
There is a really good list out there of the "Todo List" app in many different flavors such as Backbone and Knockout and some others. When deciding on a framework, I basically went through that code comparing all the different frameworks available and selected Backbone because it just seemed to make the most sense to me. I don't regret it. It's a lot of fun and I think the best way to get into it is to just try some demo tutorials.
Take a look at Marionette or Chaplin. Both are build on top of Backbone and provide a structured way to build larger application with Backbone.
Here is tutorial to organize your application as modules using backbonejs
http://backbonetutorials.com/organizing-backbone-using-modules/

What is a reasonable way to use MVVM coding patterns with HTML5

I have a nice application written in Silverlight. To allow greater cross browser support, we are considering rewriting with a HTML5 front end.
What would be a reasonable way to move from Silverlight using XAML and C# with MVVM coding patterns into a HTML5 front end.
On the other hand, if this is not a good idea and the MVVM pattern should be abandoned, please explain why.
Knockout is a great javascript library which helps you to write MVVM client side. You create your view models in javascript and bind to them using html templates (with the help of jquery templating). Your view models can use ajax to retrieve data.
It is essentially the same as Silverlight development- you have HTML instead of XAML and javascript instead of C#/VB.Net. You could even use the same web services really...which might be helpful if you plan to offer both interfaces or conversion later on.
Edit
Thought that I'd add that IMHO MVVM should not be abandoned as it really does a great job of separating concerns (I guess when implemented correctly) but a big win surely is that it has the developer thinking about or in the mindset or separating responsibility in an application. I've used Knockout.js for web projects and Caliburn.Micro for Silverlight and have really enjoyed that style of development.
Knockout is MVVM pattern implemented in HTML/Javascript with databinding and all.
http://knockoutjs.com/
If what you want is achievable simply through DOM manipulation, and you're used to and like the MVVM pattern, Knockout should be a good choice.
Yeah, the MVVM pattern for HTML 5 is called MVC. Most easily implementable with MVC3. Provides a layer of abstraction in respect to the JavaScript code, support for ViewModels (aka Views) and separation of concerns between the views, data access, and business logic.
Best of all is that validation and UI event handling is wired for you in a simple manner, allowing you to abstract yourself from the intricacies of JavaScript event handlers for various HTML controls.
However if you strictly want to stick with HTML & JavaScript, I suggest rolling your own JavaScript classes (yes JS is functional language, but you can still make those) that represent your UI layer and handle UI events. Then create your own Ajax library for getting JSON serialized data back and forth from the UI classes to the server back end. Finally create your own business logic classes (also in javascript) to control your UI and DataAccess (ajax) classes. In short.... lots of dirty work.
There is also the experimental Model Driven Views (MDV) library from Google.
Unfortunately, it is only intended as a prototype showcase. Conceptually, it is really cool, but be prepared to do some bug fixing on your own.
http://code.google.com/p/mdv/
There is also JSViews. This one is not as slick as Knockout, but it is faster at updating the DOM. The project is loosely related to jquery as its author was behind the now scrapped query templates.

Is it feasible to reuse WPF ViewModels in MVC?

we have a rich client application written in WPF/WCF and are intending to create a companion website in ASP.net (using MVC if possible).
I've been asked to figure out how much of our current codebase, we can reuse (by a separate team) - and I have little to no experience with ASP.net.
We will reuse our domain model, but is there any point in separating out the WPF-specific parts of our ViewModels and reuse the WPF-agnostic parts in MVC? Does it even follow the same paradigms? We use RelayCommands exclusively for commanding, so it would be easy to wrap the contained methods in something ASP.net specific... But how about UI-specific things - e.g. does ASP.net use INotifyPropertyChanged - or how does it handle UI-updates?
For me it wouldn't make any sense. Your models should contain all of your important business logic code and should be the point of greatest reuseability. Your view models should contain presentation logic only, and as this is so different for a desktop and web app, it doesn't make sense to reuse these.
MVC does not use any binding mechanism for UI updates, as web apps are stateless by nature. You will actually most likely end up using view models for your MVC app, but in MVC these act as simple data transfer objects (DTOs) for providing data to the views for rendering for each HTTP request. Once the view is rendered, you would need to go back to the server to update the view model and rerender the view.
Alternatively, you can of course update the UI client side with scripting. Knockout.js is a nice JS library for client side view model/view binding.
I can't directly answer your specific question because it depends highly on your application and the way your existing view-model is written but the question you raise is an interesting one.
On the one hand, the logic that the view-model contains very little view-specific code is a tantalizing argument for reuse. On the other hand, the view-model very clearly serves the needs of the view and expecting it to serve the needs of a different view could be problematic.
In the end all we can give are guidelines. You certainly don't want a monolithic view-model with ifdefs or ifs all over the place. You could refactor common functionality into base classes -- that's the object-oriented way -- but without good unit tests it's sure to break something in your already working code. But not doing that means having distasteful cut-and-paste code that is almost the same and likely to diverge creating a maintenance nightmare.
Perhaps a practical approach is to assume you'll need a whole new view-model but to review your existing view-model for code you can push down into the model before your start, thereby making the view-model as small as possible. Then at some point, maybe after you get a prototype working, you could attempt a merge to see if it is practical and what issues arise. If it can work, take those issues into account as you continue implementation and then plan the two tasks according to your needs.

MVC vs. Observer Pattern

I've recently asked a question on StackoverFlow about the MVC: Can the MVC Design Pattern / Architectural pattern be used in Desktop Application Development?
Based on the answer provided I started research on how this would be implemented in a Windows form Application. I came upon the following CodeProject article: http://www.codeproject.com/KB/cs/model_view_controller.aspx
In the comments below the article, certain users argue that (although this is a good article) it is actually the observer pattern. First, but less important, question is does anyone agree or disagree with that and why?
Regarding the second and more important question: I'm trying to build a small task list program in .NET. It will be very tiny and hopefully fast. In general, what would be a better architecture for such a project? The Observer Pattern or the MVC Pattern? Or another pattern?
Thank you
usually the model in an mvc (http://en.wikipedia.org/wiki/Model-view-controller) is an observable/subject (http://en.wikipedia.org/wiki/Observer_pattern#Subject), while the views are observers (http://en.wikipedia.org/wiki/Observer_pattern#Observer). also see: mvc in http://webcourse.cs.technion.ac.il/234321/Winter2005-2006/ho/WCFiles/08-Design-Patterns.ppt
(The article is not an example of MVC AFAIK for the simple reason that there is no controller.. it is more close to .net data binding if you ask me.)
MVC is not the Observer pattern. MVC is concerned with separation of concerns. The Model, the View and the Controller all do one job and trust the others to do theirs. In a way, the Controller 'directs' the view and tells it how to react to a change (Pure MVC). The controller also interacts with the model appropriately (whose responsibility is to encapsulate data and enforce constraints/rules). In MVC, the controller is the starting point for all activities - user input is received by the controller first.. However there are variants like MVP, where the user is input is received by the view first and then pushed/synched with the presenter.
The Observer pattern is where you want to watch another object for a change in state. So you could say .net events follow the observer pattern
If its really tiny, forget about patterns and just code it up without worrying about the architecture... Follow the heuristics/principles of good design
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
http://mmiika.wordpress.com/oo-design-principles/
If you run into design issues or it starts to get all messy, then bring in the pattern battalions.
I would agree that the article is not MVC. Its more of an implementation of observer pattern. Observer pattern in .NET can be implemented by using events, which was the case of the article.
MVC requires a controller class that controls what action to execute upon a request made from either the model, or the view. Applying MVC is a very good programming practice as it greatly promotes separation of concern. You will have a cleaner, more extensible, and more testable app with mvc. Another point to note, you can still apply observer pattern to an MVC app. They will not contradict each other.
===========
To answer your second question: which pattern is the best? I think the way you approach software development is rather wrong. You shouldn't worry too much about those things yet, not until you've hit a problem. e.g. If this object changes state I need these other objects to react to it, hence I would implement an observer pattern.
If I were you I would start on the model side first, and then takes things from there.

Resources