gpt4 book ai didi

javascript - 为继承的 Backbone.js View 覆盖事件哈希

转载 作者:搜寻专家 更新时间:2023-11-01 04:55:17 25 4
gpt4 key购买 nike

我有一个通用元素的主干 View ,特定元素将从中继承。我有需要应用于所有元素的事件处理逻辑,以及特定于子类型元素的事件处理逻辑。我遇到了麻烦,因为 subview 有自己的事件回调,该事件也由父 View 处理,因此当我尝试在两者中使用事件哈希时, subview 或父回调都不会被调用。让我用一些代码来说明:

var ElementView = Backbone.View.extend({
events: {
"mouseup": "upHandler",
"mousedown": "downHandler",
"mousemove": "moveHandler"
},

initialize: function() {
// add events from child
if (this.events)
this.events = _.defaults(this.events, ElementView.prototype.events);

this.delegateEvents(this.events);
}
});

var StrokeView = ElementView.extend({
events: {
"mousemove": "strokeMoveHandler"
}
});

我如何以可扩展的方式解决这个问题,特别是如果我以后会有另一层继承?

最佳答案

处理此问题的一种方法是为事件使用“命名空间”:

var ElementView = Backbone.View.extend({
events: {
"mouseup.element": "upHandler",
"mousedown.element": "downHandler",
"mousemove.element": "moveHandler"
},

initialize: function() {
// add events from child
if (this.events)
this.events = _.defaults(this.events, ElementView.prototype.events);

this.delegateEvents(this.events);
}
});

var StrokeView = ElementView.extend({
events: {
"mousemove.strokeview": "strokeMoveHandler"
}
});

其实这种做法就是suggested in Backbone.js documentation .

关于javascript - 为继承的 Backbone.js View 覆盖事件哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9012829/

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