backbone.js scroll event with handler is not unbinding - backbone.js

I've binded window's scroll event to a view's method like:
MyView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'handleScrolling');
$(window).off('scroll', this.handleScrolling).on('scroll', this.handleScrolling);
}
})
I see this is not working. If this callback is triggered as many times as this view is instantiated. However, if I remove handler from off, then it is correctly unbinding and triggers only once per scrolling. Like:
$(window).off('scroll').on('scroll', this.handleScrolling);
Any idea why this is happening? I dont want to remove all callbacks from this event as other views/codes may bind event to it which will make app behaving unexpected.
Is there any better way of binding events to window/document or other element outside the scope of current view?

Your problem is right here:
_.bindAll(this, 'handleScrolling');
That's equivalent to:
this.handleScrolling = _.bind(this.handleScrolling, this);
so each time you instantiate your view, you're working with a brand new function in this.handleScrolling. Then you do this:
$(window).off('scroll', this.handleScrolling)
But that won't do anything since the this.handleScrolling function that you attached with on:
.on('scroll', this.handleScrolling);
isn't the same function as the this.handleScrolling function that you're trying to .off. The result is that each time you create a new instance of your view, you're leaving the old scroll handler in place and adding a new one.
The proper solution (IMO) is to add a remove method to properly clean things up:
remove: function() {
$(window).off('scroll', this.handleScrolling);
return Backbone.View.prototype.remove.apply(this);
}
and then call view.remove() before creating the new view.

It looks like you have a new instance of the handler this.handleScrolling in each call.
so when jQuery tries to remove the specific handler it will not find the handler in the event registry, so it will not be able to remove it.
Problem: Demo
I would suggest using event namespaces here
$(window).off('scroll.myview').on('scroll.myview', this.handleScrolling);
Demo: Fiddle
Another solution is to use a shared handler like this

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.

Backbone select change event not firing

I have a view which defines a change event on some select controls, but they don't seem to be firing. The view is something like this:
var FiltersView = Backbone.Marionette.ItemView.extend({
template: FiltersTmpl,
events: {
'change #panel_filters select': 'enableSearch'
},
enableSearch: function() {
debugger;
}
});
When I change the dropdown, enableSearch doesn't fire. However, using Chrome Dev Tools, I can use jQuery to setup an event handler like this $("#panel_filters select").change(function() { debugger; }); and that does in fact fire. So I know the selector is correct and the select is triggering a change event. I know it must be a simple syntax problem but it seems like the correct syntax to me.
Ok I figured it out. #panel_filters is actually the element that I injected my view into. Technically, it's considered outside the view. And apparently, view events are scoped to the view itself. Which is handy I suppose, but I didn't know that. Good to know :-)

Backbonejs and Custom Model Event

I am trying to create a custom event for my model but apparently the custom event get triggered no matter what unless I use "anonymous" function definition as a callback
Here is the pseudo code of my app structure
//Router
initialize: ->
this.user = new User()
this.view = new View({model:this.user})
this.view.render()
//View
initialize: ->
//This event binding get triggered no matter what
//this.model.on("custom:event", this.triggerMe(), this)
//This works properly. Only triggered when I call model.trigger("custom:event")
this.model.on("custom:event", function(){console.log("I WORK!!");}))
triggerMe: ->
//I GET TRIGGER NO MATTER WHAT
you are invoking a function here:
this.triggerMe()
it should be this.triggerMe
this.model.on("custom:event", this.triggerMe, this)
Adding () or .call() or .apply() is invoking a function not a reference to it.
By passing this.triggerMe() you automatically execute the triggerMe function (because you add parentheses, and by so invocating it).
What you need to do, is to pass a reference to the function. Like so:
this.model.on("custom:event", this.triggerMe, this)

Backbonejs: How to unbind collection bindings when a view is removed?

I've got a backbonejs application with two view. It kind of looks like this:
<body>
<header></header>
<div id="content"></div>
</body>
Every time a view is loaded the app overwrites the current view by completely overwriting the contents of #content.
// Like this...
$('#content').html( new primaryView().render() );
// ...and this.
$('#content').html( new secondaryView().render() );
The application has a global collection.
App.Collection();
The secondary view modifies itself depending on the global collection. Therefor it binds a function to the 'add' event' on App.Collection in the views initialize function;
App.Collection.bind('add', function(){
console.log('Item added');
});
Which result in my problem. Every time the secondary view is loaded a new function is binded to App.Collection's add event. If I go from the primary view to the secondary view three times, the function will fire three times everytime an item is added to App.Collection.
What am I doing wrong?
I can see how I would do it if there was an uninitialize function on views.
I can see how I could do it if I never removed a view once it was loaded.
I can see how I would do it if I could namespace events like in Jquery. (by unbinding before binding).
You can generalize your problem quite a bit. Basically, you are writing an event-driven app, and in such app events should be taken care of.
Check out this post to see a recommended way to work with event handlers in backbone.
Depending on the situation, you can use initialize and render methods to handle different aspects of creating a view. For instance, you can put your binding inside the initialize
initialize: function() {
App.Collection.bind('add', function(){
this.view.render()
});
}
which only fires when the view is created. This binds your render method to the add event. Then in your render method you can actually create the html.
This prevents the binding from happening every time you need to re-render.

Backbone boilerplate Events

What is the best way to bind events to a Backbone boilerplate application? I've been trying to bind my events directly to the models associated with my views, in my views, but it doesn't seem to be working. I see within 'namespace.js', that there is an app key that extends Backbone.Events like so:
// Keep active application instances namespaced under an app object.
app: _.extend({}, Backbone.Events)
I don't fully understand how to use it...
I was able to get things working without the boilerplate, but it does provide some very cool functionality, so I'd love to be able to use it. Thanks!
ADDED
the code I was using was with the underscore bind method like so:
this.module.bind('change', this.render);
But then, I realized that 'this.model' is returning undefined, and so this doesn't work. I really am not sure how the boilerplate wants me to reference my model from the view.
I'm not sure if it is a typo that you copied from your code or a typo you only entered here, but I believe this.module (which IS undefined) should be this.model, which you also must be sure to pass in when you instantiate your view, of course, as so:
myView = new BBView({model: myModel});
then you can say this.model.bind('change', this.render); or this.model.on('change', this.render); for the most recent version of Backbone
I frequently bind my views to change events on my models in this way.
As for extending Backbone.Events, the way I have used it is to create an independent "event aggregator" that will help connect events between different views on your page. Let's say for example you have some action on one view that needs to set off an action on another view. In this case, you can pass your event aggregator object as an option to each of your views when you instantiate them, so that they can both trigger events or bind to events on a common object (i.e. your event aggregator).
whatsUp = _.extend({}, Backbone.Events) // the aggregator
myFirstView = new FirstBBView ({whatsUp: whatsUp});
(the aggregator shows up as this.options.whatsUp inside the view)
mySecondView = new SecondBBView2 ({whatsUp: whatsUp});
inside FirstBBView:
this.options.whatsUp.bind('specialEvent', function(arg1,arg2) {
// do stuff
});
inside SecondBBView, when something important happens:
this.options.whatsUp.trigger('specialEvent', {arg1: 'some data', arg2: 'more data'});
For a great explanation, see this great article by Derick Bailey

Resources