S
S
Sergey Pronin2016-12-02 22:14:23
JavaScript
Sergey Pronin, 2016-12-02 22:14:23

How to stop using that?

Standard situation

//backbone
render: function () {
        var that = this;
        App.TemplateManager.get(this.template, function (template) {
            var temp = _.template(template);
            var html = $(temp(that.model.toJSON()));
            that.$el.html(html);
        });
        return this;
    },

or
//jquery
var that = this;
$.ajax({
    url: '/api/' + id,
    success: function (template) {
        var tmpl = template;
        that.templates[id] = tmpl;
        callback(tmpl);
   }
});

How to get rid of that? I know that it is necessary to use call/apply/bind here, but I don’t understand how to do it right...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Semenko, 2016-12-02
@abler98

$.ajax({
    url: '/api/' + id,
    success: function (tmpl) {
        this.templates[id] = tmpl;
        callback(tmpl);
    }.bind(this) // <==
});

V
Vladimir Sergeevich, 2016-12-02
@VladimirZhid

One can only shorten its use with arrow functions

class NewObj{
    constructor(){
        this.some_var = "Some var"
        this.func()
    }
    func(){
        let sub_func = () => {
            console.log(this)
        }
        sub_func()
    }
}

new NewObj();
// В терминале:
// node test.js
// -> NewObj { some_var: 'Some var' }

A
Anton, 2016-12-03
@SPAHI4

  • Arrow function
  • .bind(this)
  • :: operator (only in babel)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question