Norgul
Norgul

Reputation: 4783

Ext JS 3.4. callbacks

I would like to add a callback to a created combo box, so initially I did this:

{
    fieldLabel    : i18n._('Department code'),
    xtype         : 'combo',
    ...
    store         : ...,
    listeners     : {
        scope   : this,
        'select': function(index) {
                      self.getListOfPossibleDrives(index);
                  }
    }
}

And while it works, I don't consider it really a clean solution since I would like to be left with a callback only.

So I did this:

{
    fieldLabel    : i18n._('Department code'),
    xtype         : 'combo',
    ...
    store         : ...,
    listeners     : {
        scope   : this,
        'select': self.getListOfPossibleDrives(chosenBook)
    }
}

But naturally, I now have unresolved variable chosenBook. Is it possible to give an index variable to callback without invoking "natural" function from 'select' listener?

Upvotes: 1

Views: 156

Answers (1)

I would pass thew reference of the function to the callback parameter. What you're doing now, is calling the function.

// Definition of the callback function 
this.getListOfPossibleDrives = function (chosenBook) {
     // Your code when a book is selected
}

// Configuration for the comboBox
var config = {
    fieldLabel    : i18n._('Department code'),
    xtype         : 'combo',
    ...
    store         : ...,
    listeners     : {
        scope   : this,
        'select': self.getListOfPossibleDrives
    }
}

When in a parameter or object you do somefunction() (with parentheses/brackets) you're actually calling the function, so what you need in your configuration is, or defining the function as you already did in the beginning, or passing a reference to another function.

It isn't magic, it's only that you can pass functions as parameters. For example, you can have this:

this.myFunctionOne = function (myStringParam) {
    // Do things
}

this.anotherFunction = function (callback) {
    // Do things... and call a callback function received as param
    callback('hello');
}

this.anotherFunction(this.myFunctionOne);

// Or you can do directly
this.anotherFunction(function(param) {
    console.log(param);
});

// With ES6 syntax
this.anotherFunction((param) => {
    console.log(param);
});

When you pass a function you don't need to say the params that it needs to receive.

anotherFunction will call the callback (the function received) with a hello string, so depending on the function, it'll do one thing or another:

this.anotherFunction(function(param) {
    console.log('I print a different message:', param);
});

Last one will print: I print a different message: hello

Upvotes: 1

Related Questions