[英]Backbone event callback is called when bound, not triggered
I am trying to implement a simple mediator pattern for events, but my event callbacks are being called when I register them with the mediator. 我正在尝试为事件实现一个简单的中介器模式,但是当我在中介器中注册事件回调时,它们会被调用。
The Mediator is simply: 调解员就是:
define(function(require){
'use strict';
var _ = require('underscore');
var Backbone = require('backbone');
return _.extend( Backbone.Events);
});
I have created a simple View with no backing model or template 我创建了一个没有支持模型或模板的简单视图
define(function (require) {
'use strict';
var Backbone = require('backbone');
var mediator = require('mediator');
var Sandbox = Backbone.View.extend({
el: '.sandbox',
initialize: function () {
this.render();
this.bindEvents();
},
bindEvents:function(){
mediator.on("sandbox:change", this.changeText(), this );
},
render: function () {
$(this.el).html("SANDBOX VIEW IS WORKING");
},
changeText: function () {
$(this.el).html("THE TEXT HAS CHANGED");
}
});
return Sandbox;
});
When the view is loaded, the sandbox:change
event is fired off and the changeText function is called even though nothing has called mediator.trigger('sandbox:change')
加载视图时,即使没有调用mediator.trigger('sandbox:change')
也会触发sandbox:change
事件并调用changeText函数。
Why is the callback invoked when it is simply being bound to the mediator object? 为什么仅将回调绑定到中介对象时调用该回调?
When the browser evaluates your sandbox change event binding mediator.on("sandbox:change", this.changeText(), this );
当浏览器评估您的沙箱更改事件绑定mediator.on("sandbox:change", this.changeText(), this );
the changeText function is being executed because the ()
are included. 因为包含()
,所以正在执行changeText函数。 What you really want to do is pass the changeText function object to the event binding: 您真正想要做的是将changeText函数对象传递给事件绑定:
mediator.on("sandbox:change", this.changeText, this );
Remember that changeText, is an object that is a member of your view. 请记住,changeText是一个属于视图成员的对象。
var Sandbox = Backbone.View.extend({
...
changeText: function () {...}
});
When you want to execute the function, use the parenthesis. 要执行该功能时,请使用括号。 When you want to refer to the object, omit the the parenthesis. 当您要引用对象时,请省略括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.