如何在coffeescript中的特定范围内声明一个变量? [英] How do I declare a variable in a specific scope in coffeescript?
问题描述
我试图在coffeescript中写一个使用beforeEach块的茉莉花测试。这遇到一个问题coffeescript的变量范围。这里是我想写的:
I'm trying to write a jasmine test in coffeescript that uses a beforeEach block. This runs into a problem with coffeescript's variable scoping. Here's what I'd like to write:
describe 'PhoneDetailCtrl', () ->
beforeEach () ->
scope = angular.scope()
$browser = scope.$service('$browser')
it 'should fetch phone detail', () ->
scope.params = {phoneId:'xyz'}
$browser.xhr.expectGET('phones/xyz.json').respond({name:'phone xyz'})
ctrl = scope.$new(PhoneDetailCtrl)
expect(ctrl.phone).toEqualData({})
$browser.xhr.flush()
expect(ctrl.phone).toEqualData({name:'phone xyz'})
工作,因为 scope
和 $ browser
将声明与 var
在最深的范围。也就是说,一旦在 beforeEach
,然后再次在 it
块。我可以通过初始化它们来强制变量声明在正确的范围,但是这似乎很奇怪:
This doesn't work, though, because the scope
and $browser
will get declared with var
in the innermost scope. That is, once in the beforeEach
and then again in the it
block. I can force the variables to be declared in the right scope by initializing them, but this seems very strange:
describe 'PhoneDetailCtrl', () ->
$browser = {}
scope = {}
beforeEach () ->
scope = angular.scope()
$browser = scope.$service('$browser')
it 'should fetch phone detail', () ->
scope.params = {phoneId:'xyz'}
...
这个工程,但它编译的JavaScript实际上是
This works, but the javascript it compiles to is actually
describe('PhoneListCtrl', function() {
var $browser, ctrl, scope;
$browser = {};
ctrl = {};
scope = {};
其中所有我需要的是 var $ browser,ctrl,scope;
。 in coffeescript?
where all I need is the line var $browser, ctrl, scope;
. Can I write this more concisely in coffeescript?
推荐答案
您正在以正确的方式做。
You are doing it the right way.
这在 CoffeeScript文档中有所描述,我不担心它创建的JS。 ,这是一个有点凌乱,如果你是自己写的,但这是你必须与当你使用一个重写作如CoffeeScript一样的东西。
This is described in the CoffeeScript documentation. I wouldn't worry about the JS that it creates. Yes, it is a bit messy if you were to write it yourself, but this is one of the things that you have to live with when you use a re-writer like CoffeeScript.
你可以把变量放在当前上下文中,如果你愿意的话jasmine.Spec对象的好奇,所以它是一个相对安全和适当的地方放置变量...只是不要覆盖上下文中现有的变量):
You can put the variables in the current context if you wish (which happens to be your jasmine.Spec object for the curious, so it is a relatively safe and appropriate place to be putting variables... just don't overwrite existing vars in the context.):
describe 'PhoneDetailCtrl', () ->
beforeEach () ->
@scope = angular.scope()
@$browser = @scope.$service('$browser')
it 'should fetch phone detail', () ->
@scope.params = {phoneId:'xyz'}
#... etc
$ b
You can also setup your own variable in which to store things
describe 'PhoneDetailCtrl', () ->
setup = {}
beforeEach () ->
setup.scope = angular.scope()
setup.$browser = setup.scope.$service('$browser')
it 'should fetch phone detail', () ->
setup.scope.params = {phoneId:'xyz'}
#... etc
这篇关于如何在coffeescript中的特定范围内声明一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!