Last active
January 2, 2016 00:09
-
-
Save marc-hughes/8221294 to your computer and use it in GitHub Desktop.
Some Dart Mixins I've been working on.
This file contains 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
library loggermixins; | |
import 'package:logging/logging.dart'; | |
import 'dart:mirrors'; | |
abstract class LoggerMixin { | |
Logger _log; | |
Logger get log { | |
if( _log == null ) { | |
InstanceMirror im = reflect(this); | |
ClassMirror cm = im.type; | |
_log = new Logger(MirrorSystem.getName(cm.simpleName) ); | |
} | |
return _log; | |
} | |
} |
This file contains 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
library jsonmixins; | |
import "dart:mirrors"; | |
abstract class JSONMixin { | |
Map toJSON() { | |
Map map = new Map(); | |
InstanceMirror im = reflect(this); | |
ClassMirror cm = im.type; | |
var declarations = cm.declarations.values.where((d) => d is VariableMirror); | |
declarations.forEach((d) { | |
var key = MirrorSystem.getName(d.simpleName); | |
var val = im.getField(d.simpleName).reflectee; | |
map[key] = val; | |
}); | |
return map; | |
} | |
void fromJSON(Map data) { | |
InstanceMirror im = reflect(this); | |
ClassMirror cm = im.type; | |
for(var fieldname in data.keys) { | |
Symbol field = new Symbol(fieldname); | |
if( cm.declarations.containsKey(field) ) { | |
im.setField(field, data[fieldname]); | |
} else { | |
print("Warning, $fieldname was ignored during fromJson"); | |
} | |
} | |
} | |
} | |
This file contains 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
import 'package:angular/angular.dart'; | |
import 'jsonmixin.dart'; | |
import '../util/loggermixin.dart'; | |
class Game extends Object with JSONMixin, LoggerMixin { | |
String key, url, created; | |
int id; | |
bool active; | |
var trainer; | |
var player; | |
Http http; | |
Game(this.http, this.key) { | |
} | |
void loadGame() { | |
http.get("/api/games/$key/") | |
.then((HttpResponse response) { | |
fromJSON(response.data); | |
log.info("Game loaded"); | |
}, | |
onError: (Object obj) { | |
print(obj); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment