Question

I'm having a context problem with jquery-file-upload and Backbone. In the fileupload 'done' callback, I want to call another function defined in the Backbone view, but I lose the context.

class MyBackboneView extends Backbone.view

    initialize_fileupload: ->
        $('form#my_form').fileupload
            done: (e, data) ->
                this.some_function()

    some_function: ->
        ...

The error returned in the browser console is "Uncaught TypeError: Object # has no method 'some_function'" because "this" no longer refers to the Backbone view, but the jquery form element.

Is there a way to access that function in the view from the callback?

Was it helpful?

Solution

Every function (->) has its own context (this). That includes done: (e, data) -> ..., as well as initialize_fileupload: -> .... And, in this case, they each have their own context value, so this.some_function() isn't referencing your view.

So, you'll have to define done to keep the surrounding context (the view). This can be done in CoffeeScript by defining it with the "fat arrow" (=>) instead:

initialize_fileupload: ->
    $('form#my_form').fileupload
        done: (e, data) =>
            this.some_function()

It can also be accomplished by storing the context value in a scoped variable:

initialize_fileupload: ->
    thisView = this
    $('form#my_form').fileupload
        done: (e, data) ->
            thisView.some_function()

Or by binding the function to the surrounding context:

initialize_fileupload: ->
    $('form#my_form').fileupload
        done: ((e, data) ->
            this.some_function()
        ).bind(this)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top