簡體   English   中英

Rails4:在視圖中使用Coffeescript / javascript變量

[英]Rails4: Use Coffeescript/javascript variable in view

我正在嘗試從我的Rails 4視圖代碼中調用分類的coffeescript / javascript函數。 告訴我,頁面加載時創建並在document.ready中使用的類變量不再存在。

咖啡腳本:

class App
  reload_calendar: ->
    source = new Array
    viewable_calendars = $('input:checkbox:checked.visable_calendars').map(->
      @value
    ).get().join(',')
    calendar_url = '/events.json'
    new_event_link = '#{new_event_path}'
    $('#calendar').fullCalendar
      dayClick: (date, allDay, jsEvent, view) ->
        document.location.href = new_event_link + '?start_date=' + date
        return
      header:
        left: 'prev,today,next'
        center: 'title'
        right: 'month,agendaWeek,agendaDay'
      selectable: true
      selectHelper: true
      editable: false
      ignoreTimezone: false
      select: @select
      eventClick: @eventClick
      eventDrop: @eventDropOrResize
      eventSources: [ {
        url: calendar_url
        data:
          custom_param1: 'something'
          custom_param2: 'somethingelse'
        error: ->
          alert 'there was an error while fetching events!'
          return
      } ]
      eventResize: @eventDropOrResize
      timeFormat: 'h:mmtt{ - h:mmtt} '
    return

app = new App
$(document).ready ->
  app.reload_calendar()
  $('#calendar-color').minicolors()

部分:

<ul>
<% @calendars.each do |c| %>
  <li>
    <span style="background-color: <%= c.color %>;">
      <%= check_box_tag 'show_calendar_'+c.id.to_s, value=c.id.to_s, checked=true, :onchange => "app.reload_calendar()", :class => "visible_calendars" %>
    </span>
    <%= c.name %>
    <%= link_to 'x', calendar_path(c), :confirm => "Are you sure you want to remove the calendar?", :method => :delete %></li>
<% end %>

這樣可以很好地加載日歷(在咖啡腳本末尾使用app.reload_calendar),但是失敗,並顯示錯誤Uncaught ReferenceError: app is not defined單擊或取消選中復選框觸發Uncaught ReferenceError: app is not definedUncaught ReferenceError: app is not defined

只需對每個咖啡類使用此模式

class MyClass
  ...

root = exports ? window
root.MyClass = MyClass

在此處此處將您的課程公開的其他方法

window.app =新的App可以正常工作,如LongDương在評論中所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM