From 90c8a4e06ddeaf027bc271dd4edaa007dcee2a46 Mon Sep 17 00:00:00 2001 From: Nikhil Marathe Date: Wed, 18 Jan 2012 23:32:43 +0530 Subject: [PATCH] Methods example --- methods/main.cc | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ methods/wscript | 13 ++++++++++ slides.rst | 20 +++++++++++++--- 3 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 methods/main.cc create mode 100644 methods/wscript diff --git a/methods/main.cc b/methods/main.cc new file mode 100644 index 0000000..f3d7606 --- /dev/null +++ b/methods/main.cc @@ -0,0 +1,63 @@ +#include +#include +using namespace v8; + +Handle Inventory(const Arguments &args) { + return args.This(); +} + +Handle AddStock(const Arguments &args) { + HandleScope scope; + + Handle This = args.This(); + + int items = This->Get(String::New("items"))->Uint32Value(); + + items += args[0]->Uint32Value(); + + This->Set(String::New("items"), Integer::New(items)); + + return Undefined(); +} + +Handle Ship(const Arguments &args) { + HandleScope scope; + + Handle This = args.This(); + int items = This->Get(String::New("items"))->Uint32Value(); + + int orders = args[0]->Uint32Value(); + + if (items < orders) + return ThrowException(String::New("Not enough items")); + + This->Set(String::New("items"), Integer::New(items - orders)); + + return Undefined(); +} + +extern "C" { + static void Init(Handle target) { + HandleScope scope; + + Handle inventoryTpl = + FunctionTemplate::New(Inventory); + + Handle instance = + inventoryTpl->InstanceTemplate(); + + instance->Set(String::New("items"), Integer::New(257)); + + // operating on inventoryTpl->PrototypeTemplate() + NODE_SET_PROTOTYPE_METHOD(inventoryTpl, + "addStock", + AddStock); + NODE_SET_PROTOTYPE_METHOD(inventoryTpl, + "ship", + Ship); + + target->Set(String::NewSymbol("Inventory"), + inventoryTpl->GetFunction()); + } + NODE_MODULE(methods, Init) +} diff --git a/methods/wscript b/methods/wscript new file mode 100644 index 0000000..2484e80 --- /dev/null +++ b/methods/wscript @@ -0,0 +1,13 @@ +import Options + +def set_options(opt): + opt.tool_options("compiler_cxx") + +def configure(conf): + conf.check_tool("compiler_cxx") + conf.check_tool("node_addon") + +def build(bld): + obj = bld.new_task_gen("cxx", "shlib", "node_addon") + obj.target = "methods" + obj.source = "main.cc" diff --git a/slides.rst b/slides.rst index 3335ccd..18f0522 100644 --- a/slides.rst +++ b/slides.rst @@ -198,10 +198,24 @@ Simple objects .. code-block:: cpp :include: simpleobject/main.cc - :start-at: static void - :end-at: } + :start-at: static void Init + :end-before: NODE_MODULE + +Methods +------- + +.. code-block:: js + + Inventory.prototype.addStock = function(newStock) { + this.items += newStock; + } -TODO fix indentation in inclusion + Inventory.prototype.ship = function(orders) { + if (this.items < orders) + throw Exception("Not enough items"); + + this.items -= orders + } ObjectWrap ----------