opalrbopal

Event Complete Callbacks with Opal-jQuery


I am working on a project that handles multiple jQuery events in succession using the opal-jquery wrapper. jQuery has very effective callback functionality and I am wondering if it is possible to do this in pure ruby with Opal.


Solution

  • You could use a Promise which is a technique to manage long-term asynchronous events and avoid callback-hell. In regular Opal you would do for example:

    HTTP.get("url") do |response|
      puts "got response"
    end
    

    With promises, this becomes:

    HTTP.get("url").then do |response|
      puts "got response"
    end
    

    The difference lies in the then which returns the Promise (see http://opalrb.org/docs/promises/). The code block will be executed when the HTTP get returns with content (or an error).

    Also check up this article on how to use promises with opal-jquery

    http://opalrb.org/blog/2014/05/07/promises-in-opal/