事件没有在backbone.js视图中触发

时间:2013-02-28 19:05:06

标签: javascript backbone.js

这是我对单行的视图为“tr”。我想要点击名称单元格并弹出该单元格的视图。我无法解雇事件..

我错过了什么吗?谢谢!

所以这个问题是由gumballhead解决的,我遇到的问题是需要有一个与ItemRowView关联的tagName。然后在渲染函数中,我需要做自我。$ el.html(this.template(model));

认为与...分享可能会有所帮助。

    ItemRowView = Backbone.View.extend({

    initialize : function() {
    },
    template : _.template($('#item-row-template').html()),
    render : function() {       
        var self=this;        
        var model = this.model.toJSON();
        self.$el = this.template(model);
        return self.$el;
    },

    events : {
        "click td .item-name" : "viewOneItem"
             //Even if I change it to "click td":"viewOneItem", still not firing
    },
    viewOneItem : function() {
        console.log("click");
    }
});

收藏查看:

ItemsView = Backbone.View.extend({

    initialize : function() {
    },
    tagName : "tbody",

    render : function() {
        var self = this;
        this.collection.each(function(i) {
            var itemRowView = new ItemRowView({
                model : i
            });
            self.$el.append(itemRowView.render()); 
        });
        return self.$el;
    }

});

应用视图:     AppView = Backbone.View.extend({       this.items = new Items();

  this.items.fetch();
  this.itemsView = new ItemsView({collection:this.items});    

  $('#items-tbody').html(itemsView.render());

});

表示模板:

<script type="text/template" id="item-row-template">
<tr>
    <td class="item-name">{{name}}</td>
    <td>{{description}}</td>
</tr>
</script>

 <table>
    <thead>
        <tr>
        <th>name</th>
        </tr>
    </thead>
    <tbody id="items-tbody">

    </tbody>
 </table>

1 个答案:

答案 0 :(得分:4)

使用"click td.item-name"作为选择器。您目前正在使用“item-name”类来监听td后代的点击。

仅供参考,您还有一个锚元素的结束标记,但模板中没有开头标记。

修改:我认为您需要self.$el.html(this.template(model));而不是self.$el = this.template(model);

但是您无需使用您发布的代码将this替换为self

编辑2:很高兴你把它整理好了。我来解释一下。

所有骨干视图都需要一个根元素。这是事件哈希中的事件在实例化时委托给的元素。在没有现有元素的情况下实例化Backbone View时,它将根据tagName等配置设置创建一个,默认为"div"。在您明确注入元素之前,该元素不会出现在DOM中。

所以当你在你的渲染方法中设置self。$ el时,你覆盖了根元素(以及事件,虽然它们从未被触发过,因为它会听取td的一个点击,它是一个后代DOM中不存在的div。)

作为附注,并且在您的情况下不是正确的方法,您可以完成this.setElement($(this.template(model));将事件从即时创建的div重新生成到原始模板创建的tr