1

I'm having problems with Script#. I got a ASP.NET page which loads a JavaScript file and uses a object from there.

var tracker = Piwik.getTracker(...);

Now I also have a Script# generated JavaScript file which is also included in that same page. Now I want to use the tracker object in that Script# .cs file.

Type.InvokeMethod(tracker, "trackPageView");

Doesn't compile: does not exist in the current context

Type.InvokeMethod("tracker", "trackPageView");

Compiles but outputs: 'tracker'.trackPageView();

Any ideas?

2 Answers 2

4

When trying to emit code for a 3rd party javascript library, using Script.Literal will work but usually should be avoided. The whole point of using Script# is so you get compiler support, and easy refactoring.

I would recommend creating some new classes in your Script# library or even a separate Script# Import library if you plan to use Piwik in other projects.

The key is to mark these classes with the attribute [Imported] - This attribute will prevent the creation of a js file for the classes but will give you all the strong typing and refactoring goodness that makes script# so wonderful.

I'm not sure what "Piwik" is but I'll assume it's a Singleton object in the javascript library. Create the following two classes.

[Imported]//we don't want this to show up in the javascript source.
public sealed class Tracker
{
    public void TrackElement()//this will write trackElement() in emitted js.
    {

    }


}


[Imported]//we don't want this to show up in the javascript source.
public static class Piwik
{
    public static Tracker GetTracker(string item)//this becomes getTracker()
    {
        return null;
    }


}

You'll now be able to write code like this in Script#

Tracker tracker = Piwik.GetTracker("whatever");//c#

It will emit javascript that looks like this.

var tracker = Piwik.getTracker('whatever');//javascript
Sign up to request clarification or add additional context in comments.

Comments

-1

Already found it: Script.Literal("tracker.trackPageView()");

1 Comment

Script.Literal is the last resort... and really a temporary workaround, since you're loosing a lot of the benefits of writing in c#. Marking this down as there is a better answer showing how to write the import definition than this, which is the accepted answer.

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.