我有一个 SVG Canvas ,其中包含我想要响应点击的文本。下面的代码没有完成工作:
var MyView = Backbone.View.extend({
tagName : "text",
events : {
"click" : "clickhandler"
},
initialize : function() {
this.centerX = this.options.centerX;
this.centerY = this.options.centerY;
this.svg = this.options.svg;
this.tagText = this.model.get("tag_name");
this.render();
},
clickhandler : function(event) {
console.log("I was clicked!"); //This is not firing on click
},
render : function() {
this.el = this.svg.text(this.centerX, this.centerY, this.tagText, {});
return this;
}
});
这在另一个 View 的渲染函数中被调用,如下所示:
container.svg({
onLoad : function(svg) {
for ( var i = 1; i < that.relatedTags.length; i++) {
tagView = new MyView({
model : this.relatedTags.at(i),
centerX : 100,
centerY : 200,
svg : svg
});
}
container.append(tagView);
}
});
它显示得很好,如果我把它放在 for 循环的末尾:
$(tagView.el).click(function() {
alert("xx");
});
然后单击可以工作,但我需要访问与 View 关联的主干模型,因此我更喜欢主干事件而不是直接的 JQuery 事件。
最佳答案
这里的问题是,您在渲染方法中设置了 View 的元素。但主干尝试在初始化时添加事件。因此,当主干尝试添加事件时,您的案例中没有元素。因此,您要么必须使用 svg 文本启动 View ,要么在渲染方法中手动添加事件。
也许你可以在 svg 本身上添加事件,jquery 足够聪明来处理委托(delegate)。但在这种情况下我不确定。
关于svg - 应用于作为 svg 元素的 el 的主干事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8482574/