应用于svg元素的el的主干事件



我有一个带有文本的SVG画布,我想对点击做出响应。下面的代码不能完成工作:

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;
}
});

这是在另一个视图的渲染函数中被调用的:

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");
});

然后点击工作,但我需要访问与视图关联的骨干模型,所以我更喜欢骨干事件,而不是一个直接的JQuery事件。

这里的问题是,您在呈现方法中设置了视图的元素。但是backbone尝试在初始化时添加事件。因此,当骨干试图添加事件时,在您的情况下没有元素。因此,要么你必须用svg文本开始你的视图,要么你在渲染方法中手动添加事件。

也许你可以在svg本身上添加事件,jquery足够聪明来处理委托。但我不确定在这种情况下。

最新更新