我怎么能用CoffeeScript写这个呢?

时间:2011-12-23 20:09:17

标签: javascript jquery coffeescript

我试图在昨天查看LESS css之后与CoffeeScript达成协议,我对此印象非常深刻。

我更像是一个jQuery wiz而不是Raw Javascript,所以我觉得它有点令人困惑,但与此同时我觉得调查CoffeeScript很好,因为它可以帮助我通过分析输出来更好地理解。 / p>

var Raw = (function($) {

    $(function() {
        Raw.initialize();
    });

    return {
        _current: '',
        initialize: function() {
            this.initGlobal();
            if(this.is('index')) {
                this.initIndex();
            }
            else if(this.is('single')) {
                this.initSingle();
            }
        },
        initGlobal: function() {
            atom_twitter();
            atom_loading();
            ratings();
        },
        initIndex: function() {
            atom_scroll();
        },
        initSingle: function() {
            atom_download();
        },
        is: function(page) {
            if(this._current == '') {
                this._current = $('body').attr('id');
            }
            return this._current == page;
        }

    };

})(jQuery);

任何想法从哪里开始?

到目前为止,我有这个:

Raw = (($) ->
  console.log 'hello world'
)(jQuery);

哪个输出:

(function() {
  var raw;

  raw = (function($) {
    return console.log('hello world');
  })(jQuery);

}).call(this);

3 个答案:

答案 0 :(得分:2)

我是这样做的:

raw = do ($ = jQuery) ->
  $ raw.initialize
  {
    _current: ''
    initialize: ->
      @initGlobal()
      if @is 'index'
        @initIndex() 
      else if @is 'single'
        @initSingle()
    # and the rest...
  }

请注意,您尝试移植的代码可能存在问题:传递给$的函数将在DOM准备就绪时运行,或立即运行DOM已经准备好了。因此,如果在运行此代码时DOM已准备好,则在raw.initialize定义之前将调用raw,从而导致错误。

答案 1 :(得分:1)

通过您构建代码的方式,它几乎是逐行转换。我没有打扰$转换,但如果你想要,你只需将$ = jQuery放在do行之后。

Raw = null
do ($ = jQuery) ->

  Raw = 
    _current: ''
    initialize: ->
      @initGlobal()
      if @is 'index'
        @initIndex() 
      else if @is 'single'
        @initSingle()

    initGlobal: ->
      atom_twitter()
      atom_loading()
      ratings()
    initIndex: ->
      atom_scroll()
    initSingle: ->
      atom_download()

    is: (page) ->
      @_current = $('body').attr('id') if @_current == ''
      @_current == page

  $ -> Raw.initialize()

答案 2 :(得分:1)

您也可以使用

Raw = (($) ->
  $ ->
    Raw.initialize()

  _current: ""
  initialize: ->
    @initGlobal()
    if @is("index")
      @initIndex()
    else @initSingle()  if @is("single")

  initGlobal: ->
    atom_twitter()
    atom_loading()
    ratings()

  initIndex: ->
    atom_scroll()

  initSingle: ->
    atom_download()

  is: (page) ->
    @_current = $("body").attr("id")  if @_current is ""
    @_current is page
)(jQuery)

如果您想将您的js转换为coffeescript,请使用http://js2coffee.org/上的js2cofee转换器

相关问题