简体   繁体   English

如何将此Coffeescript拆分为单独的文件?

[英]How can I split this Coffeescript into separate files?

Using the Garber method for DOM execution: 使用Garber方法执行DOM:

SITENAME = {
  common: {
    init: function() {
      // application-wide code
    }
  },

  users: {
    init: function() {
      // controller-wide code
    },

    show: function() {
      // action-specific code
    }
  }
};

UTIL = {
  exec: function( controller, action ) {
    var ns = SITENAME,
        action = ( action === undefined ) ? "init" : action;

    if ( controller !== "" && ns[controller] && typeof ns[controller][action] == "function" ) {
      ns[controller][action]();
    }
  },

  init: function() {
    var body = document.body,
        controller = body.getAttribute( "data-controller" ),
        action = body.getAttribute( "data-action" );

    UTIL.exec( "common" );
    UTIL.exec( controller );
    UTIL.exec( controller, action );
  }
};

$( document ).ready( UTIL.init );

How could I use this technique in separate .coffee files ala Rails pipeline? 如何在单独的.coffee文件和Rails管道中使用此技术?

I want to do the following 我想做以下

users.js.coffeee users.js.coffeee

SITENAME =
  users:
    init: ->
      alert("nope")

    index: ->
      alert("hi")

But if I do that now, it just rewrites it and forces me to keep it all in one file. 但是,如果我现在这样做,它只会重写它,并迫使我将所有内容保存在一个文件中。

How can I split it up and use namespacing for each page in this technique? 如何使用这项技术拆分它并为每个页面使用命名空间?

First, make sure you're including it in the application.js manifest file: 首先,请确保将其包含在application.js清单文件中:

//= require global
//= require users

Where global.coffee holds your utility methods. global.coffee保存实用程序方法的位置。 Your example users.coffee looks fine. 您的示例users.coffee看起来不错。 However, you'll need to scope SITENAME to window so that it's accessible across the board. 但是,您需要将SITENAME的范围设置为window以便可以全面访问它。

// global.coffee
window.SITENAME = ...

// users.coffee
window.SITENAME.users = ...

You'll need to do this because CoffeeScript will compile each file within it's own closure... thereby limiting scope unless you explicitly assign it to window. 您将需要执行此操作,因为CoffeeScript会在自己的闭包中编译每个文件...从而限制了范围,除非您将其明确分配给window。

(function() {
  window.SITENAME.users = {};
}).call(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM