Hi, all!
i thought this might interest some of the class binders out there:
binding to member variables.
First let's show how it's used:
struct Foo
{
std::string bar;
};
...
myObjectTemplate.SetAccessor(
"bar",
GetMemVar<Foo,std::string,&Foo::bar>,
SetMemVar<Foo,std::string,&Foo::bar> );
And now in JS code:
my.bar = "hi, world";
print( my.bar );
works :)
Now the trivial implementations:
template <typename WrappedType, typename PropertyType, PropertyType
WrappedType::*MemVar>
Handle<Value> GetMemVar(Local<String> property,
const AccessorInfo &info)
{
WrappedType * self = convert::CastFromJS<WrappedType>( info.This
() );
if( ! self ) return v8::ThrowException( v8::String::New( "Getter
function could not access native object!" ) );
return convert::CastToJS( (self->*MemVar) );
}
template <typename WrappedType, typename PropertyType, PropertyType
WrappedType::*MemVar>
void SetMemVar(Local<String> property, Local<Value> value,
const AccessorInfo& info)
{
WrappedType * self = convert::CastFromJS<WrappedType>( info.This
() );
if( self )
{
self->*MemVar = convert::CastFromJS<PropertyType>( value );
}
else
{
// Setter function could not access native object!
}
}
That code should be adaptable to other binding frameworks than my own.
The important thing is that the accessor can somehow (A) get a handle
to the native object, and (B) be able to convert to/from JS/C++ using
a consistent interface (as opposed to using IntegerValue(), ToString
(), etc., as those can't be used directly in a generic implementation.
If the type conversion framework supports transparent casting between
bound native types (the one demonstrated above does) then we can use
this to access, e.g.:
struct Foo
{
Foo * other; // Fine!
std::string bar; // Fine!
SomethingElse * something; // Fine if SomethingElse is also a
convertible type
};
:-D
--~--~---------~--~----~------------~-------~--~----~
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users
-~----------~----~----~----~------~----~------~--~---