Executing a function passed as an argument in Javascript? - Stack Overflow

I'm trying to write a generic function that will block out the UI while an AJAX call is made.Wha

I'm trying to write a generic function that will block out the UI while an AJAX call is made. What I'm trying to do is have a function A run any other function passed in as an argument. This is what I've got so far:

function blockWhileLoading(fn, msg)
{
  if (msg == null)
  {
    msg = 'Please wait while the next page is loaded...';
  }

  $.blockUI(
  {
    message: '<h1>' + msg + '</h1>',
    css:
    { 
      border: 'none', 
      padding: '15px', 
      backgroundColor: '#E3D9BA', 
      '-webkit-border-radius': '10px', 
      '-moz-border-radius': '10px', 
      color: '#4D2612'
    }
  }); 
  $('body').scrollLeft(0);

  setTimeout(function()
  {
    eval(fn);
    $.unblockUI();
  }, 1000);
}

Now when it es time to eval the function, nothing seems to happen. Is eval not the correct way to force a function to run?

I'm trying to write a generic function that will block out the UI while an AJAX call is made. What I'm trying to do is have a function A run any other function passed in as an argument. This is what I've got so far:

function blockWhileLoading(fn, msg)
{
  if (msg == null)
  {
    msg = 'Please wait while the next page is loaded...';
  }

  $.blockUI(
  {
    message: '<h1>' + msg + '</h1>',
    css:
    { 
      border: 'none', 
      padding: '15px', 
      backgroundColor: '#E3D9BA', 
      '-webkit-border-radius': '10px', 
      '-moz-border-radius': '10px', 
      color: '#4D2612'
    }
  }); 
  $('body').scrollLeft(0);

  setTimeout(function()
  {
    eval(fn);
    $.unblockUI();
  }, 1000);
}

Now when it es time to eval the function, nothing seems to happen. Is eval not the correct way to force a function to run?

Share edited Jan 16, 2013 at 12:05 wonea 4,98917 gold badges91 silver badges143 bronze badges asked Feb 12, 2010 at 19:25 Sonny BoySonny Boy 8,02619 gold badges80 silver badges105 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

No, eval is used to turn a chunk of "string" into JavaScript code at runtime. Simply call fn(). It's a function reference.

This is what eval does:

var myalert = "alert('test');";
eval(myalert);

Equivalent to:

eval("alert('test');");

Just use fn();

If fn is being passed as an object and not a string, calling fn() should work.

Why not simply use:

fn();

Instead of eval.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744880831a4598828.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信