将数据从simple_form发送到javascript

时间:2018-07-17 20:38:33

标签: javascript ruby-on-rails backbone.js coffeescript simple-form

我有一个有效的JavaScript:

 .search_client_users
    = form_tag admin_clients_path, method: "get", class: "search_form" do
      = label_tag 'search_term', 'Search for client users:'
      = text_field_tag 'search_term', nil, autocomplete: "off", size: "50"

    .client_list

- content_for :javascript do
  = javascript_include_tag 'admin/search_client_users'

搜索客户端并列出与查询匹配的客户端。

我想在普通的simple_form中使用它:

    .main_form.client_emails
      = simple_form_for(:domainNameSwap, url: { action: "update" }, html: { method: :put }) do |f|
        .input-row
          = f.input :oldDomain, :label => "Domain Name",wrapper_html: { id: 'search_term' }
        .submit-row
          .col-xs-5
            .submit
              = f.submit "Update domains", id: "submit", :class => "btn btn-primary submit"

    .client_list


- content_for :javascript do
  = javascript_include_tag 'admin/search_client_users'

但是我不知道如何将标签添加到javascript ...

看来,工作代码中相关的部分是text_field_tag = 'search_term',这似乎是将文本字段与javascript相关联的部分。但是我不知道如何在simple_form中使用它。

以下是重要的咖啡脚本:

class App.ClientUserList
  constructor: ->
    @incrementalSearchAttempts = 0

  search: (searchTerm, completeCallback) =>
    handleResponseWithOrderAwareness = (attemptNumber, response) =>
      if attemptNumber >= @incrementalSearchAttempts
        completeCallback(response)

    @incrementalSearchAttempts++
    onComplete = _.partial(handleResponseWithOrderAwareness, @incrementalSearchAttempts)
    $.get('/admin/manage_clients/client_list', { search_term: searchTerm }).complete(onComplete)

class App.Views.SearchClientUsers extends Backbone.View
  events:
    "keyup input[name='search_term']": "search",
    "click .profile_attribute": "showClientUserProfile"

  initialize: =>
    @clientUserList = new App.ClientUserList()

  search: =>
    searchTerm = $('.search_form input[name=search_term]').val()
    @clientUserList.search(searchTerm, @render)

  showClientUserProfile: (event) =>
    window.location = $(event.currentTarget).closest('tr').data('client-path')

  render: (response) =>
    @$el.find('.client_list').html(response.responseText)

$ ->
  new App.Views.SearchClientUsers(el: $('.search_client_users')).search()

ETA: 简化:我认为我需要两件事:

  1. 我需要将simple_form的类设置为“ search_form”
  2. 我需要做text_field_tag行的等效项,但对于f.input行。

我很确定第一个应该只是在simple_form的html部分中添加class: "search_form"

但是,我不知道如何设置“ text_field_tag

1 个答案:

答案 0 :(得分:0)

对于将来的搜索者:看来我是正确的,我需要设置simple_form的类,并且需要设置f.input的“名称”。

在f.input行中添加input_html: {name: 'search_term'}选项可以解决此问题。

但是,这也意味着,在控制器中,值不在params.domainNameSwap.oldDomainName中,而在params.search_term中,这是我可以忍受的问题...