简体   繁体   中英

Backbone event not working

Am trying to add and remove a class based on the link that is clicked using BackboneJS Events based on a tutorial I saw but am not sure why my code is not working.

If the link is clicked add the class "selected" to it and remove the class "selected" from any other link that may have had it.

I am not sure why the Event is not firing. Here is a fiddle: http://jsfiddle.net/EL8gM/

Here is the JavaScript:

var Model = Backbone.Model.extend({
    defaults: {
        items: [
            {
                "name": "One",
                "id": 1           
            },
            {
                "name": "Two",
                "id": 2           
            },
            {
                 "name": "Three",
                 "id": 3           
            }
        ]
    }
});

var myModel = new Model();

var View = Backbone.View.extend({
    el: '.js-container',

    initialize: function(options) {
        // Re-render when the model changes
        this.model.on('change:items', this.render, this);
    },

    template: _.template($('#list-template').html()),

    events: {
        "#items li a": "this.setSelectedItem"
    },

    render: function() {
        console.log(this.model.toJSON());
        this.$el.html(this.template(this.model.toJSON()));
    },

    setSelectedItem: function(event) {
        var selectedItem = $(event.currentTarget);
        console.log('selectedItem =', selectedItem)
        // Set all of the items to not have the selected class
        $('#items li a').removeClass('selected');
        selectedItem.addClass('selected');
        // Store a reference to what item was selected
        this.selectedItemId = selectedItem.data('id');
        return false;
    }
});

var myView = new View({model: myModel});
myView.render();

Here is my HTML

<script id="list-template" type="template">
    <ul id="items">
        <% for(i = items.length - 1; i >= 0; i--) { %>
            <li>
                <a href="#" data-id="<%= items[i].id %>"><%= items[i].name %></a>
            </li>
        <% } %>
    </ul>
</script>

<div class="js-container"></div>

Should be

events: {
    "click #items li a": "setSelectedItem"
},

edit: there's another typo where you misspelled console

cosnole.log('selectedItem =', selectedItem)

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