开发者

callback of function passes as variable

trying to pass a function name as a variable in order to call it in a function etc but can't figure out how to call it.

Any help welcome!

jQuery.fn.makeSlideShow =开发者_JS百科 function(opts) { 

    opts = jQuery.extend({
        speed       :400,
        delay       :0,
        slideCLass  :'.slide',
        pager       :'#pager',
        next        :'.nextSlide',
        previous    :'.previousSlide',
        startSlide  :0,
        screenClick :false,
        callback:function(){return false;}
    },opts||{});

   //   callback the fullscreenImage function here?

};



$('#slideShow').makeSlideShow({
    callback : 'fullscreenImage'
});

function fullscreenImage(){
    alert('called!');
}

best, Dan.


You're passing a string literal to your plugin. You need to pass the function reference

$('#slideShow').makeSlideShow({
    callback : fullscreenImage
});

Within your plugin code, you need to invoke that function. This can be done in several ways:

opts.callback();  // default call
opts.callback.call(scope, param1, param2, ...);  // invoke makeSlideShow with a specific context and arguments
opts.callback.apply(scope, [param1, param2, ...]); // invoke makeSlideShow with a specific context and arguments as array


You should probably pass the identifier describing the function, rather than a string with its name. So switch this:

$('#slideShow').makeSlideShow({
    callback : 'fullscreenImage'
});

to this:

$('#slideShow').makeSlideShow({
    callback : fullscreenImage
});


If passing a string, you would need to know the scope where the function is located.

window[ opts.callback ]()

or

window[ opts.callback ].call( this )

These assume the function is global.

It would be better to require that a reference to the function is passed instead of a String.

$('#slideShow').makeSlideShow({
    callback : fullscreenImage
});

function fullscreenImage(){
    alert('called!');
}

Then you would do:

opts.callback()

or

opts.callback.call( this )


You can set 'callbeck' propety as follows:

$('#slideShow').makeSlideShow({
    callback : fullscreenImage
});

and than you can call it like this:

...
callback()
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