Skip to content

Instantly share code, notes, and snippets.

@dherman
Created March 4, 2016 07:00
Show Gist options
  • Save dherman/2755c4763ea42d236cd8 to your computer and use it in GitHub Desktop.
Save dherman/2755c4763ea42d236cd8 to your computer and use it in GitHub Desktop.
my first working neon class
#[macro_use]
extern crate neon;
extern crate neon_sys;
use neon::mem::Handle;
use neon::vm;
use neon::js::{JsFunction, JsString, Value, Object};
use neon::js::class::{JsClass, Class};
struct Greeter {
greeting: String
}
declare_class! {
class JsGreeter for Greeter {
init(call) {
let scope = call.scope;
let greeting = try!(try!(call.arguments.require(scope, 0)).to_string(scope)).value();
Ok(Greeter {
greeting: greeting
})
}
method hello(call) {
let scope = call.scope;
let name = try!(try!(call.arguments.require(scope, 0)).to_string(scope)).value();
let msg = vm::lock(call.arguments.this(scope), |greeter| {
format!("{}, {}!", greeter.greeting, name)
});
Ok(try!(JsString::new_or_throw(scope, &msg[..])).upcast())
}
}
}
register_module!(m, {
let class: Handle<JsClass<JsGreeter>> = try!(JsGreeter::class(m.scope));
let constructor: Handle<JsFunction> = try!(class.constructor(m.scope));
try!(m.exports.set("Greeter", constructor));
Ok(())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment