JS backbone event when clicking on a document

I am new to working with Backbone JS and I am creating Backbone View. I made this look, so when you click on a template, it calls a function highlightto add a class highlightto my element:

var PlayerView = Backbone.View.extend({

    // ...

    events: {
        "click .player": "highlight"
    },

    // ...

    highlight: function () {
        this.$el.find('.player').addClass('highlight');
    }

});

I want to do this when I click elsewhere in the application, I remove the class highlightfrom this element.

I can declare a click handler on documentand remove the class highlight:

$(document).click(function () {
    $('.player.highlight').removeClass('highlight');
});

And then use event.stopPropagation()in the highlight function to prevent bubbling:

var PlayerView = Backbone.View.extend({

    // ...

    highlight: function (evt) {
        evt.stopPropagation();
        this.$el.find('.player').addClass('highlight');
    }
});

This works and demonstrates the functionality I'm looking for. However, this does not allow the use of basic infrastructure. Is there a proper way to do this in Backbone JS?

+4
2

A Backbone View events hash $el.

, , . :

handleClick: function(e) { 
    this.$(".player").removeClass('highlight');
    this.$(e.currentTarget).addClass('highlight');
}

, , Backbone.View $el, , , .

, .

, , .

+1
   $(document).on('click', function(e){
        Backbone.trigger('document-click-event', e);
    });


var Popup = Marionette.CompositeView.extend({
   ........
    initialize: function(options) {
      _.extend(this, options);
      this.listenTo(Backbone, 'document-click-event', function(e) {
         if (!$(e.target).closest(this.el).length && !$(e.target).closest(this.field).length && !$(e.target).closest('.ui-datepicker').length) {
            this.hide();
         }
      }, this)
.....
0

All Articles