在CoffeeScript中声明Backbone集合

时间:2011-08-27 20:02:31

标签: javascript backbone.js coffeescript

我正在试图找出在CoffeeScript中为Backbone Collection声明模型的正确方法。让我用一个例子来证明:

class MyApp.Collections.Likes extends Backbone.Collection
  constructor: (@models, @options) ->
  model: MyApp.Models.Like

当我初始化此集合并创建新模型时,它会失败。

likes = new MyApp.Collections.Likes
like = new likes.model // same result for likes.model.new

TypeError: Result of expression 'likes.model' [undefined] is not an object.

查看已编译的JavaScript,模型定义如下:

MyApp.Collections.Likes = (function() {
  __extends(Likes, Backbone.Collection);
  function Likes(models, options) {
    this.models = models;
    this.options = options;
  }
  Likes.prototype.model = MyApp.Models.Like; // <--
  return Likes;
})();

我可以通过两种方式定义模型:


解决方案1 ​​

class MyApp.Collections.Likes extends Backbone.Collection
  constructor: (@models, @options) ->
  model: -> MyApp.Models.Like // Notice the ->

将其编译为:

MyApp.Collections.Likes = (function() {
  __extends(Likes, Backbone.Collection);
  function Likes(models, options) {
    this.models = models;
    this.options = options;
  }
  Likes.prototype.model = function() { // <-- added to the prototype as a function
    return MyApp.Models.Like;
  }
  return Likes;
})();

解决方案2

class MyApp.Collections.Likes extends Backbone.Collection
  constructor: (@models, @options) ->
  @model: MyApp.Models.Like // Notice the @

将其编译为:

MyApp.Collections.Likes = (function() {
  __extends(Likes, Backbone.Collection);
  function Likes(models, options) {
    this.models = models;
    this.options = options;
  }
  Likes.model = function() { // <-- not added to prototype
    return MyApp.Models.Like;
  }
  return Likes;
})();

我非常确定解决方案1 ​​是更好的解决方案。但是,我在教程中看到的很多网站都是在没有->@的情况下定义的。

我做了一些明显的错误吗?

Like模型没有任何问题,它非常香草:

class MyApp.Models.Like extends Backbone.Model

3 个答案:

答案 0 :(得分:3)

我无法复制您的错误。这是我的代码:

class Like extends Backbone.Model

class Likes extends Backbone.Collection
    model: Like

likes = new Likes
like = new likes.model
console.log like instanceof Like  # true

你有可能在某个地方打错了吗?特别是,在您编写MyApp.Models.Like时定义model: MyApp.Models.Like?测试

console.log MyApp.Collections.Likes::model?

console.log MyApp.Collections.Likes::model is MyApp.Models.Like

应该都给你true。如果他们这样做,那么new likes.model应该等同于new MyApp.Models.Like

答案 1 :(得分:0)

当你写

时,你期望发生什么?
like = likes.model.new

?该语法适用于Ruby,但在CoffeeScript中,它只是将new的{​​{1}}属性赋予likes.model。在这种情况下,那就是like。尝试

undefined

代替。

答案 2 :(得分:0)

嘿,我知道我迟到了这个派对,但我想补充一点,每次我看到这个问题都是因为程序员忘记了coffeescript中的类是漏洞的抽象,而且他们的声明之前都没有读过执行 - 在这种情况下,模型需要在之前定义,编译后的js会尝试将其添加到Collection的原型中。