【问题标题】:Using coffeescript with backbone.js issues将咖啡脚本与主干.js 问题一起使用
【发布时间】:2013-05-07 17:19:42
【问题描述】:

我正在尝试遵循 Brian Mann 制作的优秀教程骨干网。不幸的是(对我来说,因为我是菜鸟)他正在使用咖啡脚本。令人困惑的是我对以下代码的假设:

class App.Views.Users extends Backbone.View

我相信相当于:

Users = Backbone.View.extend({});

在纯 JavaScript 中。但是,当我将咖啡脚本代码放在 trycoffeescript 中时,我得到:

var _ref,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if     (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() {   this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new   ctor(); child.__super__ = parent.prototype; return child; };

App.Views.Users = (function(_super) {
  __extends(Users, _super);

  function Users() {
    _ref = Users.__super__.constructor.apply(this, arguments);
    return _ref;
  }

  return Users;

})(Backbone.View);

我的问题是我对纯 javascript 应该产生什么的假设是错误的,是我错误地接近了解释咖啡脚本的方式,还是我超出了希望?

【问题讨论】:

    标签: backbone.js coffeescript


    【解决方案1】:

    coffeescript 中的类不能保证它们所扩展的类具有extend 方法,因此如果没有明确要求与它一起使用的所有类,coffeescript 就不可能编译为Backbone.View.extend提供extend 方法。

    但是,如果您查看 _.extend(Backbone 使用)的来源,您会发现它与 coffeescript 生成和使用的 __extends 方法非常相似。

    coffeescript 编译的版本显然更冗长,但在实践中我从未注意到class MyView extends Backbone.ViewMyView = Backbone.View.extends({}}; 之间的区别,因此您可以使用您喜欢的任何一个。

    编辑:一个可能的区别实际上是super coffeescript 关键字,它仅在您使用coffeescript 类时才有效。但是,您仍然可以通过直接调用超类函数来使用.extends 复制该功能。

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 1970-01-01
      • 2016-02-26
      • 2011-11-08
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 2013-02-03
      • 2013-03-11
      相关资源
      最近更新 更多