Utilities Backbone.js

I am currently considering Backbone as a way to organize our javascript files and create a clean structure for our code.

My main question is the Best Practice question.

The library works fine, and I successfully configured my structure using AMD and requirejs. My question is related to several utility files that I run. Get data from an XML document and convert it to a json data object (so that data can be localized). Another utility downloads and connects to Facebook. I created both of them as "Models".

Perhaps these models should probably be “Controllers,” because they connect to services, but they need to be called without having to go to the hash file in the file of the router (or controller).

Should I distribute a base group model for these two utility files, or is there something else I should do to implement utility files like this?

+6
source share
2 answers

There is nothing objective misuse of Backbone.Model for this purpose, but no matter what it seems suspicious. The model comes with extra baggage, which does not belong to the class of type “service” or “utility”.

Instead, I defined a more general, evented base class for functionality that does not quite match the Backbone Model-View-Collection-Router paradigm.

 define(['backbone', 'underscore'], function(Backbone, _) { var Class = function() { this.initialize.apply(this, arguments); }; //give Class events and a default constructor _.extend(Class.prototype, Backbone.Events, {initialize: function() {}}); //copy the extend feature from one of the backbone classes Class.extend = Backbone.Model.extend; return Class; }); 

The class behaves like other Backbone objects, since it can be extend ed, its instances have an initialize constructor and support events. One of your examples, a localization service, might look something like this:

 var LocalizationService = Class.extend({ initialize: function(url) { this.url = url; this.fetch(); }, fetch: function({ var self = this; $.ajax({ url:this.url, success: function(response) { self.response = response; self.trigger('fetch:complete', self, response); //etc... } }); } }); 
+6
source

There is a free help system backbone.js "Developing Backbone.js applications" by Addie Osmani: http://addyosmani.github.com/backbone-fundamentals/

At the very beginning there is a chapter on MVC and MV * .

Later there is also a chapter on requirements and AMD

+1
source

All Articles