Wednesday, April 18, 2012

How to check if variable is undefined

I am using HAML and jquery to code my application. I have a single 'Share' template that is used to display a URL link. I want it to be flexible such that it will display different URLs depending on the variables that are passed into it.



//Code to trigger view and populate template -> Note I only pass in the thread vara here
share_view = new Onethingaday.Views.Threads.ShareView
thread: new Onethingaday.Models.Thread(@options.thread_muses.first().get('question'))

//snippet from share view to pass the variables to the template
render: ->
$(@el).html @template
nickname: @options.nickname
thread_slug: @options.thread.get('slug')
thread_text: @options.thread.get('text')
@

//Snippet of share view's template. Added if-else statement to check if nickname is defined
.sidebar_text Link:
<% if (typeof <%= nickname %> !== "undefined") { %>
%input.detail_text{value: "<%= 'http://dailymus.es/' + nickname + '/threads/' + thread_slug %>"}
<% } else { %>
%input.detail_text{value: "<%= 'http://dailymus.es/' + '/threads/' + thread_slug %>"}
<% } %>


In the above example, I did not define "nickname" variable. I expect that the else portion will be triggered and the URL displayed is "http://dailymus.es/threads/some-slug-text"



However I am still getting the following



enter image description here



As you see, it is still triggering the 'if' portion and displaying the 'undefined' as part of the URL.



How can I correctly check for 'undefined' variables in my case?





No comments:

Post a Comment