【问题标题】:Cannot read property ... of undefined in backbone无法读取骨干中未定义的属性...
【发布时间】:2013-05-07 10:40:05
【问题描述】:

我正在尝试将我用 raphael.js 制作的这个简单项目转换为使用backbone.js,但我一直遇到同样的错误,我不知道为什么。在我的模型中的函数中,我尝试使用“this”访问变量,但我仍然收到此错误“无法读取未定义的属性“长度””,例如一个数组。我的模型看起来像这样:

GameModel = Backbone.Model.extend({
        defaults: {

            spawnId: '',
            gameloopId: '',
            checkId: '',
            goingUp: false,
            counter: 0,     
            recentscores: [],
            enemies: '',
            speed: -4,
            score: 0,
            health: 100,
            paper: '',
            t: '',
            h: '',
            c: '',
            circle: ''

        },
        initialize: function(){

            this.enemies = [];
            this.paper = new Raphael($('#canvas'), 0, 0);
            this.circle = this.paper.circle(100, 50, 30);
            this.t = this.paper.text(1000, 50, "Score: " + this.score);
            this.h = this.paper.text(50, 50, "Health: " + this.health);
            this.c = this.paper.image("background.png", 0, 0, 2400, 800);
            this.paper.setSize(1200,800);
            this.circle.attr({fill: '#9cf', stroke: '#ddd', 'stroke-width': 5});
            this.t.attr({ "font-size": 20, "font-family": "Arial, Helvetica, sans-serif" });
            this.h.attr({ "font-size": 20, "font-family": "Arial, Helvetica, sans-serif" });
        },

【问题讨论】:

  • 这些“你的模型中的函数”是什么样的,你怎么称呼它们?另外,defaults 中的 recentscores 是个坏主意,默认值是浅拷贝的,所以每个人最终都会共享对同一个数组的引用。
  • @muistooshort,它们只是试图访问模型中定义的变量的函数。我有一个条件为“i 的 for 循环
  • 当然可以,但是它们怎么称呼?通常,this 的值取决于函数的调用方式,而不是定义的方式或位置。并将您的 defaults 对象更改为返回默认值的 defaults 函数。
  • @muistooshort,哦,嗯,我没有考虑到这一点。大多数函数是从其他函数中调用的。我有一个启动函数,我在创建模型实例后调用它,并启动调用更新等。这可能是问题吗?我不确定我什至如何访问这些变量。使用吸气剂?
  • 在 jsfiddle.net 或 jsbin.com 上的最小演示可能会让问题变得很清楚。

标签: javascript jquery backbone.js raphael


【解决方案1】:

为此:

this.enemies = [];

也许你应该尝试使用

this.set("enemies", [])

this.circle = this.paper.circle(100, 50, 30);

this.set("circle", this.get("paper").circle(100, 50, 30))

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 2013-05-27
    • 2013-11-23
    • 1970-01-01
    • 2014-11-02
    • 2018-11-13
    • 2013-09-06
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多