切换事件在第二次调用时触发

时间:2012-11-06 15:00:06

标签: javascript jquery backbone.js

有一个模块/视图定义:

define(['jquery', 'underscore', 'backbone', 'text!templates/product.html'], 
function($, _, Backbone, productTemplate) {
    var ProductView = Backbone.View.extend({
        tagName: "li",
        className: "span3",
        events: {
            "click button.view-details": "viewDetailed"
        },
        viewDetailed: function(e) {
            var _view = this;
            $(e.currentTarget).toggle(
                function() {
                    $(this).find('i').removeClass('icon-eye-open');
                    $(this).find('i').addClass('icon-eye-close');
                },
                function() {
                    $(this).find('i').removeClass('icon-eye-close');
                    $(this).find('i').addClass('icon-eye-open');
                }
            );
        },
        initialize: function() {
            this.model.bind('change', this.render, this);
            this.model.bind('destroy', this.close, this);
        },
        render: function() {
            var compiledTemplate = _.template(productTemplate, this.model.toJSON());
            this.$el.append(compiledTemplate);
            return this;
        }
    });
    return ProductView;
});

第一次按button.view-details无效(据我所知,它只是注册toggle事件)。我如何以正确的方式定义它?

1 个答案:

答案 0 :(得分:1)

这应该是您所需要的一切

viewDetailed: function(e) {
        var _view = this;
        $(e.currentTarget).toggle(
            function() {
                $(this).find('i').toggleClass('icon-eye-closed icon-eye-open');
        });
    }

或者只是将函数绑定到button.view-details

$('button.view-details').on('click', function() {
    var _view = this;
    $(this).find('i').toggleClass('icon-eye-closed icon-eye-open');
});