使用继承配置netzkejavascript代码(在带有参数的父类中定义js代码)

configuring netzke javascript code using inheritance (defining js code in a parent class with parameters)

本文关键字:代码 父类 参数 js 定义 继承 配置 netzkejavascript      更新时间:2023-09-26

我有两个带有操作列的netzke网格组件(还有更多)。根据类型的不同,操作列几乎相同。唯一的区别是单击操作按钮时要执行的操作。

因此,我想定义一个新的网格组件,它包含所有共享部分,包括javascript,然后在继承类中配置javascript(设置参数/上下文)。

因此,首先,我的课程将如下所示:

class CpPoles < Netzke::Basepack::Grid
  include Netzke::Basepack::ActionColumn
  .. snipped ..    
  column :actions do |c|
    c.type = :action
    c.actions = [
        {name: :locate_on_map, tooltip: "show on map", icon: :map_marker},
    ]
  end
  js_configure do |c|
    c.on_locate_on_map = <<-JS
      function(record){
        Map.zoomToFeature('cp_poles', record.raw[0]);
      }
    JS
  end
end

在我的另一个类中,除了layer_name之外,它看起来完全相同:

  js_configure do |c|
    c.on_locate_on_map = <<-JS
      function(record){
        Map.zoomToFeature('markerpoles', record.raw[0]);
      }
    JS
  end

因此,我引入了一个新的网格类,它包含所有共享配置,并定义了操作:

  js_configure do |c|
    c.on_locate_on_map = <<-JS
      function(record){
        Map.zoomToFeature(this.layer_name, record.raw[0]);
      }
    JS
  end

现在我只需要设置this.layer_name。我想太容易了。在我的CpPole课上,我现在可以写了

class CpPoles < Netzke::MyApplication::Grid
  js_configure do |c|
    c.layer_name = 'cp_poles'
  end
end 

但这不起作用:(所以我尝试了一个mixin,并在initComponent上设置了this.layer_name,但也不起作用。我担心我的共享网格中的this与CpPole类中的this不同,但on_locate_map确实起作用。

我该如何解决此问题?

目前我以不同的方式解决了它,我在基类中添加了一个方法

def self.set_action_methods(layer_name)
  js_configure do |c|
    c.on_locate_on_map = <<-JS
      function(record){
        Map.zoomToFeature('#{layer_name}', record.raw[0]);
      }
    JS
  end
end

它添加了所有的操作方法(在我的代码中,它添加的不仅仅是一个)。

所以我的派生类变得非常简单,我只需要指定配置块

class Markerpoles < Netzke::MyBaseGrid
  def configure(c)
    super
    c.model = 'Markerpole'
    c.columns = [
        :name,
        {name: :location, flex: 1},
        {name: :comments, flex: 1},
        {name: 'markerpole_material__label', text: "Material"}
    ]
  end
  set_action_methods('markerpoles')
end

看起来不错。不确定是否有更好的解决方案?