Skip to content

JavaScript Decorator Functions

brett hartshorn edited this page Sep 30, 2015 · 6 revisions

You can define your own custom decorator functions, and they work as they normally do in Python. New to decorators? See TheCodeShips post on it here.

The JavaScript backend also defines some special decorators you can use to trigger some options. The following special decorators are applied at transpile time, not runtime.

@locals

Enables saving local variables of the function to .locals property of the function, this is updated each call.

https://github.com/rusthon/Rusthon/blob/master/regtests/lang/func_locals.py

@redef

Marks a function as redefinable at runtime, even when the --release options is used. The special method redefine can then be used to redefine the function at runtime.

@redef
def myfunc():
  pass
def foo():
  print 'foo'
myfunc.redefine(foo)

The example above changes myfunc to use foo You can also pass a string to the redefine method, the string must be JavaScript, not Python (the transpiler is not available at runtime).

https://github.com/rusthon/Rusthon/blob/master/examples/javascript_redefine_function.md

@debugger

This decorator only has an effect when using NW.js to test your application. It is applied to the entry point function of your program, and it takes care of opening the Chrome DevTools window just before your function loads, then when you set debugger.breakpoints to true, your program will halt on any uncaught exceptions.

debugger.breakpoints = True

@debugger
def main():
  ...

For more info on debugging, see: https://github.com/rusthon/Rusthon/wiki/JavaScript-Debugger

@bind()

The @bind() decorator is used as a shortcut to assign a function to something. If you want to add a method to a class on an external library, you can do it like this:

@bind(THREE.Camera.prototype.mymethod)
def mymethod():
  pass

Above is the same thing as doing this:

def mymethod():
  pass
THREE.Camera.prototype.mymethod = mymethod

@property

The decorator @property can be used to mark a function inside a class as a "getter" function. more info:

class A:
  @property
  def x(self):
    return 1
a = A()
assert a.x == 1

To define a setter you use the getter name as a decorator + .setter

class A:
  @property
  def x(self):
    return 1
  @x.setter
  def f(self, value):
    self._hidden = value

@getter and @setter

The decorators @getter and @setter can be used instead of the python standard @property to define getter and setter functions. It works the same but is just shorter and more clear. Note that the name of the getter or setter functions must be the same name, the property name.

class A:
  @getter
  def x(self):
    return 1
  @setter
  def x(self, value):
    self._hidden = value

https://github.com/rusthon/Rusthon/blob/master/examples/javascript_classes.md

Sidebar

Clone this wiki locally