gpt4 book ai didi

javascript - 主干 View 中的上下文

转载 作者:行者123 更新时间:2023-12-02 17:14:22 24 4
gpt4 key购买 nike

我正在努力创建一个基本的调查应用程序,以更好地学习 Backbone 。我正在努力让用户只能参加一次特定的调查。我将其构建在 Rails 端,如果同一用户尝试再次进行相同的调查,它会返回错误。

正确调用成功和错误函数。我遇到的问题是当我尝试调用@saveSurvey 时。我确信问题在于成功函数上下文中的 this.saveSurvey 实际上并不是 View 的上下文。知道我应该如何传递上下文来实际调用这个函数吗?

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 范围。它只是在幕后执行您通常在常规旧 JavaScript 中自己执行的所有 _this = this 类型的操作。

以下是相关文档:http://coffeescript.org/#fat-arrow

关于javascript - 主干 View 中的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24565481/

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