How to specify method callback when inserting Backbone View in DOM?

I need to run a script layout as soon as my views are inserted into the DOM. So that...

$(".widgets").append(widgets.render().el) $(".widgets .dashboard").isotope # <-- This needs to be called whenever new widgets are inserted 

The problem is that I have to insert new widgets in several different kinds and re-call this script several different places, which is not DRY. I am wondering how I can define isotope in a View class.

Would it be nice to define an event listener to add to ".widgets" and run the script? Is there a built-in way to create views that are reasonable when they are added to the DOM?

(In this case, it would also be useful to define a callback when the View is removed from the DOM.)

+4
source share
2 answers

How about calling an isotope every time the view is render ed? You need to be careful to call render() only after entering the widget, but this should take care of your problem:

  //in Backbone.view.extend({ initialize: function() { // fix context for `this` _.bindAll(this); }, render: function() { // .. do rendering.. this.isotope(); return this; } // }) // end .extend 
0
source

using:

 var self = this; this.$el.on('DOMNodeInserted', function(evt){ self.isotope(); $(evt.target ).stopPropagation(); }) 
0
source

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


All Articles