簡體   English   中英

如何在骨干網視圖中使用“ this”?

[英]How do I use “this” in my Backbone View?

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

this里面的$.get()是不是指的視圖。

嘗試:

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);
        });
    }
});

這是“動態this ”的JavaScript功能,如果要在回調中使用“ 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);
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM