How to write a function in script# to be called wi

2019-02-25 16:29发布

问题:

I am writing javascript in script#. I would want to write a function that looks like

function myFunc()
{
    if(this.value > 100)
          return true;
    else
          return false;
}

This function can be called with any instance which has a property 'value'.

How can I write this function in Script#? In Script#, the generated javascript code seems to be making a local reference to this and doesn't work when some other object is passed as 'this'.

回答1:

This is similar to being able to reference "this" inside a jQuery callback function. See the Current property on jQuery class for example (https://github.com/nikhilk/scriptsharp/blob/cc/src/Libraries/jQuery/jQuery.Core/jQuery.cs).

Specifically, if you write this:

[ScriptImport]
public static class Global {

    [ScriptField, ScriptAlias("this")]
    public static object This {
        get { return null; }
    }
}

Then you can write this:

public static class MyCode {

    public static bool MyFunction() {
         return (Script.GetField<int>(Globals.This, "value") > 100);
    }
}

Of course you could also write the imported class to return a strongly typed class (again see the jQuery example), which would make it possible to write MyFunction without using Script.GetField.

The code above assumes script# 0.8 APIs (which you can get from the project's download page on github). For prior builds replace [ScriptImport] with [Imported] and [ScriptField] with [IntrinsicProperty].

I am hoping to put something like the This property in the Script class so its available out-of-the-box in when 0.8 is finalized.



标签: script#