从纯 Javascript 语法的角度来看,这段代码:
App.IndexRoute = Em.Route.extend({
skipSidebar: true
});
相当于这个 Ruby:
App['IndexRoute'] = Em['Route'].extend( { 'skipSidebar' => true } );
也就是说,它将一个 Hash 的元素(在 Javascript 中所有对象本质上都是)分配给另一个 Hash 的元素上的方法调用的结果,其参数是第三个 Hash,这个是文字形式的( JSON 的基础)。
实际上,您可以将 JS 编写成与 Ruby 几乎相同的形式:
App['IndexRoute'] = Em['Route'].extend( { skipSidebar: true } );
...因为Name.KeyJavascript 中的语法只是Name['Key']当键字符串是有效标识符时的一种方便快捷方式。这也有效:
App['IndexRoute'] = Em['Route']['extend']( { skipSidebar: true } );
因为 Javascript 就像 Python 一样,方法实际上只是属性(哈希元素),其值为函数/闭包。
然而,从语义上讲,这在 Ember 中所做的是IndexRoute在App对象(用于命名空间)中定义一个名为 的类作为 Ember 定义的类Route(在Em对象/命名空间中)的子类,并添加一个skipSidebar默认的属性为true所有新App.IndexRoute对象。所以在功能上,它更像是这个 Ruby:
class App::IndexRoute < Em::Route
attr_accessor :skipSidebar
def initialize
@skipSidebar = true
end
end
在您的第二个示例中:
App.AboutRoute = Ember.Route.extend({
activate: function(){
this.controllerFor('application').set('renderAboutSubNav', true);
},
deactivate: function(){
this.controllerFor('application').set('renderAboutSubNav', false);
}
});
我们再次定义了一个子类(这次是Ember.Route而不是Em.Route),并在子类中添加或覆盖两个称为activateand的方法deactivate。红宝石:
class App::AboutRoute < Ember::Route
def activate
self.controllerFor('application').renderAboutSubNav = true
end
def deactivate
self.controllerFor('application').renderAboutSubNav = false
end
end