Backbone JS not very jQuery like? - javascript-framework

Backbone JS highly recommends you use jQuery. However, it doesn't do things very jQuery. For example, jQuery removes the necessity of the new operator, backbone makes heavy use of it.
On another note, I'm looking for a framework that is based more around prototypal inheritance than classical inheritance (new). jQuery doesn't fall under this category, this is just an architecture style I am leaning towards.
Are there any frameworks that use prototypal inheritance, or is it roll your own bridge pattern?

Backbone and jQuery solve different problems... Backbone essentially gives you a structure in order to make Javascript heavy apps... It gives you Models, Collections, Views and Controllers (although, based on only a day of playing with it, it feels to me like controllers are used for routing, and the views are kind of like a classic controller)
Backbone has a dependency on jQuery (or Zepto if you're that way inclined) to help it do things like AJAX requests.
You are correct - it is not very jQuery like, but it is providing you with something very different...
UPDATE
As of version 0.5.0 backbone have renamed controllers to routers, which should make things a little more obvious for folks coming from MS MVC / Rails etc...
"We've taken the opportunity to clarify some naming with the 0.5.0 release. Controller is now Router"
http://documentcloud.github.com/backbone/#Router

I fully agree with the answer provided by Paul and also would like to restate that your question is ambiguous in its essentials.
Jquery is highly dom-centric and provides you excellent facilities for operating upon the DOM. Be it changing styles, loading remote content to some portion of document, responding to browser events ... in (almost) everything the core focus is upon the DOM. For this kind of functionality, where you are operating upon document content, prototypal inheritance and more significantly the style of accessing widgets through the DOM (check out the APIs of JQueryUI) works rather well. If you identify widgets as javascript objects, then you have to keep track of the objects as well ... which you in case of the programming style followed by JQueryUI etc., you dont have to, because you can access any widget present in the DOM by navigating through the DOM structure or simply through its id (which essentially acts as a global identifier for the element).
backbone.js is altogether built for a different purpose. The very introduction clearly states that it is built upon the underlying philosophy that tying your data to the DOM is bad.
When you build an application that structured as per backbone.js conventions, you are essentially always concentrated on javascript objects which may be somehow linked to the DOM.
You are defining models that interface with server data sources, models which trigger events when the data contents are manipulated, collections which help you manage large data sets ... whatever, you are always operating on javascript objects which are not hardwired into the Document structure. For such scenario, it is more usual to think in terms of traditional object oriented model.
Once you have an object, the workflow is not much different from what you are habituated with using jQuery because backbone too, just like jQuery, advocates for the observer pattern.
So, in the same manner that you can bind event handlers to DOM elements with JQuery, you attach event handlers to custom events dispatched by models, collectors etc. So the two amalgamate well.
As far as other frameworks are concerned, you might want to checkout Knockout which provides data bindings and observables etc. and does not require you to use new keyword to create instances, rather instances are created by calling functions in ko namespace which might appeal to your tastes. KO has extensive documentation and code examples, which you can explore to decide whether it suites your tastes. I can not comment more on KO because I have limited knowledge about it, but as far as backbone.js is concerned I would very strongly recommend you not to dismiss the framework just because you dont like the way some things are implemented. It does elegantly and robustly what it is supposed to do and maintains an incredibly small footprint.

I think you suffer from a misunderstanding of prototypal inheritance and what you actually want in a framework. If you're modifying prototypes but never using the new keyword, then you're never creating new objects. If you're looking for a framework to abstract away object creation, that's another topic, though you shouldn't be afraid to use the new keyword; It's a big part of JavaScript.
You can actually use the new syntax with jQuery, and when you don't use it, jQuery is actually recalling itself again with the new syntax along with the arguments you passed to it. This is pure syntactic sugar and makes very little difference about anything.
"On another note, I'm looking for a framework that is based more around prototypal inheritance than classical inheritance (new)."
Backbone is built on prototypal inheritance through the method extend that is built into all models, collections, and views. It's quite problem free and easier to use and adds things like super - a hook into the parent's prototype - something that can be more difficult to do with just plain JS prototyping.

Backbone.js brings a codding standard for ajax driven web-apps that don't have to refresh the page in order to serve data.
jQuery brings a set of tools to help you get basic things done without worrying about the browser you're running the code in.
They have nothing in common. It's like comparing a hammer (jQuery) with a toolbox (backbone.js). The hammer is just a part of the toolbox, not the other way around.
So, yes! Backbone.js is not like jQuery.

"I'm looking for a framework that is based more around prototypal
inheritance than classical inheritance the new operator".
There is no 'classical' inheritance on Javascript. Actually there is no other standard way to prototype than using 'new' maybe jQuery just provides a method who does the 'new' inside.
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},

