Why do BackboneJs Collections have URL's? - backbone.js

I'm starting to use backbone.js and I'm confused as to why you can specify url's in a bunch of different ways. It doesn't seem like the collection url is used anywhere except in the model url function. So is there any harm in just setting urlroot on all of my models and never using collection urls?

there is no harm at all, you can work perfectly fine at the model level doing updates, deletes etc, but when you want to GET a set of models from the server all at once it comes handy to do something like this.
Books = Backbone.Collection.extend({
url : "/books"
});
books = new Books();
books.fetch(); // this will line will make a GET request to your backend, the result will
// be a list of models.

In Backbone.js, Models and Collections are related to 'structuring' data, and Backbone provide methods for doing this. With Restful routes, you most often need updates/fetches like this:
GET /students
[{name: "...", ...}]
GET /students/1
{name: "..."}
As you observed, the URLs are similar, but in most cases processing the response of a Collection and Model fetch, will look different. Since conceptually, Models are part of a Collection, Model URLs can in most cases be resolved from the collection. There are other APIs where models and collection don't match, and you need to set the URLs yourself (e.g. a session model, that does not belong to a collection)
Maybe it also helps to compare the documentation for the Model and Collection fetch:
http://backbonejs.org/#Collection-fetch
http://backbonejs.org/#Model-fetch
This might also help to understand the Backbone way of thinking: http://jonathanotto.com/blog/backbone_js_for_the_everyman.html

Related

backbone js using multiple collection in view

I am quite new in backbone js . I was reading the documentation of backbone and I come up with this idea to use multiple collection in view.
If I have single view and I want to use more than one collection how can I achieve it?
how can the view understand multiple collection?
thanks.
Why do you ever need to use multiple collection inside a single view? Backbone's strength is it's modularity, which means you can develop the whole structure of your application by building it's components piece-by-piece. So in normal circumstances one view has one model or collection of models, but it's acceptable and it's often used the case when a collection has multiple views (for example a chat system).
To have multiple collections inside a single view is against backbone's modularity principle. Breaking up views to respond to only one model/collection turns out much more modular and reusable code.
So i suggest to break up your application into smaller pieces and operate on segment level, but if you really need to preserve the current structure you can do something like this:
var view = new MyView({
collection: {
users: new UsersCollection(),
organization: new OrganizationCollection()
}
});

Backbone.Marionette / progressive model loading strategy

I'm working on an analytics-like dashboard with heavy data. Obviously waiting for all this data to come in isn't a good idea as it would increase load-times beyond acceptable lengths. My idea is to progressively add parts of data when certain Controllers instantiate a model. I imagine it'll end up looking something like this:
class List.Controller extends Marionette.Controller
initialize: (options) ->
{ model } = options
model.fetch( something here ) unless model.get('data')
#showData model
getDataView: (model) ->
new List.Data {model}
showData: (model) ->
dataView = #getDataView model
App.mainRegion.show dataView
I was wondering if someone has experience with this, and what a good strategy would be for what to pass into the fetch call and how to structure that...
Edit: to clarify, I'm looking for a scalable strategy to load more data for a model based on a get-param or a different endpoint when my app needs it. Should this be handled by methods on my model or by passing stuff into fetch for example?
The "standard" way is having a pageable collection, such as Backbone Pageable
Then you can have a CollectionView or CompositeView which will handle most of the work for you.

What's the best practice for handling loading child resources in ngResource?

