keithamus / jwerty

⌨ Awesome handling of keyboard events
http://keithamus.github.io/jwerty
Other
1.21k stars 107 forks source link

Don't override real global object #31

Closed kossnocorp closed 11 years ago

kossnocorp commented 11 years ago

Example of problem:

For code:

$ = global.$ = global.jQuery = require('jquery')
jwerty = require('jwerty').jwerty

// ...

jwerty.fire('esc', $el)

I've got: "TypeError: Expecting a function in instanceof check, but got [object Object]".

When I put console output to this code:

(function (global, exports) {

    console.log('#######')
    console.log('Global:')
    console.log(global)
    console.log('jQuery:')
    console.log(global.jQuery)
    console.log('#######')

    // Helper methods & vars:
    var $d = global.document
    ,   $ = (global.jQuery || global.Zepto || global.ender || $d)
    ,   $$
    ,   $b
    ,   ke = 'keydown';

    // ...

Output:

#######
Global:
{}
jQuery:
undefined
#######

This happen because this != global in require:

$ node
> this === global
true

but

$ cat example.js                                                                                                                                                                                console.log(this === global)
$ node
> require('./example')
false
keithamus commented 11 years ago

What require library are you using? RequireJS?

kossnocorp commented 11 years ago

Nope, it just pure Node.js.

kossnocorp commented 11 years ago

How I use it: https://github.com/kossnocorp/backbone.jwerty/blob/master/spec/backbone.jwerty_spec.coffee#L10

keithamus commented 11 years ago

I dont really understand the use case for this. Can you explain precisely how you are intending to use DOM based keyboard events inside NodeJS?

kossnocorp commented 11 years ago

@keithamus I'm using Node.js to run autotests in console. I'm emulate DOM via jsdom library so I don't have to manually run tests in browser.

keithamus commented 11 years ago

Aside from my urge to tell you that that is probably a bad idea, and you should consider using PhantomJS or a real browser via something like Selenium instead, I have to close this pull request because your code actually breaks in a real browser environment, as Uncaught ReferenceError: global is not defined.

You would instead need a ternary like typeof global === 'undefined' ? this : global