简体   繁体   English

如何在Coffeescript inhertiance中从父级访问子模型静态

[英]How to access child model static from parent within Coffeescript inhertiance

I have the following BaseModel class 我有以下BaseModel

namespace 'Models', (exports) ->
  class exports.BaseModel
    toJSON: =>
      if @jsonProperties? then ko.toJSON( @, @jsonProperties() ) else null

Then my Profile class that inherits the BaseModel class 然后我的Profile类继承了BaseModel

namespace 'Models', (exports) ->
  class exports.Profile extends exports.BaseModel
    constructor: ( @options ) ->
      @FirstName = ko.observable( @options.FirstName )
      @LastName = ko.observable( @options.LastName )

  @jsonProperties: -> 
    return [ "FirstName", "LastName" ]

This allows me to call something like the following 这允许我调用类似下面的内容

profile = new Models.Profile
  FirstName: 'blah'
  LastName: 'blah'   

profile.toJSON()

However within the base model @jsonProperties is undefined because it's kind of like a static function on the class type. 但是在基本模型中@jsonPropertiesundefined因为它有点像类类型上的静态函数。 The reason I want this is so that I can reference it in other classes like so Models.Profile.jsonProperties() 我想要这个的原因是我可以在其他类中引用它,如Models.Profile.jsonProperties()

Is is possible for me to get access to something like this from within the BaseModel? 我可以在BaseModel中访问这样的东西吗?


EDIT: Adding in a placeholder fix until I come up with something better 编辑:添加占位符修复,直到我想出更好的东西

I've done the following to get it working but I'd rather not have to repeat this line in every Model that I create, it seems like there should be a generic way to do this from the BaseModel. 我已经完成了以下工作以使其工作,但我不想在我创建的每个模型中重复这一行,似乎应该有一种通用的方法来从BaseModel执行此操作。

namespace 'Models', (exports) ->
  class exports.Profile extends exports.BaseModel
    constructor: ( @options ) ->
      @jsonProperties = Models.Profile.jsonProperties

If I understood what you are trying to achieve, you can fix it by defining jsonProperties as both a "static" Class method and an instance method. 如果我理解了你想要实现的目标,你可以通过将jsonProperties定义为“静态”类方法和实例方法来解决它。 Here is a simplified code (don't have access to the namespace util and knockout): 这是一个简化的代码(无法访问namespace util和knockout):

class BaseModel
  toJSON: =>
    if @jsonProperties? 
      for value in @jsonProperties()
        @[value]
    else
      null

class Profile extends BaseModel
  constructor: ( @options ) ->
    @FirstName = @options.FirstName
    @LastName = @options.LastName

  @jsonProperties: -> 
    return [ "Class FirstName", "Class LastName" ]

  jsonProperties: -> 
    return [ "FirstName", "LastName" ]

prof = new Profile
  FirstName: 'Leandro'
  LastName: 'Tallmaris'   

alert(prof.toJSON());

alert(Profile.jsonProperties());

The first alert should give you Leandro, Tallmaris , while the second Class FirstName, Class SecondName . 第一个警报应该给你Leandro, Tallmaris ,而第二个Class FirstName, Class SecondName

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

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