gpt4 book ai didi

javascript - 引用错误: todoItem is not defined Backbone + CoffeeScript

转载 作者:行者123 更新时间:2023-11-28 02:27:40 25 4
gpt4 key购买 nike

我正在尝试将主干与 CoffeeScript 一起使用,而不是 javascript:

TodoItem = Backbone.Model.extend(
toggleStatus: ->
if @.get 'status' is "incomplete"
@.set 'status': 'complete'
else
@.set 'status': 'incomplete'
@.save()
)

todoItem = new TodoItem(
description: 'I play the guitar'
status: 'incomplete'
id: 1
)

TodoView = Backbone.View.extend(
tagName: 'div'
id: "box"
className: 'red-box'

events:
"click h3": "alertStatus"
'change input': 'toggleStatus'

template:
_.template "<h3> <input type=checkbox #{ print "checked" if status is "complete"} /> <%= description %></h3>"

initialize: ->
@.model.on 'change', @.render, @
@.model.on 'destroy', @.remove, @

toggleStatus: ->
@.model.toggleStatus()

alertStatus: ->
alert('Hey you clicked the h3!')

remove: ->
@.$el.remove()

render: ->
@.$el.html @.template(@.model.toJSON())
)

todoView = new TodoView({model: todoItem})
todoView.render()
console.log todoView.el

如果我在控制台中尝试:

todoItem.set({description: 'asdfadfasdfa'});

我得到:

ReferenceError: todoItem is not defined

另外,我看不到我 body 内部的 div:

<div id="box" class="red-box">
<h3>
<input type="checkbox" undefined>
"I play the guitar"
</h3>
</div>

但是我可以在控制台中正常看到这个 div。

错误出在哪里?

谢谢!

最佳答案

CoffeeScript 的好处之一是您可以使用 @foo 而不是 @.foo。写得少一点,读起来好一点。

<小时/>

您不必使用 Backbone 的 .extend(),因为 CoffeeScript 具有以完全兼容的方式工作的类:

class TodoView extends Backbone.View
tagName: 'div'
id: 'box' # don't do this if you have more than one TodoView on the page at once
className: 'red-box'
<小时/>

todoItem 未定义,因为 CoffeeScript 会将所有代码包装在“立即执行的函数表达式”中,这可以防止将变量泄漏到全局范围(这是一件好事)。来自文档:

Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.

如果您想检查局部变量,请在 Chrome 的调试器或 Firebug 中设置断点。

<小时/>

我担心这段代码:

_.template "... #{ print "checked" if status is "complete"} ..."

什么是打印?你在哪里定义的?就此而言,status 在哪里?您的意思是@status吗?

<小时/>

最后,您看不到 div 的原因是您从未将其添加到 DOM 中。 .render() 渲染元素...但它不会自动将其插入到页面上。你必须自己做:

todoView.render()
$('body').append(todoView.el) # (or wherever you want it to go)

关于javascript - 引用错误: todoItem is not defined Backbone + CoffeeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14662337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com