CoffeeScript 和 Backbone.js 未捕获的类型错误
Rails 应用程序,学习 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()}"
我遗漏了一些东西,但无法弄清楚什么......
Rails app, learning CoffeeScript and 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
Here is the code, 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()}"
I am missing something, but having trouble figuring out what...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
主干模型构造函数需要一个字典对象,其中包含将在该模型上设置的键和值。您没有提供对象,而是提供了 2 个字符串。该错误是由主干尝试迭代对象引起的,但由于无法合法地执行
for (key in "easy")
而导致爆炸。您也不应该使用模型数据的属性。您应该在实例化或
set()
和get()
上使用对象。因此,如果我可以更正您的代码:请参阅此处的示例: http://jsfiddle.net/NMkna/
请注意我们现在如何不再接受初始化中的参数。我们可以依靠backbone在模型中设置适当的属性,因为我们现在在创建游戏时传入一个对象。我们简单地定义
@get 'propname'
方法来检索这些值。Backbone model constructor functions expect a dictionary object with keys and values that will be set on that model. You didn't provide an object, and instead provided 2 strings. The error is cause by backbone trying to iterate through the object, but explodes because you can't legally do
for (key in "easy")
.You also shouldn't be using properties for model data. You should be using an object on instantiation or
set()
andget()
. So, if I may correct your code:See this example working here: http://jsfiddle.net/NMkna/
Note how we no longer accept arguments in initialize now. We can rely on backbone to set the proper attributes in the model, because we now pass in an object when creating the game. And the methods we define simply
@get 'propname'
in order to retrieve those values.