我想用我的父对象之一替换某个子对象中的 Backbone.Events
系统。示例:
// initialize function of the repository object
initialize: function() {
var users = new Backbone.Collection();
// we save a reference of our event system in ourEvents object
var ourEvents = {};
ourEvents.on = this.on;
ourEvents.off = this.off;
ourEvents.trigger = this.trigger;
ourEvents.bind = this.bind;
ourEvents.unbind = this.unbind;
// now we overwrite events in users.collection with our one
_.extend(users, ourEvents);
// now we listen on the test event over this
this.on('test', function() { alert('yiha'); });
// but triggering over users works too!
users.trigger('test');
}
正如您一样,我们现在有了某种一对多事件系统。一个监听器和多个可以触发事件的对象。
当我使用与前端具有相同 View 系统的不同 Backbone.Collections
或 Backbone.Models
时,这对我很有帮助。
如您所见,该解决方案还不是最佳的。
是否有更短的方法来覆盖事件系统?
更新:
所以我研究了Backbone源代码,发现Backbone.Events
在下面保存了一个回调列表:
this._callback
。这至少在理论上应该有效:
this.users._callbacks = this._callbacks = {};
最佳答案
Clean Backbone 的方法是将事件绑定(bind)到集合上,而不是出于某种原因尝试从对象复制它们
// initialize function of the repository object
initialize: function() {
var users = new Backbone.Collection();
users.on('on', this.on, this);
users.on('off', this.off, this); // third parameter to set context of method to the current view
// ...and so on
// you were listening here on the current view but triggering later on collection - this would never work
users.trigger('on'); // would call the this.on method in the context of current view
// if this method would have been triggered from inside of the users collection it would still trigger the desired method inside of this view
}
提示 - 切勿触摸和利用以下划线开头的方法和变量 - 这些是私有(private) API 和属性,并且可能会在下一个版本中随时更改,因为仅保证公共(public)方法/属性不会在版本之间进行更改。我相信你在这里尝试有点过于复杂化,并且看看你所犯的一些错误,你一直在以太多不同的方式尝试有点太努力了:)总是尝试让事情变得简单
关于javascript - Backbone : Reference events to parent object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12130248/