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

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.

Related

Prevent itemView from being added to CompositeView after collection "add"

I have a problem with Backbone and Marionette. I have a CompositeView with a collection where people can a comment, this all works nicely, the comment is added and saved to the server but I don't want the view to update and to show the newly added comment. I have tried this:
App.Views.CommentsView = Backbone.Marionette.CompositeView.extend({
template: '#article-comment-container',
itemViewContainer: 'ul',
itemView: App.Views.CommentView,
collectionEvents: {
"add": "modelAdded"
},
modelAdded: function(){
console.log('Please do nothing!');
}
});
But the item is still rendered into the page on top of my modelAdded function being called. Can I prevent that from happening at some point?
In a different scenario I would like new items to be added to the top of the list and not the bottom. Do I have to override the entire appendHtml method achieve this?
Setting the collection event add simply adds another handler to the queue for that event; it doesn't replace any other events so the default marionette behaviour will still occur.
I assume you're calling the create method on the collection to create your new comment model. If this is the case you simply need to set the silent option to true. Now the add event will not fire and Marionette will not create and render the view for that model. You can do it like this:
commentCollection.create(commentModel, {silent: true});
As for you second question about prepending, yes I would override appendHtml method. Or to keep the method names consistent with what actually happens, create a method called prependHtml and then override the renderItemView method to call prependHtml.

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 ...
}

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
}

Debugging Backbone.js: rendering after collection fetch()

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(); } });

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