Related

breezejs angularjs ToDo SPA template in Visual Studio

I have a question about design. I've just been through the code of the ToDo template of Visual Studio for building a SPA with BreezejS and AngularJS.
There is a todo.model.js file that do various initialization. One interesting thing is that it extends the TodoList Entity with some additional function (addToDo).
What is the advantage of doing so, over having the addToDo function in the todo.controller instead and adding it to the $scope ?
You could make a good case for moving all of the TodoList level persistence operations out of the TodoList and into some other component. The controller is a potential candidate.
The primary reason that these operations are in the TodoList is ... because that's where the authors of the original ASP.NET template put them!
One of the "community template" design goals was for all of the "TodoList" apps to be as similar to each other as possible. By holding the design constant we made it easier for readers to compare the effect of the different frameworks: Knockout, Breeze, Backbone, Ember. Had any of them relocated these operations, you would not know if that change was imposed by the target framework or was simply the the implementer's preference. We wanted to take our ego out of it and let you concentrate on the technologies involved.
Don't treat these templates as gospel. In some respects they are unrealistic; I can't imagine saving every time a single property of a single object changes.
Learn from them. Regard them with healthy skepticism. Keeping asking questions like this one. Take what make sense to you. Discard the rest.
I believe this is just letting the entity handle its own save/delete functions for items in the list. The controller seems to be handling only adding of new lists. I'm not sure there's any advantage other than keeping the controller clean.

ruby... pull based web framework & design patterns

Please excuse the verbosity here but I need to be detailed.
I recently built a framework that uses a somewhat unconventional pattern. Essentially it's pull based from the view. Rails, imo, is a push based pattern. You push data from the model through the controller onto the view.
In my design the view requests data using custom Liquid (liquidmarkup.org) tags & drops. That triggers calls to backend API's (or return from memcache) which returns JSON which gets converted into ruby Arrays and Hashes which Liquid can iterate through and use as objects within the view. No business logic in the view. It's purely pull.
When the user posts something, a handler (aka controller, but only for PUTS & POSTS) deals with validation & passing along data again to the back-end services. Depending on the outcome the user can be redirected, rendered a page, etc...
The major advantage to this approach is that our frontend guys can design without us stepping on each others toes and also fits in nicely with our SOA environment.
My question... What, if any, design pattern does this resemble or is it a combination? Does anybody know of comparable frameworks using a similar approach? I'd really like to get ideas on improving this architecture and maybe even one day build an open source version. It's worked brilliantly for us so far.
I look forward to your comments.

Just not getting MVC (like backbone.js)

I'm reasonably comfortable with javascript and php; I'd say I'm an intermediate. I'm starting a new project that really does need to be built in something like an MVC framework. I've been looking into backbone.js, but for some reason the logic is just not sticking. I've poked around with OOPHP and of course working with jQuery, a certain level of "objectness" is inherent... but I can't quite get my hands around the basic methodology of something like backbone.js.
Is there somewhere else I should start? A simpler MVC or maybe a good resource that I can work with that will help the concepts and methods stick?
It's just such a paradigm shift. Compared to all the procedural stuff I've done thus far, it really is like learning a new language.
Also, I won't be using a RESTful interface or anything, just good ole fashioned saving stuff to MYSQL via php.
If you are interested in learning the MVC approach using javascript, I would suggest to read Javascript Web Applications. You will also find a chapter on Backbone.
Take also a look at Backbone Patterns.
Well,
technically backbone.js is a variant on the whole MVC concept. Backbone uses a model-view-collection concept rather than model-view-controller. where the view, takes over some work of what the controller in real mvc would do.
it's not a bad thing, in my opinion javascript was never even intended to do such a thing :)
and if you're not used to programming in MVC you might not even notice the difference.
though if you want to start with a few simple examples, around backbone.js i suggest you take a look at this website http://www.backbonetutorials.com/ which gives you a kickstart into building model-view-collection apps (as backbone does it). then when you grasp the concept, you can hop on to the examples given on the backbone.js website. especially the Todo Application which has also provided the annotated source of the object. it's a fully working simple application, which might give you an idea of how it should work rather than having these separated examples. but you have to start somewhere.
Backbone is not an implementation of the MVC pattern. It's better instead to think of it as a MV* implementation, where it has models, but no controller, and its views are often implemented as a combination of view, controller, and presenter, and there is no strict controller or presenter or viewmodel. Understanding that is definitely the first thing to realize when feeling confused about backbone and trying to understand how to use it when referencing the MVC pattern.
The MVC, MVP, MVVM, and MV* patterns are difficult to truly grok with just reading an article or two, or with a simple example, and it seems like everyone has a similar yet slightly different idea of exactly what they are.
For a really really good discussion of MVP and MVC in relation to backbone, read Addy Osmani's article on developing backbone applications Here.
But if you are simply concerned about how to use backbone, and feel like you have to be a MVC expert to do it correctly, then you're worrying about the wrong thing. Instead, look at existing published backbone examples, follow those patterns, and as you add code to your view and model, keep the following points in mind for every piece of code you write:
Is this view specific code? Then put it in the view.
Is this data specific code? Then put it in the model.
Is this code about coordinating the view and model? Tend toward putting that in the view.
A good guideline for # 1 and 2 above, is to not allow your model to reference the DOM at all, then put all the code you can in the model. And only code that has to reference the DOM goes in the view. If you try for that goal, and only violate it when it's obvious that the code is way more convoluted if you put it in the model, then you should be pretty good.

