【问题标题】:Extend an hash attribute and prevent overwrite it with coffeescript and marionettejs扩展一个哈希属性并防止用 coffeescript 和 marionettejs 覆盖它
【发布时间】:2013-08-16 05:57:50
【问题描述】:

我有这样的看法:

class MyView1 extends Backbone.Marionette.Layout
  template: JST['templates/view1']

  regions:
     region1: '.region1'

  ## Here some methods....

现在我想扩展这个类来添加一些区域和方法

class MyView2 extends MyView1
  template: JST['templates/view2']

  regions:
    region2: '.region2'

这会覆盖模板和区域属性。但我想将 region2 添加到区域哈希中,而不是覆盖它。所以 region 将是 region1 和 region2 的哈希值。

我怎样才能得到它?

【问题讨论】:

    标签: javascript backbone.js coffeescript marionette


    【解决方案1】:

    这里有一个解决方法:

    class MyView1 extends Backbone.Marionette.Layout
      template: JST['templates/view1']
    
      regions:
        region1: '.region1'
    
    class MyView2 extends MyView1
      template: JST['templates/view2']
    
      MyView2::regions = {}
      for k, v of MyView1::regions
        MyView2::regions[k] = v
      MyView2::regions.region2 = '.region2'
    

    但也许以下内容会更干净,并且同样可以很好地满足您的目的:

    class MyView1 extends Backbone.Marionette.Layout
      constructor: ->
        @regions =
          region1: '.region1'
    
      template: JST['templates/view1']
    
    class MyView2 extends MyView1
      constructor: ->
        super()
        @regions.region2 = '.region2'
    
      template: JST['templates/view2']
    

    按照评论的建议,编辑为使用更惯用的咖啡脚本 :: 而不是 .prototype

    【讨论】:

    • 第二个选项工作正常,更时尚。但是对 super 的调用我终于做到了,因为 Marionettejs 对哈希做了一些操作,如果在顶部调用 super 它就不能正常工作。
    • 在 CoffeeScript 中你通常会写 MyView2::regions 而不是 MyView2.prototype.regions
    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多