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.