1

So I am calling a function within a view when a user clicks a button. This function requires a callback function. I have the callback defined within the same view. When The callback is called I want to render the current view with the additional info just obtained. However it seems like you lose scope within the callback function so that I get an error when calling this.render(); Saying "global object has not method render". So 'this' now refers to the window object. How do I retain scope within my view? So here is an example of what Im talking about.

var profileView = Parse.View.extend({
    events: {
        "click #scan_item": "scanItem"
    },
    scanItem: function(){
        ScanItem(callback);
    },
    callback: function(info){
        this.render(info);
    },
    render: function(info){
        $(this.el).html(this.template({info: info}));
        return this;
    }
});
hugomg
  • 68,213
  • 24
  • 160
  • 246
David
  • 65
  • 1
  • 2
  • 8
  • Please show the code tat is calling the callback. Also, what is that `callback` variable in `ScanItem(callback)`? – hugomg Feb 04 '14 at 02:45
  • if you take callback out of the literal, you can bind it to the literal so that "this" refers to the literal. – dandavis Feb 04 '14 at 03:43
  • Ya thanks Bergi I guess it was a duplicate. I fixed it using .bind() – David Feb 05 '14 at 00:38

1 Answers1

1

You need to bind your callback to the correct 'this'

Might work:

ScanItem(this.callback.bind(this))

(I don't know if this framework has a bind function)

Otherwise, old school :) Keep this in a variable in the enclosing scope

var that=this;
ScanItem(function(info){
  that.callback(info)
});

Why does the function passed to scanItem need to be defined as though it was a "method"? And should it have to know about the arguments being passed - why not just pass them all?

var that=this;
ScanItem(function(){
  that.render.apply(that,arguments);
});
Jon Cooke
  • 92
  • 3
  • Thanks for the response. using .bind() did it. ScanItem is a method I was just trying to make a quick example but maybe should have written it explicitly. It is a google api method. Looks like service.nearbySearch(request, callback); – David Feb 05 '14 at 00:37