【问题标题】:Backbone.js Event Binding not firingBackbone.js 事件绑定未触发
【发布时间】:2012-10-17 15:32:21
【问题描述】:

select 是从模板渲染的,并且在调用 renderGroups() 之前不存在于 DOM 中。

我认为 事件是绑定到视图的,所以如果一开始 DOM 中不存在 select 并不一定重要?

我是 backbone.js 的新手,所以它可能很明显:

var DirectoryView = Backbone.View.extend({
    el: $("table tbody"),
    initialize: function(){
        // Populate our collection
        this.collection = new Directory(contacts);

        // Get our unique groups
        var groups = this.getGroups();
        this.renderGroups(groups);
    },

    renderGroups: function(groups) {
        var group = $("#groups");

        var groupView = new GroupView({
            model: {groups: groups}
        })

        group.append(groupView.render().el)

    },

    events : {
        "change select" : "select"
    },

    select: function(e) {
        console.log("hello")
    },

    getGroups: function() {
        // Pluck all the group properties from our array of contacts and return the unique groups
        return _.uniq(this.collection.pluck("group"), false, function(group){
            return group.toLowerCase();
        });
    }
});

模板

    <script id="group-option-tmpl" type="text/template">
        <option value="all">All</option>
        <% _.each(groups, function(group) { %>
            <option value="<%= group %>"><%= group %></option>
        <% }); %>
    </script>

JSFiddle

http://jsfiddle.net/BDgMu/1/

【问题讨论】:

  • 如果将renderGroups 重命名为render 会怎样?
  • @jsalonen 我可以检查,但 render() 函数实际上呈现了一些联系人。 DirectoryView 是“主”视图。

标签: javascript backbone.js backbone-events


【解决方案1】:

看起来$("#groups") 不在DirectoryView.el 内。我想$('#groups')select

【讨论】:

  • $("#groups") 是插入选择的包装 div
  • 该包装器是否位于 $("table tbody") 内?你的select 标签在哪里?
  • 我明白了,因为它是由其他视图组成的“主视图”,我将 el 设置为“body”,它工作正常
  • 我不会将整个body 用作view.el。我认为.container 更好。
猜你喜欢
  • 1970-01-01
  • 2012-04-16
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
相关资源
最近更新 更多