【问题标题】:Refreshing backbone form (including events) after validation error without reloading page验证错误后刷新主干表单(包括事件)而不重新加载页面
【发布时间】:2012-10-29 01:03:25
【问题描述】:

我有一个带有表单的 Backbone 视图。当用户提交表单时,可能会出现验证错误,由后端处理。 显示错误后,我希望表单再次可用。我以为我应该只做 this.delegateEvents(),但由于某种原因它不起作用...

代码如下:

class App.Views.PlotsCreate extends Backbone.View
  template: JST['plots/create']

    events:
        'submit #new_plot': 'createPlot'


    createPlot: (event) ->
      event.preventDefault()
      @attributes = plot: {name: $('#new_plot_name').val(), docreate: "true", code: code }
      @collection.create @attributes,
        wait: true
        success: (plot) => 
          document.body.style.cursor = 'default'
            @showProgress(plot)
        error: @handleError
      )

    handleError: (entry, response) =>
      if response.status == 422
        errors = $.parseJSON(response.responseText).errors
        for attribute, messages of errors
          $('#new_plot_name').val("#{message}" for message in messages)



    <form class="new_plot" name="create_form" id ="new_plot"  data-remote="true" enctype="multipart/form-data">
      <textarea class="input" id="new_plot_name" name="name" rows="5" maxlength = '140'></textarea> 
      <input class="blue_button btn_generate" name="commit" type="submit" value="create" id ="plot_subm"/>
    </form>   

如何使表单再次起作用(即在显示错误后再次提交事件触发)

【问题讨论】:

    标签: javascript backbone.js coffeescript backbone-views backbone-events


    【解决方案1】:

    验证失败通常不会对事件绑定产生任何影响;事实上,从技术上讲,视图甚至没有验证方法,只有模型有(并且该方法所做的只是触发“错误”事件并返回 false)。你确定你没有破坏视图的代码吗?

    【讨论】:

    • 代码在这里.. 只是报错后无法第二次提交表单。
    • 好吧,显然不是全部;您的视图中有一些模板,如果没有某种外部模板库(或 Backbone 插件),这些模板可能无法执行任何操作。但是您错过了重点,即 Backbone 没有做任何事情:您放置在 Backbone 之上的一些代码(像您的模板库这样的第三方库或您自己的代码)是问题的根源。
    • P.S.我注意到你还有data-remote="true",Google 发现它是一些疯狂的 Rails 东西;完全有可能涉及的任何 Rails JS 都可能是罪魁祸首(Rails 在我使用它时没有 JS,但我有一段时间没有使用它,所以也许现在它有?)。
    • 我认为您可能对date-remote 的东西有所了解,同时让 Rails AJAX“友好”助手和 Backbone 都试图处理表单提交只是要求它。我会更进一步说,使用带有 Backbone 的 Rails 表单构建东西是一个错误。
    • omg,我刚刚看到我实际上在提交后使用 jquery 禁用了按钮...我想我会接受这个答案,因为问题确实出在未粘贴的代码上。跨度>
    猜你喜欢
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2021-10-29
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多