javascripthighchartsrubymotionrubymotion-promotion

Pass data to Javascript from ProMotion WebScreen


I am building an iOS app using the wonderful RubyMotion framework and ProMotion gem stack.

I want to display a chart in a PM::WebScreen on my iPhone. I reference an HTML file in the content method, and have (1) the HTML file, (2) my custom JS methods file, (3) my JS chart library (HighCharts), and (4) jQuery in my resources folder. All this renders fine.

I am able to create the data array for the chart in my PM::WebScreen file (I get the data from an API call to an external source.) The chart renders fine with static data typed in.

The Problem

I want to pass my the data array to my custom JS file to get it to draw the chart with dynamic data. How can I do that?

I would prefer not to make an ajax call from my JS because I may want to use that array elsewhere in my RubyMotion/ProMotion code.

If I can pass the data to the HTML file, I suppose I could extract it to JS from there using jQuery.

Please advise. Thanks!


Solution

  • You can use the webview method stringByEvaluatingJavaScriptFromString. For example, if you have a JS function included in your html called loadData that take data as an argument, you can do

    In your JS:

    function loadData(data) {
    // do something with your data
       $("#chart").show();
    }
    

    In RM:

    data = dataFromSource
    webView.stringByEvaluatingJavaScriptFromString('loadData(' + data +')')