簡體   English   中英

Backbone.js:從視圖的Initialize:函數調用render()

[英]Backbone.js: calling render() from view's Initialize: function

我希望我的視圖在第一次創建時呈現自己,所以我調用this.render(); initialize: function中,這樣(刪除了一些代碼):

var MyView = Backbone.View.extend({

    el: $("#mydiv"),

    initialize: function() {
        this.render();
    }
...

render: function中,我然后循環遍歷子集合,並附加每個子元素的渲染視圖:

render: function() {
    this.model.somecollection.forEach(function(c) {
        var view = new ChildView({ model: c });
        this.el.append(view.render().el); //*****
    });
    return this;
},

我遇到的問題是,在渲染函數(用星號標記)中this的引用設置為window而不是MyView對象,並且它導致錯誤。

我假設我正在調用渲染錯誤(目前this.render(); )。 我該怎么做才能保留this上下文?

this保存在for循環之外。

var that = this;

this如果你用的是不運循環內_.each()

在Javascript中,當你進入一個新的功能背景下,價值this可能已經改變。 所有你需要做的是存儲的值this輸入函數之前:

render: function() {
    var self = this;
    this.model.somecollection.forEach(function(c) {
        var view = new ChildView({ model: c });
        self.el.append(view.render().el); //*****
    });
    return this;
},

這是我們在這里使用它的方式,

這樣,初始化時仍會調用render。

ContactView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // we use underscsore templating, this just gives a chunk of html
        var template = _.template( $("#search_template").html(), {} );
        // and we load that template html into the Backbone "el"
        this.el.html( template );
    }
});

我們在創建視圖時將'el'賦予視圖,並且render函數將html插入到該元素中。

var contact_view = new ContactView({ el: $("#contact-list") });

在匿名函數的上下文中,這指的是全局范圍。 如果您希望以您編寫的方式使用代碼,則需要明確地保留它。 假設你的頁面中有jquery:$ .proxy函數可以使用:


this.model.somecollection.forEach($.proxy(function(c) {
        var view = new ChildView({ model: c });        
        this.el.append(view.render().el);
 },this));

或者,下划線有一個_.bind函數,它以類似的方式工作。 此外,如果您定義局部變量並將其分配給匿名函數外部,則可以在匿名函數內使用它代替此函數。

如果somecollection是Backbone.Collection你應該能夠說:

this.model.somecollection.each(..., this);

最后一個參數是要在函數內使用的上下文。

暫無
暫無

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

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