Backbone.listenTo与this.listenTo [英] Backbone.listenTo vs this.listenTo
问题描述
在Backbone
对象(模型,视图,路由器)内部,我们可以调用this.listenTo
Inside a Backbone
object (model,view,router), we can call this.listenTo
像这样
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
,而不是this.listenTo
?我没有在网上看到任何此示例,但我看不到为什么它不应该存在.
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);
true
参数传递到哪里?我不明白
where is the true
argument being passed to? I don't get it
推荐答案
我正在查看带注释的Backbone源. http://backbonejs.org/docs/backbone.html#section-19
I was looking at the annotated Backbone source. http://backbonejs.org/docs/backbone.html#section-19
有一个明确的方法可以做到这一点. 天真的观点是,无论Backbone在哪里,您都应该能够在前端传递消息,而不仅仅是Backbone.Views,Backbone.Models等在哪里.
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
是:
可以混入任何对象以提供它的模块 与自定义事件.您可以使用on回调绑定或使用off回调删除 事件的功能;触发事件会触发所有回调 继承.
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.
例如:
var object = {};
_.extend(object, Backbone.Events);
object.on('expand', function(){ alert('expanded'); });
object.trigger('expand');
这篇关于Backbone.listenTo与this.listenTo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!