What is the advantage of Model-View-Controller (MVC) over Model-View?

Could anyone give an example of why it would be advantageous to use MVC instead of a simpler Model and a View only.
Note: whether it's called MVC or MVP (Model-View-Presenter), I'm talking about the one where the View receives input, then the Controller will respond to the input event by interpreting the input into some action to be done by the Model. When the model changes, the View will update itself by responding to events from the model.
What is disadvantageous of simply letting the Model respond to events in the View and vice versa?
In MVC, if I changed the model in a way that affects the controller then I'll have to do changes in the controller. In Model-View, if I change the Model, I'll have to update the view.
So, it seems like we are introducing complexity by adding the "controller" part?
In MVC, the Model is blind to its environment, the view can be too - passing off (blindly) its events to the controller, which knows more about the view and model. So when all is said and done, the controller is the 'non-reusable' disposable part of the system, since it is the most context aware component.
if I changed the model in a way that affects the controller...
The the model should expose simple CRUD methods in such a way that those using the methods do not have to know anything about the passed update object, nor what really happens inside the model.
This means that the view, IMO, has to do a bit of work by creating the passed record, since Controllers are supposed to be stateless and the view is more persistent. Controllers get triggered and 'kick-in' do their work with a passed object and do not have a state.
The passed data is created by some sort of generic convention.
Let me go even further. Suppose you have a view, a tablegrid, and a control whose enabled property is dependent on item is selected in the grid -- you COULD create a view that handles both those controls and this logic internally, and that would probably be the way to go in such a simplified example.
But the more atomic your views are, the more reusable they become, so you create a view for every, yes every, control. Now you are looking at a situation where views have to know about each other in order to register themselves for the right notification...
This is where the controller steps in, since we want to stick all these dependencies onto him, the long term disposable one. So the controller manages this type of view-to-view notification scheme.
Now your views are ignorant as they can be and independent, thus reusable.
You can code a view without having to know about the system, or the 'business logic' as they like to call it. You can code a model without having to know too much about your goals (though it does help to tweak the model to enable it to return the datasets you have in mind).... but controllers, they are last and you have to have the previous two firmed up before you can wire things together.
Here is another thing to think about -- just as the Model is supposed to abstract-away and provide a generic interface to the underlying implementation of the data it is managing (the client does not know if the data comes from a DB, a file, a program setting, etc) -- the view should also abstract away the control it is using.
So, ultimately this means a view should not (caveat below) have functions/properties that look like this:
public property BackgroundColor{get;set}
Nor
public function ScrollBy(x,y){}
But instead:
public SetProp(string name, object val){}
And
public DoCmd(string name, object val){}
This is a bit contrived, and remember I said ultimately... and you ask why is this a good idea?
With reusability in mind, consider that you may one day want to port things from WinForms to, say, Flex, or simple want to use a new-fangled control library that may not expose the same abilities.
I say 'port' here, but that is really not the goal, we are not concerned with porting THIS particular app, but having the underlying MVC elements generic enough to be carried across to a new flavor -- internally, leaving a consistent and ability-independent external interface intact.
If you didn't do this, then when your new flavor comes along, all your hard references to view properties in the (potentially reusable/refactorable/extendable) controllers have to be mucked with.
This is not to mean that such generic setters and cmds have to be the interface for all your views abilities, but rather they should handle 'edge case' properties as well as the normal props/cmds you can expose in the traditional hard-link way. Think of it as an 'extended properties' handler.
That way, (contrived again), suppose you are building on a framework where your buttons no longer have buttonIcon property. Thats cool because you had the foresight to create a button view interface where buttonIcon is an extended property, and inside the view your conditional code does a no-op now when it receives the set/get.
In summary, I am trying to say that the coding goals of MVC should be to give the Model and View generic interfaces to their underlying components, so when you are coding a Controller you don't have to think to hard about who you are controlling. And while the Controllers are being (seemingly unfairly) set up to be the sacrificial lamb in the long run of re-usability -- this does not mean ALL your controllers are destined for death.
They are hopefully small, since a lot of their 'thinking' has been shoved off into semi-intelligent Models and Views and other controllers (ex: Controller to Sort a Grid or Manipulate a TreeView) -- so being small they can be easily looked at and qualified for reuse in your next project -- or cloned and tweaked to become suitable.
It actually reduces complexity by separating the workflow logic from the domain logic. It also makes it easier to write unit tests and makes your application easier to maintain and extend.
Imagine if you wanted to add a new data type. With the approach above, you would probably duplicate a lot of the workflow logic in the new class as it would be likely to be tightly coupled to the domain logic.
The discipline involved in separating the workflow logic into the controller makes it more likely that you will have fewer dependencies between workflow and domain logic. Adding a new data type would then be more simple, you create the new domain object and see how much of the controller you can reuse, e.g. by inherited from a controller super class.
It would also make it easier to change frameworks in future - the model would probably not change too much and so would be more portable.
Having said that, you might want to look into MVVM depending on what you are using as your presentation layer: Benefits of MVVM over MVC
Advantages of MVC/P (I am talking about Supervising Controller here) over MV include:
You can handle complex data binding code in the controller, if required.
You can test that complex presentation logic without a UI testing framework.
You can also have a graphic designer make your views, and not see your code, and not mess up your code when they fix your views.

