Skip to content

Commit

Permalink
Methods example
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhilm committed Jan 18, 2012
1 parent bae624f commit 90c8a4e
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 3 deletions.
63 changes: 63 additions & 0 deletions methods/main.cc
@@ -0,0 +1,63 @@
#include <v8.h>
#include <node.h>
using namespace v8;

Handle<Value> Inventory(const Arguments &args) {
return args.This();
}

Handle<Value> AddStock(const Arguments &args) {
HandleScope scope;

Handle<Object> 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<Value> Ship(const Arguments &args) {
HandleScope scope;

Handle<Object> 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<Object> target) {
HandleScope scope;

Handle<FunctionTemplate> inventoryTpl =
FunctionTemplate::New(Inventory);

Handle<ObjectTemplate> 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)
}
13 changes: 13 additions & 0 deletions 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"
20 changes: 17 additions & 3 deletions slides.rst
Expand Up @@ -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
----------
Expand Down

0 comments on commit 90c8a4e

Please sign in to comment.