Created
July 17, 2013 14:42
-
-
Save thomasboyt/6021224 to your computer and use it in GitHub Desktop.
weird rails-y findBy method in JS
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
| var myClassCollection = []; | |
| var _MyClass = function(id, foo) { | |
| this.id = id; | |
| this.foo = foo; | |
| // some sort of arbitrary storage thing | |
| this.collection[id] = this; | |
| } | |
| _MyClass.prototype.collection = myClassCollection; | |
| var MyClass = new Proxy(_MyClass, { | |
| get: function(target, name) { | |
| var match = /^findBy_(.*)/.exec(name); | |
| if (match) { | |
| name = match[1]; | |
| return function(query) { | |
| return this.prototype.collection.filter(function(item) { | |
| return item[name] == query; | |
| }); | |
| }.bind(target); | |
| } | |
| return target[name]; | |
| } | |
| }); | |
| var instance = new MyClass(5, "bar"); | |
| console.log(MyClass.findBy_id(5)); | |
| console.log(MyClass.findBy_foo("bar")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment