Calling a jQuery user defined function from Silverlight

524 views Asked by At

I have this:

(function ($) {
  var myObj = {
    callMe: function (msg) {
      console.log(msg);
    }
  }
})(jQuery);

and I would like to call the callMe function from Silverlight.

This does not seem to work:

ScriptObject jsObject = (ScriptObject)HtmlPage.Window.GetProperty("callMe");
jsObject.InvokeSelf('This is a message');

How would I go about exposing the callMe function so that I can Invoke it from Silverlight?

Answer: (since I don't have enough rep I have to answer here)

Tomalak, you pointed me in the right direction! It actually works both ways as long as you make it a property of the window object:

<script type="text/javascript">

    (function ($) {

        var myObj = {

            callThis:function(msg){
                console.log("Internal call:" + msg);
            }

        };
    window.myObj = myObj;

    window.callMe = function (msg) {
        console.log("External call:" + msg);
      }

    })(jQuery);
</script>

<script type="text/javascript">
    window.callMe("well, hello there...");
    window.myObj.callThis("... and hello you!");
</script>
1

There are 1 answers

4
Tomalak On BEST ANSWER

This is impossible with your code since myObj and its contents is local to your JavaScript function.

Make it a property of the window object instead.

(function ($) {
  window.callMe = function (msg) {
    console.log(msg);
  }
})(jQuery);