2016-07-26 59 views
0
的Javascript代碼聲明

所以,我有一點點多餘的代碼在我的意見之一:的Rails在HAML

- unless @event.start_time.nil? 
    :javascript 
    $(function() { 
     $('#datetimepicker1').datetimepicker({ 
     format: 'dddd, MMMM Do, YYYY, h:mm a' 
     }); 
     $('#datetimepicker1').data("DateTimePicker").date("#{@event.datepicker}"); 
    }); 
- else 
    :javascript 
    $(function() { 
     $('#datetimepicker1').datetimepicker({ 
     format: 'dddd, MMMM Do, YYYY, h:mm a' 
     }); 
    }); 

基本上,我使用的DateTimePicker我的領域之一,如果模型具有該字段的值,它將被追加。如果我能做這樣的事情會更清潔:

:javascript 
    $(function() { 
    $('#datetimepicker1').datetimepicker({ 
     format: 'dddd, MMMM Do, YYYY, h:mm a' 
    }); 
    - unless @event.start_time.nil? 
     $('#datetimepicker1').data("DateTimePicker").date("#{@event.datepicker}"); 
    }); 

任何想法?

回答

0

爲什麼不使用Ruby/HAML設置變量並在JS中處理條件?

:javascript 

    $(function() { 

    $('#datetimepicker1').datetimepicker({ 
     format: 'dddd, MMMM Do, YYYY, h:mm a' 
    }); 

    var event_start_time_present = #{@event.start_time.present?}; 

    if (event_start_time_present) { 
     $('#datetimepicker1').data("DateTimePicker").date("#{@event.datepicker}"); 
    } 

    }); 
0

我們可以嵌入Ruby代碼來檢查條件unless @event.start_time.nil?,因此代碼將是:

:javascript 
    $(function() { 
    $('#datetimepicker1').datetimepicker({ 
     format: 'dddd, MMMM Do, YYYY, h:mm a' 
    }); 
    var validStartTime = "#{@event.start_time.present?}"; 
    if (validStartTime === 'true') { 
     $('#datetimepicker1').data("DateTimePicker").date("#{@event.datepicker}"); 
    } 
    });