Backbone.js - Coffeescript扩展

Baz*_*zZy 18 javascript coffeescript backbone.js ruby-on-rails-3

我正在通过本文http://blog.shinetech.com/2011/07/25/cascading-select-boxes-with-backbone-js/与backbone.js进行链接选择,但在扩展类时遇到错误.

所以,我有LocationsView类:

class Blog.Views.LocationsView extends Backbone.View
  events:
    "change": "changeSelected"
Run Code Online (Sandbox Code Playgroud)

CountriesView类:

class Blog.Views.CountriesView extends Blog.Views.LocationsView
  setSelectedId: (countryId) ->
Run Code Online (Sandbox Code Playgroud)

CitiesView类:

class Blog.Views.CitiesView extends Blog.Views.LocationsView
  setSelectedId: (cityId) ->
Run Code Online (Sandbox Code Playgroud)

但是当coffeescript代码编译为javascript时,我的双扩展类看起来像:

(function() {
  var __hasProp = Object.prototype.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;
cities_view.js:5 Uncaught TypeError: Cannot read property 'prototype' of undefined
    child.prototype = new ctor;
    child.__super__ = parent.prototype;
    return child;
  };
  Blog.Views.CitiesView = (function() {
    __extends(CitiesView, Blog.Views.LocationsView);
    function CitiesView() {
      CitiesView.__super__.constructor.apply(this, arguments);
    }
    CitiesView.prototype.setSelectedId = function(cityId) {};
    return CitiesView;
  })();
}).call(this);
Run Code Online (Sandbox Code Playgroud)

我得到了错误:

Uncaught TypeError: Cannot read property 'prototype' of undefined    cities_view.js:5
Run Code Online (Sandbox Code Playgroud)

那么,问题出在哪里以及如何解决?

Bri*_*sio 35

既然你正在使用ROR,那么说你在资产管道中使用3.1是否正确?如果您没有使用3.1,那么这些信息可能仍然有用,具体取决于您的工作方式.

当文件在同一文件夹中时,3.1中的资产管道将按字母顺序显示您的js文件.

因此,cities_view.js将在locations_view.js之前执行.然后,当CitiesView试图定义自己时,LocationsView还不存在.(但这让我感到困惑,因为你不应该使用.coffee文件而不是.js文件吗?)

您将不得不清除资产管道中的文件顺序(可通过注释控制),以便获取正确的文件...或更改名称.

换句话说,您可以告诉Sprockets(管理资产管道的RoR中的东西)首先要求另一个文件.

cities_view.coffee文件顶部,您可以添加以下行:

##= require ./locations_view
Run Code Online (Sandbox Code Playgroud)

祝好运

  • 几年过去了,但是你还在用这个回复保存驴子,欢呼! (3认同)