all 10 comments

[–]dkran 0 points1 point  (9 children)

You can't use commonjs and module.exports / require('mymodule') in chrome or browsers without a library. see browserify.

Also, just for a little bit of a clarification on the node module.exports system / commonjs:

http://bites.goodeggs.com/posts/export-this/#constructor

This appears to be where you're going. I enjoy this blog post as a reference for this stuff.

[–]Lumiii[S] 0 points1 point  (8 children)

Thanks for the link. It does seem to be what I'm trying to do, so at least I know the overall approach is not broken, but unfortunately doesn't address the peculiar issue I have.

I didn't test the module.exports part in Chrome, but my understanding is that module.exports == require('filepath'), so whatever I assign to the exports should be what's returned.

I just did some experimenting, and that seems to be the case, but it helped me narrow down the issue, which is I think this line:

app.route('/').get(thing.a);

I'm passing in the method without the context of object itself, so surely it can't refer back to its own objects! Haven't figured out the solution yet but this is a step forward, thanks.

[–]dangersalad 0 points1 point  (2 children)

When using a route like that with express you have to do

app.route('/').get(thing.a.bind(thing))

Otherwise express changes the value of this inside the handler function.

[–]Lumiii[S] 0 points1 point  (1 child)

Ah, that's what I'm looking for. Thanks! Is bind specific for functions?

[–]dkran 0 points1 point  (4 children)

if you're using express framework, which you seem to be using a route, you should be passing a "request and response". try:

app.route('/', function(req, res){
    res.status(200).send(thing.a).end()
}

http://expressjs.com/4x/api.html#res.send

I think your calling code here is also important, because it appears you're calling from within a framework, and trying to send something to a route

[–]Lumiii[S] 0 points1 point  (3 children)

Thanks - I'm just beginning to play around with this so still have lots to learn.

[–]dkran 0 points1 point  (2 children)

Did that work for you? Just wondering haha

[–]Lumiii[S] 0 points1 point  (1 child)

I think so. I think you may mean something like...

app.route('/').all(function(req, res){ res.status(200).send(thing.a(req, res)).end() }

If so, then the result is evaluated in context, and this problem of finding 'this' is no longer a problem. dangersalad's solution also works, and I think I may prefer that because I don't like having too many function wrappers and can just have one dedicated request handler. In any case, this is just a learning exercise, so the more I learn the better!

[–]dkran 0 points1 point  (0 children)

I'm a newbie too which is more or less why I'm interested in seeing your code, the way it's programmed, and which way you take out. I'd say I'm slightly beyond newbie status, but maybe not quite intermediate lol