0

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 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

That does not work. I get 'Unexpected token (' (function ($) { window.callMe: function (msg) { console.log(msg); } })(jQuery); <script type="text/javascript"> window.callMe("test"); </script>
@Jonah: Sorry, my bad. Fixed, try again.
Tomalak: I've given the answer as an edit in my question. You'll be getting your points! Thanks!
@Jonah Of course it works both ways as long as you make it a property of the window object. That's the whole point. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.