Debugging Backbone.js: rendering after collection fetch() - backbone.js

I'm trying to do basic render() after fetch() on collection (Backbone 0.9.2):
var ProjectListView = Backbone.View.extend({
el: $('#container'),
initialize: function () {
this.collection = new ProjectsCollection();
this.collection.bind("change", _.bind(this.render, this));
this.collection.fetch({ success: function () { console.log("collection fetched"); } });
...
},
render: function () {
console.log("rendered");
...
Creating new View instance prints out:
collection fetched
So the render() never gets called after fetch(). What am I doing wrong here? There are no exceptions present.
Any tips how to debug these sort of things in backbone?
Ps.
It seems that this feature is poorly documented given the number of questions on SO.

From the fine manual:
fetch collection.fetch([options])
Fetch the default set of models for this collection from the server, resetting the collection when they arrive. [...] When the model data returns from the server, the collection will reset.
And what does reset do? reset does this:
reset collection.reset(models, [options])
[...] Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end.
So fetch calls reset to update the collection's models and reset triggers a "reset" event, not a "change" event. None of the models have changed and a collection's "change" events come from its models.
You should have render bound to "reset":
initialize: function () {
this.collection = new ProjectsCollection();
this.collection.bind("reset", _.bind(this.render, this));
this.collection.fetch(...);
}
If you want to listen for "change" events on the contained models then you can bind a "change" handler to the collection since:
You can bind "change" events to be notified when any model in the collection has been modified,
[...]
Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience.
The collection will also generate "add" and "remove" events as the collection itself changes.
Newer versions of Backbone no longer reset collections during fetch:
When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, in which case the collection will be (efficiently) reset.
And set:
[...] performs a "smart" update of the collection with the passed list of models. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as this happens
So with newer versions of Backbone you'll want to list for the "add", "remove", and "change" events (which a collection based view should be listening for anyway); you could also use {reset: true} on the initial fetch and listen to "reset" as well. I'd recommend the following approach for collection based views:
Listen to "add" and handle that event with a callback that simply adds one item to the view, don't throw everything away and re-render.
Listen to "remvoe" and handle that event with a callback that only removes the newly removed model.
Listen to "change" and handle that with a callback that replaces (or updates) the appropriate item.
Listen to "reset" and bind that to render. Then pass {reset: true} to the collection's initial fetch call.
That will trap the important events and the collection-view will do the minimal amount of work to handle each one. Of course, this strategy isn't applicable to all situations but I think it is a good starting point.

This changed in 1.0
http://backbonejs.org/#changelog
"If you'd like to continue using "reset", pass {reset: true}."

Ok, so until some one can explain why binding didn't work, I used following workaround:
initialize: function () {
var self = this;
this.collection = new ProjectsCollection();
this.collection.fetch({ success: function () { self.render(); } });

Related

How to determine why the remove event of backbone collection is triggered?

Remove event on backbone collection is triggered when the model has been removed from the collection.
But I need to differentiate whether destroying the model triggers the remove event on collection or just removing the model from collection triggers the remove event on collection.
There's no easy way to differentiate those two cases. My recommendation would be to override the remove method yourself and have it trigger your own event(s):
var YourCollection = Backbone.Collection.extend({
remove: {
this.trigger('aboutToRemovedViaRemoveMethod');
// Call the original remove
var removeResult = Backbone.Collection.prototype.remove.apply(this, arguments);
this.trigger('removedViaRemoveMethod');
return removeResult;
}
});
And then of course destroy you can already listen for separately, as it has its own event.

View event reflected in collection convention

What is the best way to remove a model from a collection that has been removed in the DOM. Let me ask a better question, how do I keep views in sync with a collection?
remove the view first, while removing execute
this.model.collection.remove(this.model);
you can check with conditions to whether current view has a model, and that model has a collection etc before you execute the same.
I've followed the backbone Todos example application. This keeps view state up to date with collection.
Pass models to any view created like so:
var someView = new SomeItemView({ model: modelFromCollection });
Then listen to events on that model and react from the view:
initialize: function() {
this.listenTo(this.model, 'destroy', this.remove);
// listen to other events ...
}

Collection create function firing add event too quickly

(Using Backbone 0.9.10)
I have a list view of sorts where the user can click a button to show a modal view. The list view has a counter that shows the amount of items contained in the list. Clicking a button in the modal view executes create on a collection that is passed into both views. This fires the add event in the list view, which in turn runs this function:
renderCount: function () {
// Container for model count
var $num = this.$el.find('.num');
if ($num.length > 0) {
// 'count' is a value returned from a service that
// always contains the total amount of models in the
// collection. This is necessary as I use a form of
// pagination. It's essentially the same as
// this.collection.length had it returned all models
// at once.
$num.html(this.collection.count);
}
}
However, add seems to be fired immediately (as it should be, according to the docs), before the collection has a chance to update the model count. I looked into sync but it didn't seem to do much of anything.
How can I make sure the collection is updated before calling renderCount?
Here's the list view initialize function, for reference:
initialize: function (options) {
this.collection = options.collection;
this.listenTo(this.collection, 'add remove reset', this.renderCount);
this.render();
}
EDIT:
Turns out I was forgetting to refetch the collection on success in the modal view.
$num.html(this.collection.count);
shoule be:
$num.html(this.collection.size());
Backbone.Collection uses methods imported from underscore, here is list: http://backbonejs.org/#Collection-Underscore-Methods
Turns out I was forgetting to refetch the collection on success in the modal view.

Using Remove event to detect the model removed from the collection in Backbone.js

My question is , is there a way to detect the model that got removed from the collection when we bind/listen to the collection's add Event.
for ex:
this.listenTo(monthsOnBoardCollection, "remove", function(){
//is it possible here to find what got removed from the collection ?
}
You have the Catalog of Events which shows the arguments being passes to the event.
"remove" (model, collection, options) — when a model is removed from a collection.
So it's basically:
this.listenTo(monthsOnBoardCollection, "remove", function(model, collection, options){
//now you have the model, the collection and the options which were passed to the remove method
}

How can I get a list of models from the collection that have changes since constuction

If I initialize a collection with an array of objects for the model attributes when a dialogview is initialized. Then the dialog view that lets the user edit the list updates those model values with calls to model set. When the dialog's ok button is clicked, Does backbone provide a way to get the list of only those models that changed since the collection was created/initialized?
There are various model methods that look tempting:
Model#hasChanged
Model#changedAttributes
Model#previous
Model#previousAttributes
But don't be fooled, those only apply while a "change" event is being triggered:
Note that this method, and the following change-related ones, are only useful during the course of a "change" event.
so they're useless after the event has been triggered and handled.
I think you have to track which models have changed yourself. You can do this on the collection itself without too much effort since
Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience.
and the collection can bind to its own events. For example, you could have something like this in your collection:
Backbone.Collection.extend({
initialize: function() {
this.delta = { };
this.on('change',​​​​​ this._a_model_has_changed);
},
changed_models: function() {
return _.chain(this.delta).values();
},
_a_model_has_changed: function(m) {
this.delta[m.id] = m;
}
});
Then you could get the models that have changed by calling collection.changed_models(). You'd want to listen for other events as well so that you could update this.delta when models are deleted or synced with the server; the above is just for illustration. If you didn't want an Underscore object returned you could use this instead:
changed_models: function() {
return _(this.delta).values();
}
but being able to collection.changed_models().each(function() { ... }) is convenient.
Demo: http://jsfiddle.net/ambiguous/8PQh9/
You could also let the models track their own dirtiness through a similar set on the models. Then you could do something like this:
collection.filter(function(m) { return m.is_dirty() });
where, of course, is_dirty would return true if the model had been changed.

Resources