gpt4 book ai didi

javascript - Backbone : Reference events to parent object

转载 作者:行者123 更新时间:2023-11-29 20:05:26 24 4
gpt4 key购买 nike

我想用我的父对象之一替换某个子对象的 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');
}

正如您所见,我们现在有了某种一对多的事件系统。一个监听器和多个可以触发事件的对象。

当我使用不同的 Backbone.CollectionsBackbone.Models 时,这对我有帮助,它们与前端有相同的 View 系统。

如您所见,解决方案还不是最优的。

是否有更短的方法来覆盖事件系统?

更新:所以我研究了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com