2

我有一个带有文本的 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 事件。

4

1 回答 1

3

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

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

于 2011-12-16T19:50:27.610 回答