Backbone.js: Get collection on which event occurred inside callback - backbone.js

I have multiple collections bound to the same callback. I need a way identify the collection on which the event actually occurred. But, I can't pass arguments to the callback in backbone.js. Is there a way out?

In Backbone collection event handlers this is always set to the collection on which the event was triggered:
function eventHandler(){
console.log(this); // this refers to either collection1 or collection2, depending on where the event was triggered
};
collection1.on("sth", eventHandler);
collection2.on("sth", eventHandler);

Related

Backbone.js | What is the argument passed to any Backbone.js event callback?

When I tap on a button, I call the changeProfil method:
'tap div:first-of-type button:first-of-type': 'changeProfil'
I want to know what is the argument passed to this function. I tried:
changerProfil: function(e) {
alert(JSON.stringify(e))
}
But I get this error: "json.stringify cannot serialize cyclic structures"
Also, I can not do console.log. How can I know what is the argument passed?
Backbone views use delegateEvents to bind the events and that
Uses jQuery's on function to provide declarative callbacks for DOM events within a view.
jQuery's on passes a normalized event object to the event handlers:
jQuery’s event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from the original event are copied over and normalized to the new event object.
JSON.stringify can't serialize arbitrary objects so don't use that, just say console.log(e) or even console.log(arguments) to see what you're getting passed.

Should all Backbone on/off events be replaced with listenTo/stopListening?

As far as I have been able to tell, listenTo and stopListening should replace on and off respectively. Do I understand that correctly? Is there any situation where on/off should be used instead of listenTo/stopListening?
Edit:
As I went to refactor my code, it became obvious that there are some cases for on over listenTo. The documentation is pretty clear that it is for when one object listens to another object:
Tell an object to listen to a particular event on an other object.
Therefore, when a collection or model is listening to an event on itself, we should use on instead of listenTo.
Assuming I have this correct...
The simple rule to follow is this:
Use listenTo when listening for events on another object. Use on when listening to events on self.
Copying an extract from an interesting blog post that I read recently. Hope it helps.
Avoiding common backbone pitfalls: Creating memory leaks by not unbinding events
A common pattern in Backbone.js is creating views that listen on changes in models or collections. This technique is usually intended to allow the view to automatically re-render itself when the underlying data changes. It also means that for large collections we may end up with many views (at least one for every model in the collection) that we may dynamically create or destroy based on changes to the data.
The problem arises when we remove a view (usually by calling its .remove() method), but forgetting to unbind the methods that listen on model changes. In such a case, even though our code may no longer hold a reference to that view, it is never garbage collected since the model still holds such a reference via the event handler.
Take this view for example:
var SomeModelView = Backbone.View.extend({
initialize: function() {
this.model.on('change', this.render, this);
},
render: function() {
// render a template
}
});
When calling the .remove() method, the "change" event handler (our render function) is still bound. So while the DOM element may be removed, the view object itself is never released from memory.
Solving this is easy (especially since Backbone 0.9.x) - all we need to do is to stop using .on() when binding the event handler. instead, we can use the new .listenTo() method, like this:
initialize: function() {
this.listenTo(this.model, 'change', this.render);
}
The biggest difference here being the shift in responsibility from the model to the view. This means that whenever we call .remove(), the view will automatically unbind any event bound to it using the .listenTo() method, essentially fixing this common leak.
For the most part, you understand it correctly. Here is a discussion on the matter from their github repository: https://github.com/documentcloud/backbone/issues/1923#issuecomment-11462852
listenTo and stopListening keep track of state. It will take care of cleanup for you at the cost of a little code overhead. In just about every case I can think of you'd want this behavior for your views, but you wouldn't be at fault for handling on/off calls yourself either; they won't be deprecating on and off any time soon.

Don't call render() if the View itself updated Model via Backbone.Model.set()

