Backbone.js的:从调用视图的初始化渲染()函数 [英] Backbone.js: calling render() from view's Initialize: function

查看:260
本文介绍了Backbone.js的:从调用视图的初始化渲染()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的观点来表现自己当第一次创建它,所以我打电话 this.render(); 初始化: 功能,这样(有些code删除):

I want to my view to render itself when it is first created, so I am calling this.render(); in the initialize: function, like this (some code removed):

var MyView = Backbone.View.extend({

    el: $("#mydiv"),

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

渲染:功能,我再通过子集合循环,并追加每个子元素的渲染视图:

In the render: function I'm then looping through a child collection, and appending the rendered views of each child element:

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

我遇到的问题是,提及这个在渲染功能(标有星号)设置为窗口,而不是 MyView的对象,而且它导致错误。

The problem I'm having is that that the reference to this in the render function (marked with asterisks) is set to window rather than the MyView object, and it's causing an error.

我假设我打电话渲染不正确(目前 this.render(); )。我应该怎么做这个,使这个上下文是preserved?

I assume I am calling render incorrectly (currently this.render(); ). How should I be doing this so that the this context is preserved?

推荐答案

保存这个之外的for循环。

Save this outside the for loop.

var that = this;

这个如果你使用 _不循环内传输。每个()

这篇关于Backbone.js的:从调用视图的初始化渲染()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