私はバックボーンをよりよく学ぶための基本的な調査アプリの作成に取り組んでいます。ユーザーが特定の調査を1回だけ受けることができるように取り組んでいます。私はこれをレール側に構築しましたが、同じユーザーが同じ調査を再度実行しようとするとエラーが返されます。
成功関数とエラー関数は正しく呼び出されます。私が遭遇している問題は、@ saveSurveyを呼び出そうとしたときです。問題は、成功関数のコンテキストでのthis.saveSurveyが実際にはビューのコンテキストではないことだと確信しています。この関数を実際に呼び出すためにコンテキストを渡す方法はありますか?
class SurveyMe.Views.SurveyShow extends Backbone.View
template: JST['templates/surveys/survey_show']
initialize: ->
@model.on('all', @render, this)
@questionNumber = 0
@questionLimit = @model.get("questions").length - 1
@completion = new SurveyMe.Models.Completion
#@listenTo(@completion,'change', @saveSurvey)
render: ->
$(@el).html(@template(survey: @model, questionNumber: @questionNumber))
this
back: ->
if @questionNumber <= @questionLimit and @questionNumber > 0
@questionNumber -= 1
$("#container").html(@render().el)
else
Backbone.history.navigate("surveys",trigger: true)
events:
'click #answer': 'updateQuestion'
'click #back': 'back'
updateQuestion: ->
choice = new SurveyMe.Models.Choice
choice.save(
choice:
appuser_id: Cookie.get('survey_user_id')
question_id: @model.get('questions')[@questionNumber]["id"]
answer_id: "4"
)
if @questionNumber < @questionLimit
@questionNumber += 1
$("#container").html(@render().el)
@renderQuestion()
else
@completion.set(survey_id: @model.get('id'), appuser_id: Cookie.get('survey_user_id'))
@completion.save null,
success: ->
@saveSurvey()
error: ->
alert('fail fail fail')
Backbone.history.navigate("surveys",trigger: true)
renderQuestion: ->
question = new SurveyMe.Models.Question(id: @model.get("questions")[@questionNumber]["id"])
questionView = new SurveyMe.Views.Question(model: question)
$('#questions').html(questionView.render().el)
saveSurvey: ->
alert('great success')
@model.save(
number_taken: @model.get('number_taken') + 1
)
これはCoffeeScriptの問題です。
成功コールバックの=>
コンテキストを維持するには、太い矢印()構文を使用する必要がありthis
ます。
@completion.save null,
# Use the fat arrow here "=>" instead of the skinny arrow "->"
success: =>
@saveSurvey()
# You would also need to do it here if you planned to use @ to
# refer to the parent context in the error callback
error: ->
alert('fail fail fail')
@
親関数のコンテキストを参照するために関数内で使用する場合は常に、これを行う必要があります。
CoffeeScriptは、関数のスコープ@
を維持するための便利なthis
機能として、太い矢印とショートカットを提供します。舞台裏では_this = this
、通常の古いJavaScriptで一般的に行うすべてのタイプの処理を実行します。
関連するドキュメントは次のとおりです:http://coffeescript.org/#fat-arrow
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加