Question about returning values from the API Iteration without returning the API

Question about returning values from the API Iteration without returning the API

jLinuxjLinux Posts: 981Questions: 73Answers: 75

I had a question about returning values from custom API methods. Lets say I wanted to return a string (and just the string value) from a method, and this would rely on something in the DT Settings object, so I use the iterator() to get the settings via the callback. The iterator() attaches an API instance, whats the best way to return JUST the string?

Here is an example...

$.fn.dataTable.Api.register( 'something.test1()', function ( conditions ) {
    return this.iterator( 'table', function( dtSettings )  {
        return 'Table ID: ' + dtSettings.sTableId;
    }, false );
} );

However, that returns the API as well, I thought setting the last parameter to false would stop the API from being returned if there was a value that got returned.. Per the documentation

If not set, or false the original instance will be returned for chaining, if no values are returned by the callback method.

I know what I could do is this:

$.fn.dataTable.Api.register( 'something.test1()', function ( conditions ) {
    return this.iterator( 'table', function( dtSettings )  {
        return 'Table ID: ' + dtSettings.sTableId;
    }, false )[0];
} );

But honestly, that just seems really incorrect... But if its not, then just let me know.

JSBin demo here, open the console, notice the differences.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin

    You would probably avoid using the iterator all together for this - this is how I do it for row().data().

    There is another option - if you want to have both a plural and singular function, as much of the API does, you can register a plural method (for example).

    Allan

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75

    I use the iterator mainly because the API method is associated to specific tables, so I use the the dtSettings parameter that gets passed to the callback. How can I get my hands on that otherwise?

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin
    Answer ✓

    this.context is the array that contains the settings objects for the instance - so this.context[0] will give you the settings object for the table (if you are only handling one table - which most do). The row().data() link above shows one option for how to do this.

    Allan

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75

    Perfect! Thanks!

This discussion has been closed.