我有这样的功能:
getData = ->
$('body').data('key')
我有另一个函数,我想使用第一个函数来检查是否有一些数据。我想写的是这样的:
otherFunction = ->
if getData()
...do something...
但是,在我的测试中,该陈述if function()
将始终正确,因为那里有一些东西(一个功能)。所以上面的行不通。
做我在这里尝试的最干净的方法是什么,检查函数是否返回一些数据?
我有这样的功能:
getData = ->
$('body').data('key')
我有另一个函数,我想使用第一个函数来检查是否有一些数据。我想写的是这样的:
otherFunction = ->
if getData()
...do something...
但是,在我的测试中,该陈述if function()
将始终正确,因为那里有一些东西(一个功能)。所以上面的行不通。
做我在这里尝试的最干净的方法是什么,检查函数是否返回一些数据?
如果没有 data 属性,或者 dom 元素上有一个空的 data 属性,您的模式肯定会解析为 false(因为返回值错误)。
见这个例子:http: //jsfiddle.net/wkGcW/1/
getData = ->
$('div').data 'key'
getData2 = ->
$('div').data 'foo', 'bar'
otherFunction = ->
if getData()
console.log 'yep'
else
console.log 'nope' <--- Resolves false
if getData2()
console.log 'yep' <--- Resolves true
else
console.log 'nope'
otherFunction()
您可能还有其他问题在起作用...
就像是:
if(getData() !== false) then do...
你需要在你的 getData 方法上有一个返回转义。
获取数据是对象还是返回数据的方法?