4
\$\begingroup\$

I have a lot of repeatable blocks of code and want to optimize/simplify them:

 function animationInit() {
 content = $('#content')
 .bind('show',function(event, f) {
 $(this).animate({right:0}, lag + 200, function() {
 if (f) f();
 });
 })
 .bind('hide',function(event, f) {
 $(this).animate({right:-700}, lag + 200, function() {
 if (f) f();
 });
 });
 hotelnav = $('#hotel')
 .bind('show',function(event, f) {
 hotelnav.removeClass('small');
 $(this).animate({left:0}, lag + 200, function() {
 if (f) f();
 });
 })
 .bind('hide',function(event, f) {
 $(this).animate({left:isGallery()?-300:-300}, lag + 200, function() {
 hotelnav.addClass(isGallery()?'small':'');
 if (f) f();
 });
 });
 bottompanel = $('#bottompanel')
 .bind('show',function(event, f) {
 $(this).animate({bottom:40}, lag + 200, function() {
 if (f) f();
 });
 })
 .bind('hide',function(event, f) {
 $(this).animate({bottom:-120}, lag + 200, function() {
 if (f) f();
 });
 });
 booknow = $('#booknow')
 .bind('show',function(event, f) {
 $(this).fadeIn(lag + 200, function() {
 if (f) f();
 });
 })
 .bind('hide',function(event, f) {
 $(this).fadeOut(lag + 200, function() {
 if (f) f();
 });
 }); 
};

How i can optimize repeatable parts of code with callbacks? Im trying to create separate function like this:

function cb(callback) {
 if (callback) callback();
};

... but just have a lot of asynchronous callbacks...

Quill
12k5 gold badges41 silver badges93 bronze badges
asked Sep 7, 2011 at 21:40
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I don't understand the need for

function() {
 if (f) f();
}

put f instead of that whole thing. If it is undefined it won't get called.

e.g

.bind('show',function(event, f) {
 $(this).animate({right:0}, lag + 200, f);
});

Another thought came to me. The functions you use could be factored and used like:

function animateRight(event, f, rightValue, delay)
{
 $(this).animate({right: rightValue}, lag + delay, f);
}

(or if you can't pass that information in:

function animateRight(event, f, rightValue, delay)
{
 return new function()
 {
 $(this).animate({right: rightValue}, lag + delay, f);
 }
}
answered Sep 8, 2011 at 7:25
\$\endgroup\$
2
  • \$\begingroup\$ @350D I've also some other thoughts Read my update. \$\endgroup\$ Commented Sep 8, 2011 at 23:28
  • 1
    \$\begingroup\$ creating universal function for all kind of animations - good point. Im working on it, thanks! \$\endgroup\$ Commented Sep 9, 2011 at 13:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.