I am currently looking at Backbone as a way to organise our javascript files and create a clean structure for our code.
My question is mainly a "Best Practice" question.
The library works great and I have successfully setup my structure with AMD and requirejs. My question relates to a couple of utility files that I am running. One gets data from an XML document and converts it to a json data object (so data can be localised). The other is a utility that loads and connects to Facebook. I have created both of these as 'Models'.
Arguably these models should probably be "Controllers" as they connect to services but these need to be called without the need to browse to a hashbang in a router (or controller) file.
Should I be extending backbones model for these two utility files or is there something else I should be doing to implement utility files like this ?
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
There is only method named "start" can be used to manipulate the Backbone. js history.
Vue. js, React, AngularJS, Angular 2, and Ember. js are the most popular alternatives and competitors to Backbone. js.
There's nothing objectively wrong with using Backbone.Model
s for this purpose, but regardless it feels fishy. Model comes with extra baggage which doesn't belong in a "service" or "utility" type class.
Instead I've defined a more generic, evented base class for functionality that doesn't quite fit 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, in that it can be extend
ed, its instances have a initialize
constructor method and they support events. One of your examples, the localization service, could look something like:
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...
}
});
}
});
There is a free backbone.js ebook "Developing Backbone.js Applications" by Addy Osmani: http://addyosmani.github.com/backbone-fundamentals/
Right in the beginning there is a chapter about MVC and MV*.
Later on there is also a chapter about requirejs and AMD
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