Creating custom attribute properties

While the built-in SC.RecordAttribute transforms, String, Boolean, Number, Array, Object, Date, and SC.DateTime, will cover almost all the different types of attributes in your records. If you wish to create a reusable custom transform, this is easily done using SC.RecordAttribute.registerTransform().

For instance, SproutCore provides a class for manipulating colors called SC.Color. If we were sending and receiving a lot of color information to and from a remote data source, it would be nice to add a custom transform so that we could use a color string in the data hash for communicating with the server, but use an SC.Color object in the record for use in the application.

To do this, we would register our own SC.RecordAttribute transform using SC.RecordAttribute.registerTransform to map between the raw value of the attribute and the complex object of the property.

For example:

SC.RecordAttribute.registerTransform(SC.Color, {
  /**
    Convert a String in the format 'rgb(###,###,###)' to an SC.Color.
  */
  to: function(stringValue, attr) {
    // If there is a value, convert it to an SC.Color.
    if (!SC.none(stringValue)) {
      stringValue = SC.Color.from(stringValue);
    }

    return stringValue;
  },

  /**
    Convert an SC.Color to a String in the format 'rgb(###,###,###)'
  */
  from: function(colorValue, attr) {
    // If there is a value, convert it to a String.
    if (!SC.none(colorValue)) {
      colorValue = colorValue.toRgb();
    }

    return colorValue;
  }
});

Once you've added a custom transform type, you can use it in any of your records. The following is an example of a pen record that contains a color attribute using our previous transform:

MyApp.Pen = SC.Record.extend({

  color: SC.Record.attr(SC.Color)

});

Although you may not use this functionality right away, it's good to know that it exists and you may find it to be a nice way to clean up your code, if you find you need a lot of data transformations in your application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.172.115