tlnagy tlnagy - 1 year ago 85
CoffeeScript Question

Scoping issue with callbacks in coffeescript

I'm really new to Coffeescript/Javascript and I'm writing a little package for Atom. I have no idea why the

function is not visible to the inner function. I suspect there is some kind of scoping problem going on,

{CompositeDisposable, Directory, File} = require 'atom'

module.exports = ImageAssistant =
subscriptions: null

activate: (state) ->
# Events subscribed to in atom's system can be easily cleaned up
# with a CompositeDisposable
@subscriptions = new CompositeDisposable

# Register command that toggles this view
@subscriptions.add atom.workspace.observeTextEditors((editor) ->
textEditorElement = atom.views.getView(editor)

# on drag and drop event
textEditorElement.addEventListener("drop", (e) ->

editor = atom.workspace.getActiveTextEditor()
return unless editor

dropped_files = e.dataTransfer.files
target_file = editor.getPath()

fs = require 'fs'
path = require 'path'
crypto = require "crypto"

assets_path = path.join(target_file, "..", "assets")

for f in dropped_files
if fs.lstatSync(f.path).isFile()
buffer = new Buffer(fs.readFileSync(f.path))
md5 = crypto.createHash 'md5'

img_filename = "#{path.parse(target_file).name}-#{md5.digest('hex').slice(0,8)}#{path.extname(f.path)}"
console.log img_filename

assets_dir = new Directory(assets_path)

@create_dir assets_dir, ()=>
fs.writeFile path.join(assets_dir, img_filename), buffer, 'binary', ()=>
console.log "Copied file over to #{assets_dir}"
editor.insertText "![](#{path.join("assets", img_filename)})"

return false

create_dir: (dir_path, callback)=>
dir_handle = new Directory(dir_path)

dir_handle.exists().then (existed) =>
if not existed
dir_handle.create().then (created) =>
if created
console.log "Creation of #{dir_path} successful"

deactivate: ->

The error I'm getting: Uncaught TypeError: _this.create_dir is not a function(anonymous function) @
/Applications/ GET 404 (Not Found)send @ /Applications/ @ /Applications/ function) @ /Applications/ @ /Applications/ @ /Applications/ @ /Applications/…:204NotificationElement.render @ /Applications/…:159NotificationElement.initialize @ /Applications/…:50(anonymous function) @ /Applications/ @ /Applications/ @ /Applications/ @ /Applications/ function) @ /Applications/ @ /Applications/ @ /Applications/ @ /Applications/ @ /Applications/ function) @ /Applications/ @ /Applications/ @ /Applications/ function) @ /Applications/

I've tried changing all
as suggested here: Multiple Callbacks in CoffeeScript but that didn't fix my issue with the function being undefined.

Answer Source

This is due to using a plain object instead of class, see @muistooshort's answer here: Anonymous function works as callback but defined function does not

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download