Monkeypatching Sproutcore with Mixins

by Evin

Have you ever needed a function specific to your application, but you want it to work like the rest of Sproutcore? You can use the power of mixins to monkey patch Sproutcore in your application. I needed a call on SC.Record like resourceUrl() but I needed something like pluralResourceUrl() because the RESTful API on the back end had a different url for lists of objects that asking for a single object…


In my model, I wanted to be able to do things like this:

myApp.Recipe = SC.Record.extend(
/** @scope myApp.Recipe.prototype */ {
 
  resourceURL: 'recipe',
  pluralResourceURL: 'recipies',
  properties: ['id', 'name', 'createdBy', 'createdAt', 'updatedBy', 'updatedAt', 'ingredients', 'directions'],
  dataSource: myApp.server,
 
  // MORE CODE BELOW...
 
}) ;

Then, in my custom server, I wanted to be able to call things like this in the listFor:

listFor: function(opts) {
  var recordType = opts.recordType ;
  var resource = recordType.pluralResourceURL() || recordType.resourceURL(); // changed to plural for WCF crappyness
  if (!resource) return false;
 
  // MORE CODE BELOW...

So what are we to do? Monkeypatch SC.Record with a mixin! I looked up in the SC code to see how they do the resourceUrl() and then added the following to the bottom of my core.js file:

// Added Mixin Function to SC.Record to handle our plural resource API
SC.Record.mixin(
/** @static SC.Record */ {
  pluralResourceURL: function() { return this.prototype.pluralResourceURL; }
});

Success! Now any model that I create I can add a pluralResourceUrl attribute and it will work seamlessly with my server, creating the correct url it needed. With this pattern you can monkeypatch pretty much anything that you want on the SC library for you own needs.

This entry was posted on Friday, January 9th, 2009 at 4:10 am and is filed under Coding Tutorials, Sproutcore. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply