How to execute callback in cotext of different object?

How to execute callback in cotext of different object?

mnowotkamnowotka Posts: 2Questions: 0Answers: 0
edited September 2011 in General
Hello,
In datatables API there are many callbacks. Lets say I would like to specify my own fnServerData callback because I'm using special object to execute all ajax requests (this sound like a stupid reason but lets assume now that it have sense). So I would like to pass method of this object as a callback and make it executed in context of this object, not the context of datatables object. In jQuery $.ajax() function I can specify callback context as one of parameters. How can I achieve it using datatables? Is it possible? Possibility to execute callbacks in context of different objects would be very helpful in building web applications based on MVC pattern.

Replies

  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    http://vikasrao.wordpress.com/2011/06/09/javascripts-call-and-apply-methods/
  • mnowotkamnowotka Posts: 2Questions: 0Answers: 0
    Hmm, I'm not sure if I know how to follow this advice...

    When I initialize dataTable I have to specify some callback (it should be inline function or function name). If I write:

    [code]
    var _this = this;
    this.oTable = $('#my_table').dataTable
    ({
    (...)
    "fnServerData": _this.controller._serverDataCallback
    });
    [/code]
    than _serverDataCallback will be called in context of dataTable object.

    On the other hand I cannot write:

    [code]
    "fnServerData": _this.controller._serverDataCallback.call(_this.controller)
    [/code]

    because it will execute this method instead of defining it.

    Of course I can write:

    [code]
    var _this = this;
    this.oTable = $('#my_table').dataTable
    ({
    (...)
    "fnServerData": function( sSource, aoData, fnCallback ){_this.controller._serverDataCallback( sSource, aoData, fnCallback );},
    });
    [/code]

    But I was looking for some more elegant solution, not including inline functions...
  • allanallan Posts: 63,531Questions: 1Answers: 10,474 Site admin
    Basically I think you've got exactly the correct idea here. If you don't want to inline it, then you could simply pull it out into its own function, but as you've noted fnServerData must be given a function primitive, rather than the result of a function.

    Allan
This discussion has been closed.