Monday, 28 October 2013

extending GeoExt.data.LayerModel with extra fields

In Ext 4 the data package has changed quite a bit. What was called a Record in Ext 3, is now called a Model. Also, adding extra fields to an existing model requires a different approach.

In GeoExt 1 we were able to do things like:

  // create a layer record for this layer
  var Record = GeoExt.data.LayerRecord.create([
    {name: "name", type: "string"},
    {name: "source", type: "string"},
    {name: "group", type: "string"},
    {name: "fixed", type: "boolean"},
    {name: "selected", type: "boolean"},
    {name: "type", type: "string"},
    {name: "args"}

  ]);

  var data = {
    layer: layer,
    title: layer.name,
    name: config.name || layer.name,
    source: config.source,
    group: config.group,
    fixed: ("fixed" in config) ? config.fixed : false,
    selected: ("selected" in config) ? config.selected : false,
    type: config.type,
    args: config.args,
    properties: ("properties" in config) ? config.properties : undefined
  };
  record = new Record(data, layer.id);

However in GeoExt 2 this requires a different approach, and I ran into an issue in GeoExt 2 whilst doing this see this PR

Basically static properties and methods are not automatically inherited in Ext 4, we need to explicitly use inheritableStatics for them to get inherited. Also we need to make sure we don't use instance properties in the static method itself, but only static methods.

In GeoExt 2 all extra properties are read through the metadata object which is present on OpenLayers Layer instances. So we need to follow this approach for our custom fields as well, which leads to:

Ext.define('gxp.data.OLLayerModel',{
  extend: 'GeoExt.data.LayerModel',
  fields: [
     {name: "name", type: "string", mapping: 'metadata.name'},
     {name: "source", type: "string", mapping: 'metadata.source'},
     {name: "group", type: "string", mapping: 'metadata.group'},
     {name: "fixed", type: "boolean", mapping: 'metadata.fixed'},
     {name: "selected", type: "boolean", mapping: 'metadata.selected'},
     {name: "type", type: "string", mapping: 'metadata.type'}, 
     {name: "args", type: "array", mapping: 'metadata.args'},
     {name: "properties", type: "string", mapping: 'metadata.properties'}
  ]
});

Ext.apply(layer.metadata, {
  name: config.name || layer.name,
  source: config.source,
  group: config.group,
  fixed: ("fixed" in config) ? config.fixed : false,
  selected: ("selected" in config) ? config.selected : false,
  type: config.type,
  args: config.args,
  properties: ("properties" in config) ? config.properties : undefined
});
record = gxp.data.OLLayerModel.createFromLayer(layer);

No comments:

Post a Comment