-
22-10-2019 - |
题
这应该是关于backbone.js的一个非常基本的问题,我是javascript/backbone.js的完整初学者,我已经阅读了几个教程,但是我没有设法执行一个相当简单的任务:数据库”。
整个应用程序都在Google App Engine上。数据库已经包含了几个条目“单词”,我使用烧瓶发送条目的JSON表示。
这是我用于此任务的功能:
@wordbook.route('/words', methods=('GET', 'POST'))
def wordlist():
return retrieve_words()
def retrieve_words():
content = json.dumps([word.to_dict() for word in Word.all()])
response = make_response(content)
response.mimetype = 'application/json'
return response
因此,据我了解程序的工作方式,我的骨干应用程序将是网站的根源,他将要求“/wiss” URL以某种格式从数据库中获取一些数据,称为JSON,因此该应用程序可以自由使用。
我假设URL http://localhost:8080/words
是正确的,因为输出为以下:
[{"word": "keyboard", "key": "ahB2b2NhYnVsYXJpdW0tYXBwcgoLEgRXb3JkGAEM", "language": "en", "nature": "noun", "usage": "Plural keyboards", "gender": ""}, {"word": "keyboard", "key": "ahB2b2NhYnVsYXJpdW0tYXBwcgoLEgRXb3JkGBoM", "language": "en", "nature": "verb", "usage": "Regular verb", "gender": ""}, {"word": " mouse", "key": "ahB2b2NhYnVsYXJpdW0tYXBwcgoLEgRXb3JkGB4M", "language": "en", "nature": "noun", "usage": "Plural mousemice", "gender": ""}, {"word": " mouse", "key": "ahB2b2NhYnVsYXJpdW0tYXBwcgoLEgRXb3JkGDIM", "language": "en", "nature": "verb", "usage": "Regular verb", "gender": ""}, {"word": " hard", "key": "ahB2b2NhYnVsYXJpdW0tYXBwcgoLEgRXb3JkGDoM", "language": "en", "nature": "adj", "usage": "Comparative harder, superlative hardest", "gender": ""}...]
在网站的根源上,我有一个空白的网页(我想首先从非常简单的任务开始),其中一个简单的JavaScript文件(以及依赖项,JSON2,jQuery,jquery,underscore和Backbone)。
我是JavaScript的初学者,所以我使用了CoffeeScript,因为该语法与我在Python中真正知道的相对相似,因此我认为学习曲线的陡峭幅度不那么陡峭。这是我的咖啡文件:
class Word extends Backbone.Model
class WordList extends Backbone.Collection
model: Word
url: 'words'
Words = new WordList
class WordView extends Backbone.View
tagName: 'p'
render: ->
word = @model.get 'word'
$(@el).html word
@
class WordListView extends Backbone.View
el: $ 'body'
initialize: ->
_.bindAll @, 'addOne', 'addAll'
Words.bind 'add', @addOne
Words.bind 'refresh', @addAll
Words.fetch()
addOne: (word) ->
view = new WordView model: word
@.$ 'body'.append view.render().el
addAll: ->
Words.each @addOne
-> WordList = new WordListView
为了总结我在这里写的内容,我创建了一个名为Word的模型,以及一个包含所有单词的集合。该集合应使用JSON URL从服务器获取所有数据。每个单词都可以用自己的特定视图(WordView)呈现,在段落p。在应用程序视图(WordListView)中,我只需将添加操作绑定到addone函数,以及对Addall函数的刷新操作。我现在尝试获取所有单词。 Addone函数创建了相应单词的新视图,并将一个应包含该单词的新段落附加到身体上。每次添加一个新单词时,绑定都会触发addone函数,从而呈现每个单词。
我不知道我是否有正确的思考方法。
解决方案
如果我正确理解您的问题,您正在尝试理解为什么 Words
运行时不会填充 Words.fetch()
. 。我有几个问题要问你:
- 什么价值是
WordList.url
?它应该是"/words"
为您的例子。 - 这 提取方法 接受
success
和error
回调...
这意味着您可以如下调试(假设您的浏览器具有开发人员控制台):
Words.fetch
success: (collection, response) -> console.log "success: #{response}"
failure: (collection, response) -> console.log "failure: #{response}"
当您这样做时,您在控制台中看到了什么?