如何使用“this”?在我的主干视图中

How do I use "this" in my Backbone View?

本文关键字:我的 视图 何使用 this      更新时间:2023-09-26
var homeView = Backbone.View.extend({
        el:  $("#main_container"),
        initialize: function(){
            _.bindAll(this, 'render');
        },
        render:function(){
            $.get('/home', {}, function(data){
                console.log(data);
                var tpl = _.template(home_container_temp, {});
                this.el.html(tpl);
            });
        }
    });

我想做一个ajax GET请求,然后设置数据。但是我不能这样做,因为我得到:

Uncaught TypeError: Cannot call method 'html' of undefined

$.get()里面的this没有指向视图

试题:

var homeView = Backbone.View.extend({
    el:  $("#main_container"),
    initialize: function(){
        _.bindAll(this, 'render');
    },
    render:function(){
        var $el = this.el;
        $.get('/home', {}, function(data){
            console.log(data);
            var tpl = _.template(home_container_temp, {});
            $el.html(tpl);
        });
    }
});

这是JavaScript的"动态this "功能,如果你想在回调中使用"this",请将其保留在回调之外的变量中:

render: function() {
    var _this = this; // keep it outside the callback
    $.get('/home', {}, function(data){
        console.log(data);
        var tpl = _.template(home_container_temp, {});
        // use the _this variable in the callback.
        _this.el.html(tpl);
    });
}