Can i give the view a show up animation in emberjs

2019-03-20 13:28发布

问题:

Here is a example using emberjs router http://jsbin.com/agameq/edit. Now I wanna have some showup animation, like fadeIn or fadeOut, when route changed. what should I do?

回答1:

Every View in ember has a method named didInsertElement:

Called when the element of the view has been inserted into the DOM. Override this function to do any set up that requires an element in the document body.

All ember views also have a $ which is a reference to jQuery, so you can wrap some element in your view with it and apply any changes to it such as:

// this will animate only the tag h2, which in your case is the title of the users view
App.UsersView = Ember.View.extend({
    templateName: 'users',
    didInsertElement: function() {
        this.$('h2').animate({ fontSize: "3em" }, 900 );
    }   
});

Or you can call it without arguments (like $()) to return the current view wrapped by jQuery.

To animate a view as you enter in that view/route, do this in your App.UsersView:

// this will animate the entire view
App.UsersView = Ember.View.extend({
    templateName: 'users',
    didInsertElement: function() {
        this.$().animate({ fontSize: "3em" }, 900 );
    }   
});

(Note: my animation is pretty lame, but it's just to show where to call the methods, do a real animation)

Here's a modified version of your JSBin



回答2:

Following the answer from @MilkyWayJoe, you probably want to hide the View before inserting it, by setting the isVisible property to false:

App.UsersView = Ember.View.extend({
    templateName: 'users',

    isVisible: false,

    didInsertElement: function() {
        var self = this;
        this.$().fadeIn(700, function(){
            self.set('isVisible', true);  //inform observers of `isVisible`
        });
    }   
});

Or use this animation Mixin, which allows you to animate Views by changing a set of observed CSS properties:

App.UsersView = Ember.View.extend( JQ.Animate, {
    templateName: 'users',

    isVisible: false,

    // Observed CSS properties
    cssProperties: ['display'],

    // Optional animation properties
    duration: 700,
    easing: 'easeInOutCubic', 

    didInsertElement: function() {
        this.set('display', 'block'); 
    },

    afterAnimate: function() {
        this.set('isVisible', true);
    }   
});