在骨干视图中的上下文

时间:2014-07-04 01:26:05

标签: javascript backbone.js coffeescript

我正在努力创建一个基本的调查应用程序,以更好地学习骨干。我努力做到这一点,以便用户只能进行一次调查。我有这个建立在rails侧面,如果同一个用户尝试再次进行相同的调查,它会返回错误。

正确调用成功和错误函数。我遇到的问题是当我试图打电话给@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
    )

1 个答案:

答案 0 :(得分:2)

这是一个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提供了fat-arrow和@快捷方式,以方便在函数中维护this范围。在幕后,它只会执行您通常在常规旧JavaScript中执行的所有_this = this类型的操作。

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