Context: I'm new to Angular, and this feels like a lot more of a "What's the right way to do this in AngularJS" kind of question.
My API backend has a couple of related objects that I need to request and assemble into a coherent user interface. It can be modeled as a subscription hub thing, so I have: Subscription hasMany Subscription_Items, belongsTo Source.
What I want to do is look up a user's Subscriptions (/api/subscriptions?user_id=1), which gives me some JSON that includes a subscription_item_ids=[1,2,3 ...] array. I then want to query on those ids, as well as query the server on source_id to pull shared info, and then repackage everything nicely into the $scope so the view layer has easy access to the system and can do stuff like ng-repeat="item in subscription.subscription_items" inside an outer ng-repeat="subscription in subscriptions".
Conceptually this makes sense, and I've thought of a few ways to load this linked data, but what I'm curious about is: what's the best practice here? I don't want to excessively reload the data, so it seems like a plain old function that does a REST request every time I look at an item is a bad idea, but at the same time, I don't want to just push the data in once and then miss out on updates to items.
So, the question is: what's the best way to handle linked resources like this, to trace hasMany and belongsTo types of connections out to other models in a way that aligns with the ideas embedded in $scope and the $apply cycle?
I like to use a lazy-loaded dataModel service which will cache results and return promises. The interface looks like this:
dataModel.getInstitution(institutionId).then(manageTheInstitution);
If I need something that is a child, I call it like this:
dataModel.getStudents(institutionId).then(manageStudents);
Internally, getStudents looks something like this:
function getStudents(institnutionId) {
var deferred = $q.defer();
getInstitnution(institutionId).then(function(institution) {
institution.students = Student.query({institutionId: institutionId});
institution.students.$promise.then(function(students) {
deferred.resolve(students);
});
});
return deferred.promise;
}
These functions are a bit more complex. They cache the results and don't request them again if they already exist... and return or chain the existing promise. They also handle errors.
By carefully crafting my dataModel service this way, I can manage any nesting of resources and I can optimize my network requests. I've been very happy with this approach so far.

Collection vs Model confusion in backbone.js

I just started learning backbone.js. I have a problem understanding how/when use models and collections. I found several tutorial online and each of them use different approach of building the application. There are cases where data is retrieved from REST API in a Collection object, in other examples in a Model object? I also noticed in every example json data was in format like
{'id':1, 'name':'some name'}.
My api returns a bit more complex data structure - something like {'message':'response message', 'error':'', 'data': [{list of data objects to be manipulated},{}]}. Is it possible to use such formatted data in backbone.js.
Well, yes, for both of your questions. Typically here is how the Relational database system relates to backbone.js:
Your model is a record from a table of the database.
Your collections are the table itself. So set of models make up the collection.
Views are used to define how your model should look and what it should do. There are views for your models, collections and intermediate data.
Your response if different; hence, you need to parse the data before it is set to the model, collection. Use the parse method and define the data key.

Clear all elements from Backbone Collection and remove them from the associated Lawnchair

I am using Backbone.js, Lawnchair, and backbone.lawnchair.js.
I was wondering what the correct way to "empty" a collection (both from the application and from localStorage) would be?
Currently, I am employing something along these lines:
Favorites.Collection = Backbone.Collection.extend({
model: Favorites.Model,
lawnchair: new Lawnchair({ name: "favorites" }, function(e){}),
empty: function(){
this.lawnchair.nuke();
this.fetch();
}
});
This is essentially destroying the elements in localStorage (lawnchair provides the nuke method) and fetching from localStorage. This seems a bit clunky, and I was wondering if I am thinking about this right - or if there is a better way.
Cheers!
Backbone follows sort of RESTish principles and sadly REST doesn't describe a bulk-delete procedure. Resources can only be deleted one at a time. Typically APIs don't support HTTP DELETE on the entire collection URI like DELETE /favorites, only DELETE /favorites/42 - one at a time. Thus there's no single backbone method that just does this as generally the collection is mostly designed to do fetch/GET and then delegate to the individual models to do saves and deletes. So yes, you're on your own for a bulk-delete approach. You can do something more RPC-like and pass a list of IDs to a delete procedure, but what you have above seems perfectly adequate to me, and yes deleting them all directly and then re-fetching the collection seems also very reasonable to me. So I think you're solution is fine as is, but I'm also curious to see what others suggest.

Resources