Permalink
Browse files

Methods example

  • Loading branch information...
1 parent bae624f commit 90c8a4e06ddeaf027bc271dd4edaa007dcee2a46 @nikhilm committed Jan 18, 2012
Showing with 93 additions and 3 deletions.
  1. +63 −0 methods/main.cc
  2. +13 −0 methods/wscript
  3. +17 −3 slides.rst
View
@@ -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)
+}
View
@@ -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"
View
@@ -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
----------

0 comments on commit 90c8a4e

Please sign in to comment.