Being some random rails dev, and getting around all those backbone/underscore javascript stuff…
Backbone seems interesting, but in a functional point of view (I mean the way you can get your data back from the db and your page can be updated), I can't see any real good reason to move forward to backbone. I'm saying, compared to the RJS approach rails bring.
With backbone, more things happens on the client side; but can't see any fundamental difference besides this fact
Any backbone-evangelist's feedback appreciated
It's definitely going to be a matter of preference, but here's some rambling as to why you might want to go with something like Backbone over something like RJS.
RJS is great for when you just need to return code like $('#post_#{#post.id}').slideUp() or something like that. When you want the backend to be in control of the front-end directly. This does make sense for a lot of apps, for sure. But when you start getting into more complex stuff: change the post title, change the post body, change the post tags, change the post title in the 'recent posts' sidebar, etc. This can get difficult to maintain quick. If you change the markup subtly you can break all of your RJS. Also, using RJS, it's pretty difficult to change the whole page and keep the user sane (eg, you will break back buttons and generally stomp all over the state in the browser).
So, for bigger/more end-to-end applications, you can institute something like Backbone as a way to keep your code organized, and move the logic to handle the display of your data to the client. Some benefits:
You will put less load on your server, since the client will do a lot of rendering work.
You change some markup in a client side template, it's natural and simple to modify the corresponding Backbone.View if there are changes to make there, instead of at the bottom of potentially several controller actions in Rails.
You can easily handle navigation between multiple pages/states, and keep that logic on the client.
It's very easy and low-barrier to organize your javascript strictly into whatever makes sense for your app (eg, collections.js, models.js, views.js, or maybe app.js for smaller stuff, or maybe post_view.js, posts_collection.js... whatever you need)... again rather than having javascript spread into procedural chunks all over Rails.
If you have an application that lends itself well to being on a single page (eg, lots of shared elements like navigation/sidebars/etc between pages for example), then it's going to be a pretty good fit for something like Backbone.
Your Rails app can act more like an API which any number of front-ends can use - the Backbone one for the web, an iPhone app, and so on.
There are surely downsides, too. You have to write at least some of your application's view/controller logic in Java(/Coffee)Script, and you have to be careful, when you don't reload the page for long periods, not to cause memory leaks and javascript errors that can kill your app. When is it not about tradeoffs, right?
A high profile example of someone not using Backbone when it otherwise might have been considered a good idea can be found at this 37signals post about Basecamp Next (and the corresponding HN discussion).
Let me know if I can clarify anything here for you.
Related
I'm using .NET MVC for all my serverside logic and serving out initial pages, but my application is very heavy on the client-side so I have adopted Backbone.JS which is proving to be very useful.
I'm unsure how to architect my system to incorporate both technologies though. The way I see it I have two options
Scrap the 'V' from MVC on the server-side, return JSON Data to the
client on pageload and use backbone clientside templates to build up
the GUI from the base JSON/Backbone Models.
Return the initial pages from the server fully rendered in .NET MVC.
Also return the data that was used to render them and call the
collection.reset({silent: true}) method to link up the
returned data to the view. Am I right in thinking that this will
allow me to subsequently make changes to using the add/remove/change
handlers on the views?
1 Troubles me as I'm afraid of letting go of any part of server-side MVC, its where my core skill lies.
2 Troubles me as I'm concerned I might be introducing risk and work by having two different rendering methods on client server.
Whats the correct way to combine Server-side MVC with backbone.js 1 or 2 or some other way?
You are not really scrapping the V, you're just changing it's representation from HTML to JSON. You are troubled because you feel more comfortable with the server side stuff, and that's not really a valid concern... you'll get done what needs to be done, and learn/create the Javascript patterns as you go.
This is one way to do it, and it really helps if you need a javascript disabled fallback or you're bound by accessibility guidelines. The part you're missing is that you will have to re-render the page once it's loaded to attach your models up to the DOM elements. Alternatively you could use a tool that handles this mapping for you, but that's added complexity you'll have to weigh out yourself.
In the Careers usage of backbone, we are not bound to support javascript-less scenarios, and we so we just load the templates + js on the initial load, then let the router take over and use something more like your first idea. Since it sounds like you're just getting started, the biggest thing that helped us really get moving was realizing that it's way easier to make changes to your model and then let your views subscribe to model change events (instead of the other way around).
I don't know what the Accepted Way is, but I've found it problematic to combine V from the server side and then weaving Backbone (etc) in. In very controlled situations it can work out, but if your app is going to be extremely heavy on the client side, my suggestion would be to forget about rendering on the server side and just return JSON and let Backbone handle the rendering of your content through some sort of templating (Mustache, etc).
Yes, you have full control over the Backbone events, so you will have a handle on them to do what you wish.
I hear you about giving up part of your skill set on the server side. I was the same way but if this is what your project calls for, I think you'll find it easier to let the server side rendering go for this.
Good luck!
I was wondering this for quite a while and haven't really found an answer for this yet.
Why would you use Backbone.js exaclty inside a Rails application? Is it to extend functionality, have a more MVC pattern for your JS, build better API's...?
At the moment I can't see a reason why you would want to use it for something, because I don't think I understand the concept of Backbone.js
The big advantage of rails is that you have one platform and one language that you use that will handle the server-code and can generate the client-code (using the views).
Undoubtedly this theoretical advantage quickly starts slipping once you want to improve your user-experience with javascript and jquery. So actually you still have to learn two languages.
But still: all your models, business-rules, ... is handled on the server-side in Ruby. This also means that the server always has to be reachable.
What a javacript/client MVC (like Backbone.js, Sproutcore, ...) can offer you is a more native application feel. A single web-page application, like e.g. Gmail.
Depending on your requirements there are some very valid use-cases for such a platform. E.g. in places or devices with low connectivity it could be very useful (with HTML5) to have a web-application that does not need to be "online" all the time. It could save data and edits to the local storage and sync back to the server/database when the device is back online.
But, there is a big disadvantage when developing client MVC applications in combination with Rails: you will have to do some double development (it is the same when you are using flex/silverlight). Your models will need to be defined both on the server and on the client. I can imagine that some improvements could be made, like on the client MVC you are actually using presenter-classes, which on the server-side could be stored in different models/tables. But still there will be duplication of logic, models, ...
So that's why I think that for most applications, at the moment, it is not wise to switch to some client MVC framework. It will be a lot more work.
But when you do need the look and feel of a real native application, or a one-page-web application, then a javascript client MVC framework is the way to go. And if you do need a client MVC framework, I would propose Sproutcore.
To simply ajaxify your current rails application (reduces load-time of every single page), take a look at pjax-rails.
(better late than never - hope this is useful to someone)
The description on backbonejs's website seems like a lot of words thrown together without much meaning. There is a big hype around it but what's all the fuss about?
The premise behind backbone is that modern day, single page web apps (think gmail) quickly become a very complex interaction between syncing dom elements, UI events and the backend. You could easily find yourself storing data within the dom elements, and then having to somehow extract the data again to update the database. If you don't structure your code very carefully, you'll quickly end up with spaghetti code full of complex bindings, or code without backbone.
Using backbone's models, collections and views gives you a well thought out structure to work within, allowing you to build large apps without being overwhelmed by their complexity. What's more, it ties in beautifully with a restful backend.
Isotope lets you write templates in javascript. These templates can then be rendered by either the client (using plain-old javascript) or on the server (using Johnson).
The benefit is DRYer code. When updating the DOM on an ajax or web socket update, you can don't have to write a new partial...just point it to the one you already wrote.
Has anyone used this?
Interesting, I would have to try it, however , and I know not a lot of people do it, but I actually use HAML to template .js files. Although there is still that problem the author mentions , of each request being templated on the server and sending back html, unless you are sending loads of kb, or you have really, really high load site I don't think it's such a big deal.
Also ideally you shouldn't be even sending html data back and force, just JSON objects, which are rendered on the page by your ajax request. The only legitimate use I can see for this is if you have heavily ajax website, such as where you load a page once, and the you just keeping doing ajax requests for all interaction and javascript to manipulate view.
So it would help if you would clarify the final goal. Is this for some internal app where you control user environment ( you know for sure which browsers they will use, and that they will have fast enough computers to manipulate all this javascript?) Or is it going to be an app targeted towards 3rd world, where people don't have yet resources available to use all that fancy javascript.
All that said, it's an interesting concept, and I will try it our myself, to see how well it works.
This uses Johnson, which last I checked did not work on Ruby 1.9. So that might hint at some of the immaturity of this particular solution. Eventually the community will come up with something that works really well.
One approach I have used is to make 2 completely separate templates, but try to make them as similar as possible so that it is easy to port changes from one to the other.
This seems like a bad idea. In an Ajax application, I believe that the server should be responsible for rendering all display text. This makes i18n easier, and concentrates everything in one place. The JavaScript should simply receive data from the server, with all display text already rendered, and put it in the appropriate DOM object.
In other words, I believe that in an Ajax application, the need for a JS template engine is itself a design smell.
The situation is different in exclusively client-side JS applications, of course.
Is it common practice for people to NOT use rail's built in support for ajax? Or is it very flexible and it can really help speed things up and there is no need to go custom?
If by ajax you mean ajax view helpers, in rails 3 they are implemented quite well, and there really isn't a reason not to use them. If you mean RJS, it is a much faster way to get stuff done, but if you want to build highly dynamic and responsive interfaces, there is no shortcut to writing the javascript yourself.
Rails 2 was heavily tied to Prototype and was pretty obtrusive; it seemed a lot of people didn't use. Rails 3 is far more unobtrusive and framework-agnostic, and I expect it will be used a lot more.
Let me put it this way..
Using built in ajax functionalities will will save lot of your time and get your app up an running with no-time. But the problem is once your app starts growing and when you need more and more cool ajax features, its hard to manage.
Another thing is, If you are working on a team and there are UI designers to implement UI. sometimes they find it difficult to deal with built-in rails ajax functions. As they prefer go with pure Ajax framework and HTML.
Basic concept here is to let the UI designers to implement a user friendly interface while rails supports back-end features
** I really like the rails3 approach of Unobtrusive javascripts. which makes the clear separation of java scripts and server code
So as a sum up - Its all depending on the requirement. If you are looking at a small scale project with defined ajax functionalities you may go with default rails ajax support.
But if your app will grow and if you want to continuously implement your user experience its a good idea to have your own custom ajax implementations up on proven framework like jquery
cheers
sameera
I am not sure what you mean by built-in support for ajax. Because Rails has very good support for Prototype and jQuery.
But in rails 3 there is (good) push towards unobtrusive javascript, and that is indeed imho what most people do.
If you are talking about rjs, generating javascript with ruby code: that is imho best avoided. Sometimes it is good to get you started, and doing things unobtrusively is sometimes a bit harder at first, but it is generally much better.
The rant against rjs: it is not unobtrusive, you mix two languages, it only works for very straightforward cases (granted most cases). But because you can't do everything with rjs, there is bound to be a need to let some 'real' javascript slip in.
At first i really liked rjs: one language to do everything in. Until you discover the boundaries, and then you are stuck.
So i would suggest, for anybody new beginning in Rails: skip rjs. It will help you in the long run. Do javascript unobtrusively.
It is the same division in CSS: you want all your stylistic definitions separate from the content. Well, actually in js you want the same: you want your behaviour separated from the content. This makes for very clean HTML, clean CSS and clean js.
I am sorry for possible misleading about the title, but I have no idea for a proper title.
Feel free to edit.
Anyway, I am using ASP.NET Web Forms, and maybe this isn't how web forms is intended to be used, but I like to construct and populate HTML elements manually. It gives me more control.
I don't use DataBinding and that kind of stuff. I use SqlConnection, SqlCommand and SqlDataReader, set SQL string etc. and read the data from the DataReader.
Old school if you like. :)
I do create WebControls so that I don't have to copy-paste every time I need some control, but mostly, I need WebControls to render as HTML so I can append that HTML into some other function that renders the final output with the control inside.
I know I can render a control with control.RenderControl(writer), but this can only be done in (pre)Render or RenderContents overrides.
For example.
I have a dal.cs file where is stored all static functions and voids that communicate with the database.
Functions mostly return string so that it can be appended into some other function to render the final result.
The reason I am doing like this is that I want to separate the coding from the HTML as much as I can so that I don't do <% while (dataReader.Read()) %> in HTML and display the data. I moved this into a CodeBehind.
I also use this functions to render in the HttpHandler for AJAX response.
That works perfectly, but when I want to add a control (ASP.NET Server control (.cs extension, not .ascx)) I don't know how to do that, so I see my self writing the same control as function that returns string or another function inside that control that returns string and replaces a job that would RenderContents do, so that I can call that function when I need control to be appended into a another string.
I know this may not be a very good practice.
As I see all the tutorials/videos about the ASP.NET MVC, I think it suite my needs as with the MVC you have to construct everything (or most of it) by your self, which I am already doing right now with web forms.
After this long intro, I want to ask how can I build my controls so I can use them as I mentioned (return string) or I have to forget about server controls and build the controls as functions and used them that way?
Is that even possible with ASP.NET Server Controls (.cs extension) or am I right when I said that I am not using it right.
To be clear, I am talking about how to properly use a web forms, but to avoid data binders because I want to construct everything by my self (render HTML in Code Behind).
Someone might think that I am appending strings like "some " + "string", which I am not. I am using StringBuilder for that so there's no slowness.
Every opinion is welcome.
You need to stop thinking in terms of "controls" and webforms. MVC is a completely different way of constructing applications.
I also hate the automatic renderers in WebForms, they produce horrible html that never makes any sense. However, you dont want to be writing your html in your codebehind and passing it around as strings, thats just nasty. Your presentation code is mixed in with your logic, AND youre writing HTML in c# strings!!!
So, MVC... Instead of "widgets" that do interacty things with codebehinds and postbacks, yours view ONLY display data and contain forms to allow you to post to the controllers.
Because of this, you can strongly type your views to a Type, and then access the data you pass to it from a controller via the Model property. The equivalent to UserControls are Partial Views (ViewUserControl) which can be used to modularise your rendering code for types. For example, you might make an Address partial to which you pass your Person's Address property every time you need it rendered. This way you aren't repeating html all over the place.
P.S. A single file for all your DAL?
I hope I never ever have to work on an app you wrote in this manner. If your application is string-heavy then something is wrong.
Agree with #sliderhouserules, the way you are using MVC framework is awful. You must forgot all your "old school" techniques.
You should never use SqlCommands, SqlReaders, etc. in the code of the pages. You should pass to the view only a model (e.g. View(bar)) and it will be better if you avoid usage of
ViewData["some magic string"] = bar
Every time when you will use "old school" technique 2 mans and 2 cats will be killed :).
Also it's better to use some ORM (Object-Relational Mapper) like Linq2sql, NHibernate, SubSonic, etc.
If you need in samples of good application design please look at SharpArchitecture. It has a very good architecture and implementation and may help a lot. It has one sample (with Northwind db) and one more sample will be added soon.
Also look at CodeCampServer. It has very good architecture too.
It's better to look at the code of these projects instead of looking videos because existing videos can't demonstrate good sample of architecture, just a simple usage of functionality.
About server controls, you may use them if they can be used without 'runat="server"', like PlaceHolder. And you may create them too, but you shouldn't load any data in them directly. If you don't want to copy-paste html you should review your code and you should refactor it. Every duplicated code should be moved to MasterPages of UserControls (ascx ones).
And once more, please spend some time to look at these samples. You'll save your nerves and time in the future when you'll need to update the app or fix something. At the first look they can be hard to understand but this is only at the first look.
Hope this helps.
#lopkiju, I think that the MVC pattern would serve you much better than your current WebForms solution if you want that much control over the output HTML.
You can use Web Forms this way as you already do, but it is not designed to be used this way, so it will be a pain.
More detail
In my opinion, read some articles about the Separation of Concerns (also known as SoC) principle. If you apply it correctly, it can save you many-many headaches when you'll debug your app, and also for those people who you work with (eg. those who may have to read or modify your source code).
My other tip for you is this:
You are right that you shouldn't do things like <% while (dataReader.Read()) %> in your View code. But perhaps there are better ways to make it more elegant than your current way.
I think you should consider using some sort of ORM for these purposes. (LINQ to SQL, or even NHibernate.) If you get it, it will be much simpler. So much that you may not want to use DataReaders directly again. :-)
What I recommend for you
Simply, read the NerdDinner tutorial, and build the samle app by yourself step-by-step.
After that, try to build a similar app that serves a different purpose by yourself while applying the same rules and design that you applied to the tutorial.
I'm pretty sure you have the expertise to do it, and after actually doing something with it, you can pretty much get the feel of it.
The tutorial also explains and includes the principles I mentioned above, which will be very much use to you.
If you want the ASP.NET MVC path, you can set up controls as ASCX and they will simply be tags filled by the controller. It may not be old school enough for you, however.
You can create your full UI in code behind, if you so desire. This can include creating the HTML in routines.
But, I would recommend, if you are sticking with ASP.NET, reconsidering the bind model over the DataReader.Read() and output + loop. It is not only old style, it is highly inefficient and hard to maintain.
ASP.NET MVC does create a much looser ASPX, as it is just a view. And there is a much greater separation of code and UI. But it will not fit with the old school model either.
Have you considered using micro-templates? Dave Ward has a good example of of a client side data repeater that is uses micro-templates for layout after making a call to a page method. This sounds like this is more in the spirit of what you are trying to accomplish and can still be integrated nicely with WebForms.
The side effect will be that you will not rely on passing around HTML and can isolate your presentation from your logic.