简体   繁体   中英

Backbone.js Event Binding not firing

The select is rendered from a template and does not exist in the DOM until renderGroups() is called.

I thought the events were bound to the view so it wouldn't necessarily matter if the select didn't exist in the DOM at first?

I'm new to backbone.js so its probably pretty obvious:

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

template :

    <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/

Looks like $("#groups") is not located inside DirectoryView.el . I suppose $('#groups') is select .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM