Javascrit callback

Please post public support tickets here. Note: for private support tickets, please send an email to support@cshtml5.com instead.
amir
Posts: 1
Joined: Tue Nov 10, 2015 3:02 am

Javascrit callback

Postby amir » Tue Nov 10, 2015 3:18 am

Is there a way to have callback from Javascript event?

I execute javascript code with

Code: Select all

JSIL.Verbatim.Expression(@"my JS code");
but do not know how to get callback.

I have integrated Leaflet map library and now need to get callback from variuos events (map click, zoom, drag etc)., e.g.

Code: Select all

map.on('click', function (e) {
                alert(e.latlng.lat);
            });


Instead of alert I need to I need callback triggered in my C#Html project.

JS-Support @Userware
Site Admin
Posts: 1142
Joined: Tue Apr 08, 2014 3:42 pm

Re: Javascrit callback

Postby JS-Support @Userware » Thu Nov 12, 2015 8:03 am

Hi Amir,

Yes, you can easily get callbacks from JavaScript to C#.

To do so, please place the following C# code in your CSHTML5 project:

Code: Select all

void MyMethodThatCallsJavaScriptCode()
{
    JSIL.Verbatim.Expression(@"

    // Place your JavaScript code here ...

    map.on('click', function (e) {
                $0(e);
            });
           
    ", (Action<dynamic>)OnClick);
}

static void OnClick(dynamic eventArgs)
{
    // This is C# code:
    double value = (double)eventArgs.latlng.lat;
    MessageBox.Show("Latitude in degrees: " + value.ToString());
}




In the code above, we access the C# "OnClick" method from within JavaScript. This is achieved by passing it as the first argument of the "JSIL.Verbatim.Expression" method, which makes it available to the JavaScript code via the "$0" keyword. Similarly, you can use "$1", "$2", "$3", etc. keywords to reference the second, third, and fourth arguments of the "JSIL.Verbatim.Expression" method.
Please note that, unlike the "String.Format" method which replaces "{0}" at RUNTIME, the "JSIL.Verbatim.Expression" method replaces "$0" at COMPILE TIME. In fact, if you look at the generated JavaScript code (in the Output folder), you will notice that the "$0" code has already been replaced.

If something is not very clear, please let me know.

Please note that the "dymanic" keyword is currently not well supported under VS 2015 as of the Beta 5.2 - even though it works very well under VS 2012 and VS 2013.

Regards,
JS-Support


Return to “Technical Support”

Who is online

Users browsing this forum: Google [Bot] and 28 guests

 

 

cron