CoffeeScript和Backbone.js的未捕获类型错误

时间:2012-01-25 18:13:03

标签: ruby-on-rails-3.1 backbone.js coffeescript

Rails app,学习CoffeeScript和Backbone.js:

Uncaught TypeError: Cannot use 'in' operator to search for 'id' in easy
_.extend.setbackbone.js:205
Backbone.Modelbackbone.js:142
Gamegames.js:13
(anonymous function)games.js:34
jQuery.Callbacks.firejquery.js:1047
jQuery.Callbacks.self.fireWithjquery.js:1165
jQuery.extend.readyjquery.js:436
DOMContentLoadedjquery.js:924

以下是代码,games.js.coffee

jQuery ->
  root = global ? window
  class Game extends Backbone.Model
    initialize: (@n, @diff) ->
      console.log "--> Game.initialize()"
    difficulty: ->
      @diff
    name: ->
      @n
  # Make class Game globally available
  root.Game = Game
  my_game = new Game('easy', 'hard')
  console.log "my_game.name(), my_game.difficulty() --> #{my_game.name()}, #  {my_game.difficulty()}"

我遗失了一些东西,但却无法弄清楚是什么......

1 个答案:

答案 0 :(得分:2)

Backbone模型构造函数需要一个字典对象,其中包含将在该模型上设置的键和值。您没有提供对象,而是提供了2个字符串。这个错误是由于主干试图遍历对象而引起的,但是因为你不能合法地做for (key in "easy")而爆炸。

您也不应该使用模型数据的属性。您应该在实例化时使用对象或set()get()。所以,如果我可以纠正你的代码:

jQuery ->
  root = global ? window
  class Game extends Backbone.Model
    initialize: ->
      console.log "--> Game.initialize()"
    difficulty: ->
      @get 'diff'
    name: ->
      @get 'n'
  # Make class Game globally available
  root.Game = Game
  my_game = new Game n: 'easy', diff: 'hard'
  console.log "my_game.name(), my_game.difficulty() --> #{my_game.name()}, #{my_game.difficulty()}"

请参阅此示例:http://jsfiddle.net/NMkna/

注意我们现在不再接受初始化中的参数。我们可以依靠骨干在模型中设置适当的属性,因为我们现在在创建游戏时传入一个对象。我们定义的方法只是@get 'propname',以便检索这些值。