In my Backbone.js project I have one Model and several Views. All Views have registered callbacks for 'change:currentTextTitle' on this model:
// 'this' stands for any of the Views here
myModel.on('change:currentTextTitle', this.render, this);
Now a user performs some action, which causes the specific View to change its "current text title" field. This specific view then calls myModel.set("currentTextField", newTextValue) which in turn triggers the 'change:currentTextTitle' event calling all Views (including the one from which set() originated). Then all Views call their render callback functions.
The problem is that the render method is also called on the View from which the set()-Method was originally called, which is completely unnecessary because it is already up-to-date with currentTextTitle.
How would my Views call myModel.set() in a way that the other Views' callbacks get informed, but without triggering/calling the "source View" itself?
One workaround seems to be to pass the source view as part of the options parameter of the set() method (which gets passed along to trigger() and then along the the render() callback):
myModel.set("currentTextField", newTextValue, thisViewSetAttribute)
Then in the render callback one could check if thisViewSetAttribute != this. However, instead of implementing checks in every callback, I think it would make more sense to handle this in the Model itself by only calling the necessary callbacks and ignoring the source View from which the set() method call originated. Is this possible?
I think the 'proper' MCV solution is that your views should not know or care how the model changed, they should simply handle the change and update accordingly. If they are already current, the user shouldn't know the difference.
I definitely would not pass the source view to the model. Instead when the model changes, you could just have the view check if it is current and not re-render. But if the extra render doesn't cause any issues then just let it happen :)
In Backbone, the 'view' is both view and controller. So try to treat the change as 2 separate steps. First, convert user input into changes on the model, then as a separate step (initiated by model change event), handle that change and update the view. If each view does this, no matter how the model changes, everything will stay up-to-date.

when the add event is fired in backbonejs?

When does the 'add' event gets fired in a collection?
I am in a notion that when i execute something like app.mycollection.create(this.newAttributes()); the add event will be fired.
Actually i do this while initializing a view
window.app.mycollection.on('add',this.render,this)
So ideally, first there should be a post request (when i do a create) and then the get request (my render function fetches rows from backend). But in network console, i get the opposite. I first see a get request and then the post request.
This made me thought that 'add' event gets fired immediately after a call to create method without waiting for creation to be complete.
This thus fetches me old data without including the data that has just been created.
Please shed some light.
You have executed render function immediately. Try update your code:
window.app.mycollection.on('add', this.render, this)
EDIT
Take a look
Creating a model will cause an immediate "add" event to be triggered
on the collection, a "request" event as the new model is sent to the
server, as well as a "sync" event, once the server has responded with
the successful creation of the model. Pass {wait: true} if you'd like
to wait for the server before adding the new model to the collection.

Backbone "success" callback vs. model "change" event binding purposes

What is the purpose of the "success" callback when fetching data for a model vs. the purpose of binding to a method for the "change" event?
"success" callback
this.model.fetch({
url: '...'.
success: function(response) {
...
}
});
vs. model "change" binding
this.model.bind("change", this.attributesChanged);
Usually i use fetch-success callback in cases when i call fetch outside of the model itself and want an additional success function callback triggered in the model.
Also on a note, be careful with CRUD events though, as "change" events may still be trigger even when its unsuccessful in storing to the server, remember "change" is triggered when the model is changed. As of version 0.9.0, a "sync" event has been added to address this issue. This triggers whenever a model's state has been successfully synced with the server.
The main reason to use "success" or "error" for that matter, is to execute functionality based upon the response as "change" will only fire on successful change of the model. If your fetch failed for some reason, "change" won't fire. The callbacks allow you a bit finer level of control. That said, it kind of boils down to personal preference as to when you want to respond to the response. My thought is that if I am only interested in doing something in response to a successful CRUD operation, then listening for "change" is entirely appropriate, as I will just ignore errors.
The 'change' event will fire if the model is updated by any method, for example user input into a form which is used to change a model attribute, or fetching data from the server.
The success callback on fetch is obviously called only after fetching from the server.
So if you only want to respond to changes to the model caused by fetches, rather than 'bidirectional' changes, use a success handler rather than a change event.

Resources