Search code examples
javascriptbackbone.jsmarionette

backbone marionette pass variable to view method


I have simple situation and can't understand why variable that I pass to function always undefined.

var ProjectItemView = Backbone.Marionette.ItemView.extend({
        template: "#ProjectItemTemplate",

        initialize: function () {

            var id = this.model.get('project_id');

            $.getJSON('service/api.php/projects/' + id + '/progress').done(function (data) {

                 this.renderProgress('4'); //<== pass here
            });

        },

        renderProgress: function (why) {
            alert(why);  //<== undefined
        ...
        },
    ...
});

I expect that it equals '4'. In next step I want to pass "data" but now I realize that I can't pass anything.


Solution

  • You loose the context in $.getJSON done callback. Try this:

    var ProjectItemView = Backbone.Marionette.ItemView.extend({
            template: "#ProjectItemTemplate",
    
            initialize: function () {
    
                var id = this.model.get('project_id');
                var _this = this;
    
                $.getJSON('service/api.php/projects/' + id + '/progress').done(function (data) {
    
                    _this.renderProgress('4'); //<== pass here
                });
    
            },
    
            renderProgress: function (why) {
                alert(why);  //<== undefined
            ...
            },
        ...
    });