返回值时的Javascript函数排序

时间:2015-06-07 21:19:05

标签: javascript greensock tweenmax gsap

我有三个函数:show(),hide()和swap(),它们控制布局中显示的当前模板,给定模板容器元素的id。

我想交换函数调用show,当show返回一个值时,我想触发隐藏函数。

E.g。

var hide = function(template) {
    TweenMax.to(frame, 1.18, {
        opacity: 0,

        onComplete: function() {
            return true;
        }
    });
}

var show = function(template) {

}

var swap = function(currentTemplate, targetTemplate) {
    // hide(currentTemplate) then when "true" is returned, show(targetTemplate)

}

swap();

TweenMax中的onComplete函数在1.18秒后运行。我知道我可以把show()放在这里或者把show传递给hide函数,但是如果可能的话我宁愿保持两个独立。

有没有办法做到这一点(最好不用jQuery)?

谢谢!

2 个答案:

答案 0 :(得分:0)

只要hide和show是同步的 - 因为它们都是简单的DOM更新,似乎可能是真的 - 你可以使用swap来控制流。

也就是说,如果这些操作是异步的(例如,如果他们需要AJAX请求),这种方法将无效。您必须传递回调才能使它们正常工作,或者在es6界面中使用新的Promise来使事情正常工作。

hide(template).then(show)

答案 1 :(得分:0)

不会TimelineMax足够吗?如果我理解正确,您希望序列您的动画,如果您已加载TweenMax,则可以使用TimelineMax,因为TweenMax bundles TimelineMax & other goodies with it

因此,您的代码可以变为:

function swap(currentTemplate,targetTemplate){
    new TimelineMax().to(currentTemplate,1.18,{opacity:0}).to(targetTemplate,1.18,{opacity:1});
}

看看this fiddle。希望你觉得它很有用。

<强>更新

在这个new fiddle中,我添加了一个切换按钮,切换动画返回或转发。

代码如下:

<强> JavaScript的:

var byeWorld=document.querySelectorAll('.bye-world')[0];
var helloWorld=document.querySelectorAll('.hello-world')[0];
var toggleButton=document.querySelectorAll('.toggler')[0];
var timeline=new TimelineMax({paused:true,reversed:true});
var duration=.8;

function init(){
    toggleButton.addEventListener('click',swap,false);
    TweenMax.set(helloWorld,{opacity:0});
    timeline.to(byeWorld,duration,{opacity:0,ease:Power2.easeIn}).to(helloWorld,duration,{opacity:1,ease:Power2.easeOut});
}

function swap(){
    (timeline.reversed())?timeline.play():timeline.reverse();
}

init();

希望它有所帮助。