简体   繁体   中英

How do I assign a real function into a javascript object to use as a callback?

I've got a Javascript mess that looks something like:

Note: Not working code, just trying to illustrate my problem...

$(function() {
    $(foo).Something( {  //Something is a grid control
       buttons: {
            add: {
                onClick: function() { //Build dialog box to add stuff to grid
                    $('<div></div>')
                    .html('...')
                    .dialog({
                        buttons: {
                            done: { //Finished button on dialog box
                                OnClick: function() {
                                    $(this).dialog('close');
                                }
                            }
                        }
                    });
                }
            }
       } 
    } );
});

I'd like to replace some of the function(){...} s with real functions, to clean things up a bit and to get rid of all that indenting. How do I assign a real function to one of the callbacks rather than an anonymous function?

function abc(){
  return false;
}
var callback = {click : abc}

You can then use callback.click.call or callback.click.apply

给出函数名称而不是function(){ ... }

+1 because of the awesome indentation example.

You can define named functions as Joyce stated; you can also considerably clean up that deeply nested code by just declaring some variables (function or not) and spreading the code into multiple, non-nested statements.

The dialog creation would be my first candidate for that type of refactoring (and it demonstrates uses a named function):

function CreateDialog() { //Build dialog box to add stuff to grid
                    $('<div></div>')
                    .html('...')
                    .dialog({
                        buttons: {
                            done: { //Finished button on dialog box
                                OnClick: function() {
                                    $(this).dialog('close');
                                }
                            }
                        }


$(function() {
    $(foo).Something( {  //Something is a grid control
       buttons: {
            add: {
                onClick: CreateDialog
                }
            }
       } 
    } );
});

I should also note that you can initialize most jQuery objects (looks like you are using jQueryUI) after they are created. For example, you don't have to configure the buttons all in one shot: http://jqueryui.com/demos/dialog/#option-buttons

OK then, here goes my answer:

Oops.. You did functionname() (note the extra ()s). :sigh: That's what you get for working on this at 3 AM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM