-
Notifications
You must be signed in to change notification settings - Fork 11
/
MochaJSDelegate.js
80 lines (57 loc) · 2.04 KB
/
MochaJSDelegate.js
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
74
75
76
77
78
79
80
//
// MochaJSDelegate.js
// MochaJSDelegate
//
// Created by Matt Curtis
// Copyright (c) 2015. All rights reserved.
//
var MochaJSDelegate = function(selectorHandlerDict){
var uniqueClassName = "MochaJSDelegate_DynamicClass_" + NSUUID.UUID().UUIDString();
var delegateClassDesc = MOClassDescription.allocateDescriptionForClassWithName_superclass_(uniqueClassName, NSObject);
delegateClassDesc.registerClass();
// Handler storage
var handlers = {};
// Define interface
this.setHandlerForSelector = function(selectorString, func){
var handlerHasBeenSet = (selectorString in handlers);
var selector = NSSelectorFromString(selectorString);
handlers[selectorString] = func;
if(!handlerHasBeenSet){
/*
For some reason, Mocha acts weird about arguments:
https://github.com/logancollins/Mocha/issues/28
We have to basically create a dynamic handler with a likewise dynamic number of predefined arguments.
*/
var dynamicHandler = function(){
var functionToCall = handlers[selectorString];
if(!functionToCall) return;
return functionToCall.apply(delegateClassDesc, arguments);
};
var args = [], regex = /:/g;
while(match = regex.exec(selectorString)) args.push("arg"+args.length);
dynamicFunction = eval("(function("+args.join(",")+"){ return dynamicHandler.apply(this, arguments); })");
delegateClassDesc.addInstanceMethodWithSelector_function_(selector, dynamicFunction);
}
};
this.removeHandlerForSelector = function(selectorString){
delete handlers[selectorString];
};
this.getHandlerForSelector = function(selectorString){
return handlers[selectorString];
};
this.getAllHandlers = function(){
return handlers;
};
this.getClass = function(){
return NSClassFromString(uniqueClassName);
};
this.getClassInstance = function(){
return NSClassFromString(uniqueClassName).new();
};
// Conveience
if(typeof selectorHandlerDict == "object"){
for(var selectorString in selectorHandlerDict){
this.setHandlerForSelector(selectorString, selectorHandlerDict[selectorString]);
}
}
};