#include "chrome/renderer/extensions/native_handler.h"
#include "base/memory/linked_ptr.h"
#include "base/logging.h"
#include "chrome/renderer/extensions/module_system.h"
#include "v8/include/v8.h"
namespace extensions {
NativeHandler::NativeHandler()
: object_template_(
v8::Persistent<v8::ObjectTemplate>::New(v8::ObjectTemplate::New())) {
}
NativeHandler::~NativeHandler() {
object_template_.Dispose();
}
v8::Handle<v8::Object> NativeHandler::NewInstance() {
return object_template_->NewInstance();
}
v8::Handle<v8::Value> NativeHandler::Router(const v8::Arguments& args) {
if (!ModuleSystem::IsPresentInCurrentContext()) {
return v8::ThrowException(v8::Exception::Error(
v8::String::New("ModuleSystem has been deleted")));
}
HandlerFunction* handler_function = static_cast<HandlerFunction*>(
args.Data().As<v8::External>()->Value());
return handler_function->Run(args);
}
void NativeHandler::RouteFunction(const std::string& name,
const HandlerFunction& handler_function) {
linked_ptr<HandlerFunction> function(new HandlerFunction(handler_function));
handler_functions_.push_back(function);
v8::Handle<v8::FunctionTemplate> function_template =
v8::FunctionTemplate::New(Router,
v8::External::New(function.get()));
object_template_->Set(name.c_str(), function_template);
}
void NativeHandler::RouteStaticFunction(const std::string& name,
const HandlerFunc handler_func) {
v8::Handle<v8::FunctionTemplate> function_template =
v8::FunctionTemplate::New(handler_func, v8::External::New(this));
object_template_->Set(name.c_str(), function_template);
}
}