In the last few days I've been reading about Backbone.js and how it simplifies JS code interaction with View elements, basically within HTML. I've also read about the differences between KnockoutJS and Backbone.js. Now I'm thinking whether using one or the other inevitably leads to duplicating the code that we already have in our MVC app (mostly ViewModels and routes in global.asax) inside our Views. Essentially requiring us to code another set of Models in Backbone or Knockout. As I understand, with KnockoutJS this is even more prevalent, that's why I thought I will choose Backbone but now I think it is not that different - after a few examples I saw that same duplication is becoming evident.
Also how do we maintain such an application if for instance we already have a bunch of MVC Partial Views and now we are supposed to recreate them in Backbone using some templating engine like JQuery templates?
Have been reading about backbone and knockoutjs myself lately, and was also pondering about how to leverage the framework with asp.net mvc. One approach to avoid the duplication of models is to serialize (json) the server side viewmodel and use it as your backbone or knockout model. Positive side effect, your client side models already contain the data on page load and don't have to fetch the data via an ajax request when the page is first loaded. I'm aware that only serializing the serverside viewmodel isn't enough for backbone/knockout, but it could be a starting point. Perhaps the serialized model could be a property on the clientside model.
About jquery templates, I usually put a jquery template in a partial view. This way they are easily rendered in your view like this:
<script id="SomeTemplate" type="text/x-jquery-tmpl">
@Html.Partial("Templates/SomeTemplate")
</script>
Obviously, porting an existing application to leverage jquery templates will take some time and effort.
I used backbone with Rails on a project once, and I ended up redoing all my templates in Underscore - underscore.js is a dependency of Backbone and comes with its own templating language.
My app was not huge, so it ended up not taking a lot of time. If your app is already pretty complex, than it may be a different story.
Like Suhas said, Backbone's collection has the ability to fetch all your models from the server and you can send them back using a save functionality that piggy-backs on Jquery's ajax calls. All you have to do is make sure they are serialized through JSON.
I found a recent 4-part series on using Backbone with ASP.NET MVC 3 - maybe it will be helpful to you: http://www.bitcandies.com/blog/2011/asp-net-mvc3-restful-application-tutorial-with-backbone-js-part-i/
Plus this makes a good reference for me to refer back to when I make a go at .net mvc :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With