Inside a Backbone
object (model,view,router), we can call this.listenTo
like so
var BodyView = Backbone.View.extend({
initialize: function() {
this.listenTo(Backbone, 'prevent-scroll', this.preventScroll);
},
preventScroll: function(prevent) {
// .prevent-scroll has the following CSS rule: overflow: hidden;
this.$el.toggleClass('prevent-scroll', prevent);
}
});
// And now from anywhere in the code:
Backbone.trigger('prevent-scroll', true); // prevent scrolling
however, is there a way to use
Backbone.listenTo
, instead of this.listenTo
? I don't see any examples of this online, but I don't see why it shouldn't exist.
Also, one more question in the call
Backbone.trigger('prevent-scroll', true);
where is the true
argument being passed to? I don't get it
I was looking at the annotated Backbone source. http://backbonejs.org/docs/backbone.html#section-19
There is a clear way to do this. The naive standpoint is that you should be able to pass around messages on the front-end wherever Backbone is, not just wherever Backbone.Views, Backbone.Models, etc, are.
If you put this on your front-end, it will work:
Backbone.Events.on('event1',function(msg){
alert(msg);
});
Backbone.Events.trigger('event1','hiiii');
Not only that, you can also simply do:
Backbone.on('event1',function(msg){
alert(msg);
});
Backbone.trigger('event1','hiiii');
this is because of this call in the Backbone source:
_.extend(Backbone, Events);
Backbone.Events
is:
a module that can be mixed in to any object in order to provide it with custom events. You may bind with on or remove with off callback functions to an event; trigger-ing an event fires all callbacks in succession.
for example:
var object = {};
_.extend(object, Backbone.Events);
object.on('expand', function(){ alert('expanded'); });
object.trigger('expand');