summaryrefslogtreecommitdiffstats
path: root/core/NSMutableDictionary+V8.mm
blob: 8653c25a1e744964792a2eb75b26f73046881738 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
//  NSMutableDictionary+V8.m
//  JMX
//
//  Created by Andrea Guzzo on 2/26/12.
//  Copyright (c) 2012 Dyne.org. All rights reserved.
//

#define __JMXV8__

#import "NSMutableDictionary+V8.h"
#import "NSDictionary+V8.h"

@implementation NSMutableDictionary (JMXV8)
using namespace v8;

static v8::Handle<Value> MapSet(Local<String> name, Local<Value> value, const AccessorInfo &info)
{
    v8::Locker lock;
    HandleScope handleScope;
    NSMutableDictionary *dict = (NSMutableDictionary *)info.Holder()->GetPointerFromInternalField(0);
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if (dict && [dict isKindOfClass:[NSMutableDictionary class]]) {
        String::Utf8Value nameStr(name);
        NSString *key = [NSString stringWithUTF8String:*nameStr];
        id obj = (id)value->ToObject()->GetPointerFromInternalField(0);
        if (obj) {
            [dict setObject:obj forKey:key];
        }
    }
    [pool release];
    return Undefined();
}

static v8::Handle<Value> MapGet(Local<String> name, const AccessorInfo &info)
{
    v8::Locker lock;
    HandleScope handleScope;
    NSDictionary *dict = (NSDictionary *)info.Holder()->GetPointerFromInternalField(0);
    if (dict && [dict isKindOfClass:[NSDictionary class]]) {
        String::Utf8Value nameStr(name);
        NSString *key = [NSString stringWithUTF8String:*nameStr];
        id obj = [dict objectForKey:key];
        if ([obj respondsToSelector:@selector(jsObj)])
            return handleScope.Close([obj jsObj]);
    }
    return handleScope.Close(Undefined());
}

static Persistent<FunctionTemplate> objectTemplate;

+ (v8::Persistent<FunctionTemplate>)jsObjectTemplate
{
    //v8::Locker lock;
    if (!objectTemplate.IsEmpty())
        return objectTemplate;
    objectTemplate = v8::Persistent<FunctionTemplate>::New(FunctionTemplate::New());
    //objectTemplate->Inherit([NSDictionary jsObjectTemplate]);
    objectTemplate->SetClassName(String::New("MutableDictionary"));
    v8::Handle<ObjectTemplate> classProto = objectTemplate->PrototypeTemplate();
    // set instance methods
    v8::Handle<ObjectTemplate> instanceTemplate = objectTemplate->InstanceTemplate();
    instanceTemplate->SetInternalFieldCount(1);
    
    instanceTemplate->SetNamedPropertyHandler(MapGet, MapSet);
    /*
     if ([self respondsToSelector:@selector(jsObjectTemplateAddons:)])
     [self jsObjectTemplateAddons:objectTemplate];
     */
    NSDebug(@"NSDictionary objectTemplate created");
    return objectTemplate;
}
@end