为什么把骨干和车把的情况下进入初始化函数删除错误? [英] Why does putting Backbone and Handlebar's context into initialize function remove error?

查看:222
本文介绍了为什么把骨干和车把的情况下进入初始化函数删除错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty相信这是一个一般的JS问题,并不仅仅局限于骨干,但我遇到了这个,因为我是学习骨干。在下面的第一个例子,我没有得到一个错误,但是这不是第二个例子是一样的。你能解释一下到底是怎么回事,让Chrome浏览器开发工具显示在后者的例子错误,但不是第一个在幕后。我最好的猜测是,当某事是在一个功能(如初始化),它不会马上作为浏览器正在读取,而如果它是被定义的类的一部分的脚本运行(在此情况下,app.ItemView) ,对象上下文需要完成这样浏览器就需要通读this.model#,以建立上下文对象得到的。

I'm pretty sure this is a general JS question and not just limited to Backbone but I encountered this as I was learning Backbone. In the first example below, I don't get an error but that's not the same for the 2nd example. Can you explain what is going on behind the scenes that makes Chrome Dev Tools show the error in the latter example but not the first. My best guess is that when something is in a function (such as initialize), it doesn't get run right away as the browser is reading the script whereas if it's part of the class being defined (in this case, app.ItemView), the object context needs to be completed so the browser will need to read through this.model#get in order to build the context object.

app.ItemView = Backbone.View.extend({
    initialize: function() {
        this.context = {
            title: this.model.get("title"),
            completed: this.model.get("completed")
        }
    }
});

VS

app.ItemView = Backbone.View.extend({
    context: {
        title: this.model.get("title"),
        completed: this.model.get("completed")
    }
});

未捕获类型错误:无法读取属性'得到'未定义

编辑:它也不会工作,如果在第一个例子情况下未适当定义 -

app.ItemView = Backbone.View.extend({
    initialize: function() {
        this.context.title = this.model.get("title");
        this.context.completed = this.model.get("completed");
        this.render();
    }
});

未捕获类型错误:无法读取属性'得到'未定义

推荐答案

修改更正的说明这个看完亩太短的评论。

EDIT Corrected explanation of this after reading mu is too short's comment.

该错误的主要原因是这个在你的第二件code的可参考窗口或其中 Backbone.View.extend 被调用函数的调用者。

The main reason for the error is that this in your second piece of code could refer to window or the caller of a function where Backbone.View.extend is being called.

这对象不具有<​​code>模式属性,所以它的未定义并调用获得上的误差未定义的结果。

That object doesn't have a model property, so it's undefined and calling get on undefined results in the error.

您需要让初始化函数,因为它会presumably由Backbone.View对象调用,它确实有模型可获得的财产。在这种情况下,这个将引用Backbone.View对象。

You need to make initialize a function because it will presumably be called by a Backbone.View object, which does have the model property available to it. In that context, this would refer to the Backbone.View object.

这篇关于为什么把骨干和车把的情况下进入初始化函数删除错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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