ASP MVC Ajax Controller pattern?

My MVC app tends to have a lot of ajax calls (via JQuery.get()). It's sort of bugging me that my controller is littered with many tiny methods that get called via ajax. It seems to me to be sort of breaking the MVC pattern a bit--the controller is now being more of a data access component then a URI router.
I refactored so that I have my 'true' controller for a page just performing standard routing responses (returing ActionResponse objects). So a call to /home/ will obviously kick up the HomeController class that will respond in the canonical controller fashion by returning a plain-jane View.
I then moved my ajax stuff into a new controller class whose name I'm prefacing with 'Ajax'. So, for example, my page might have three different sections of functionality (say shopping cart or user account). I have an ajax controller for each of these (AjaxCartController, AjaxAccountController). There is really nothing different about moving the ajax call stuff into its own controller class--it's just to keep things cleaner. on client side obviously the JQuery would then use this new controller thusly:
//jquery pseudocode call to specific controller that just handles ajax calls
$.get('AjaxAccount/Details'....
(1) is there a better pattern in MVC for responding to ajax calls?
(2) It seems to me that the MVC model is a bit leaky when it comes to ajax--it's not really 'controlling' stuff. It just happens to be the best and least painful way of handling ajax calls (or am I ignorant)?
In other words, the 'Controller' abstraction doesn't seem to play nice with Ajax (at least from a patterns perspective). Is there something I'm missing?
While you might put Controller on the end of it to make ASP.NET MVC's routing magic work, I tend to do what you've already done--except when I read AjaxCartController I think to myself AjaxCartPresenter (as in the Model-View-Presenter pattern commonly seen in WinForms). That is, this "controller" is not controlling but instead unashamedly tied to the view interface. But, unlike the view, the controller presenter is testable.
When we AJAXify a Web page, we're turning it into something that can react in a fine-grained manner, so fine-grained methods are okay. Fined-grainedness is the point and the whole reason it was invented. We are deliberately walking away from REST for a particular scenario because that particular pattern is not solving the UI requirement at hand, instead choosing an RPC-like model. They are just patterns, one is not going to be better than the other in all situations, even if our technology stack might be pushing us toward one over the other. (Indeed, HTTP itself does better in chunks/pages/entities/representational state transfer documents.)
Mentally, you can treat these pages as if they were forms in a WinForms application; the fact that these methods sit in a "controller" is just an artifact of and concession toward the technology being used. (If it super-duper bothers you, you could roll the AJAX methods into an IHttpHandler and bypass MVC entirely, but why throw away the automatic routing/instantiation/method lookup and make it difficult for yourself? It would be architecturally 'clean' and pure but of dubious benefit.)
... at least, that's how I rationalize it to myself =)
If you have too many fine-grained requests, you might want to have one Controller Action method to service all the calls. You might use a 'switch' in the method to determine the call type and service it accordingly instead of having a zillion tiny methods. You might even use explicit string constants instead of numbers for the switch variable.

Resources