Last active
July 31, 2018 09:00
-
-
Save darknoon/af7ee904573c1a1154987eb2b0c4e8f8 to your computer and use it in GitHub Desktop.
You can use ivars so you don't need to make so many hilarious classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Make a class with some handlers. | |
function Class(handlers){ | |
var uniqueClassName = "fetchDelegate_" + NSUUID.UUID().UUIDString(); | |
var cls = MOClassDescription.allocateDescriptionForClassWithName_superclass_(uniqueClassName, NSObject); | |
// Add each handler to the class description | |
for(var selectorString in handlers) { | |
var sel = NSSelectorFromString(selectorString); | |
cls.addInstanceMethodWithSelector_function_(sel, handlers[selectorString]); | |
} | |
// Add ivar to store instance-specific info | |
const ok = cls.addInstanceVariableWithName_typeEncoding("extraInfo", "@"); | |
return cls.registerClass(); | |
}; | |
const cls = Class({ | |
// Use this new syntax, but not arrow syntax to make sure we can still access the instance as this | |
"test"() { | |
log("extra = " + this.valueForKey("extraInfo")) | |
}, | |
}); | |
const instance = cls.new(); | |
// Slightly inelegant, can use properties to make it a bit shorter | |
instance.setValue_forKey({a:123}, "extraInfo"); | |
instance.test(); | |
/* Output | |
extra = { | |
a = 123; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment