Created
February 12, 2012 15:19
-
-
Save dvdsgl/1809026 to your computer and use it in GitHub Desktop.
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
fs = require 'fs' | |
class MyClass | |
# Trying to create middleware with access to class members. | |
withData: (cb) -> | |
return cb @__data if @__data? | |
fs.readFile 'datafile.json', (err, json) => | |
throw err if err? | |
@__data = JSON.parse json | |
cb @__data | |
getUsers: (n) -> @withData (data) => | |
data.users[..n-1] | |
x = new MyClass | |
console.log x.getUsers 5 |
Try withData =
instead of withData:
so it will be defined as a method in the MyClass closure scope, and not an instance method for the MyClass object.
@tdreyno What if I want to access the instance within withData
? I want @__data
to be per-instance, for example.
Also, this
is no longer bound to the instance within getUsers
when defined via the class method.
Why so much magic? Why not just call withData
from inside the function?
In my actual use case, I have many functions that rely on async data and I just wanted to avoid the extra level of indentation.
@tdreyno, I found a less magical version that works – it's just what you recommended except I call the 'middleware' right after the argument list.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The problem is that
@withData
is undefined whengetUsers
is created.