How to hide div in backbone when user click outside div?

I have a View in Backbone that contains an inner div. I want to hide the div when the user clicks outside the div.

I'm not sure how to set up an event inside the view that says "click NOT #inner_div": "removeDiv".

Any suggestions on how to do this?

+4
source share
3 answers

The usual approach is to bind the click handler directly to <body> , and then close it or hide your <div> . For instance:

 render: function() { $('body').on('click', this.remove); this.$el.html('<div id="d"></div>'); return this; }, remove: function() { $('body').off('click', this.remove); // This is what the default `remove` does. this.$el.remove(); return this; } 

If you just want to hide the <div> rather than remove it, just attach the clicks on the <body> to a different method than remove ; you still want to remove the click handler from <body> to remove . In addition, you will want to block click events on your el view so that they do not fall into <body> .

Demo: http://jsfiddle.net/ambiguous/R698h/

If you have other elements that take care of click events, you can completely position the <div> to hide the <body> , and then bind the click handler to this. You can watch the jQuery BlockUI plugin to see how this is done.

+3
source

If you are using Prototype, you can do this:

 initialize: function() { // some code document.on('click', function(e, target) { if (target !== this.el && target.up('#inner_div').length === 0) { this.remove(); } }.bind(this)); } 

I think with jQuery this might look like this:

 initialize: function() { // some code $(document).on('click', function(e) { if (e.target !== this.el && e.target.parent('#inner_div').length === 0) { this.remove(); } }.bind(this)); } 
0
source

Although manipulating the DOM directly works, you can let Backbone handle things for you, providing your views with an appropriate structure. For instance:

 BoxView = Backbone.View.extend({ events: { 'click': '_click' }, _click: function() { return false; } }); AppView = Backbone.View.extend({ el: '.app', initialize: function() { this.boxView = new BoxView({ el: $('.box') }) }, events: { 'click': '_click' }, _click: function() { this.boxView.remove(); } }); new AppView({ el: $('.app') }); 

Thus, we can change the internal appearance as soon as we click on the external appearance. Pay attention to the binding to the BoxView click event, so that it is not deleted when the user clicks on it.

Demo: https://jsfiddle.net/embs/45da2ppm/

If you already have a complex Backbone view structure that cannot be easily reorganized into a subviews structure, you can still use Backbone.Events to listen to appearance events in the internal view and then manipulate it as you like.

I also recommend checking out this nice article regarding common Backbone errors. Some of them are closely related to your question:

0
source

Source: https://habr.com/ru/post/1440895/


All Articles