0

我使用这个代码的CoffeeScript:参数为骨干视图渲染方法

在SPEC文件:

index = new MeetingIndex(render: false, collection: booking.meetings) 
index.render(writeTo: '.sandbox') 
在视图文件

render: (options = {}) -> 
    console.log 'options' 
    console.log options 
    console.log 'options' 
    options[key] ||= val for key, val of writeTo: 'body', enhanceUI: true 

浏览器控制台打印:

Object 
    enhanceUI: true 
    writeTo: "body" 

what coul这里会发生什么?我怎样才能传递参数来渲染方法?

+1

意识到这一点'选项[关键] || = val'。如果你传递'enhanceUI:false',它将被重写为'true'。如果你不想这样做,你可以把它改成'options [key]?= val' :) – epidemian

回答

1

你只是通过异步console.log上当。您的第一个console.log电话只是获取对options的引用,但在尝试记录它时,您已经更新了它。试试这个:

render: (options = {}) -> 
    console.log 'options' 
    console.log _(options).clone() 
    console.log 'options' 
    options[key] ||= val for key, val of writeTo: 'body', enhanceUI: true 

演示:http://jsfiddle.net/ambiguous/EZc7N/

+0

我不确定这是怎么回事。由于其异步行为,他不应该在控制台中获得'enhanceUI:true,writeTo:'.sandbox''吗? – epidemian

+0

@epidemian:这是一个很好的观点。它闻起来像异步问题,也许代码与真正做的不匹配。任何想法,它可能是什么? –

+0

不是,但是当你的答案被接受时,它可能是一个'console.log'问题:)(也许有更多的代码比我们在这里看到的和'options'对象稍后被修改?)。 – epidemian

0

我无法重现此问题。这works as expected

render = (options = {}) -> 
    console.log 'first:', JSON.stringify options 
    options[key] ||= val for key, val of writeTo: 'body', enhanceUI: true 
    console.log 'then:', JSON.stringify options 

render writeTo: '.sandbox' 

输出:

first: {"writeTo":".sandbox"} 
then: {"writeTo":".sandbox","enhanceUI":true} 

注意到,我记录对象的JSON字符串化,以避免登录同一个对象两次(作为对象是一样的,调试控制台会打印相同的值(当前状态))。

此外,您maight感兴趣的Underscore's default填写默认参数:

render = (options = {}) -> 
    _.defaults options, writeTo: 'body', enhanceUI: true