Backbone Marionette - Add a visual effect when swi

2020-02-16 20:33发布

问题:

Is there a convenient way to add an effect when I leave a page (close a view/layout) and open a new one in the same region ? (something like a fade effect)

回答1:

Marionette regions have a method called open that by default just replace the HTML of the old view with the new view. You can override this method to do any animation you like. From the region documentation:

Set How View's el Is Attached

If you need to change how the view is attached to the DOM when showing a view via a region, override the open method of the region. This method receives one parameter - the view to show.

The default implementation of open is:

Marionette.Region.prototype.open = function(view){
  this.$el.html(view.el);
}

This will replace the contents of the region with the view's el / content. You can change to this be anything you wish, though, facilitating transition effects and more.

Marionette.Region.prototype.open = function(view){
  this.$el.hide();
  this.$el.html(view.el);
  this.$el.slideDown("fast");
}

This example will cause a view to slide down from the top of the region, instead of just appearing in place.



回答2:

You could override the close function on the view, doing something like this:

close: function () {
  // fancy fade-out effects
  Backbone.Marionette.View.prototype.close.apply(this, arguments);
}

And do something similar with your render functions.



回答3:

This seems to work for me:

this.views = {
    messageItem: Marionette.ItemView.extend({
        template: Handlebars.templates.messaging_item,
        tagName: "li",
        className: "messaging-item",
        render: function(){
            this.$el.html(this.template(this.model.attributes));
            this.$el.hide();
        },
        onShow: function(){
            this.$el.slideDown(800);
        }
    })
};


回答4:

For future users people could user my plugin for Transition Support in marionette.

https://github.com/saqibshakil/Marionette.TransitionRegion/

I used css3 transitions as those have more hardware support than jquery animations. on the downside using this makes the code async so be carefull of that.



回答5:

I think this could be useful for you.

The following marionette plugin that adds 4 kind of transitions. There can be easily added more transition types.

Basically instead of using yourRegion.show(view)... you can use now yourRegion.showAnimated(view, {animationType: 'yourAnimation'});

it's very easy to use.

https://github.com/marcinkrysiak1979/marionette.showAnimated

see the documentation on github for more info