Skip to content

Instantly share code, notes, and snippets.

@andrewdavey
Created March 16, 2012 16:49
Show Gist options
  • Save andrewdavey/2051062 to your computer and use it in GitHub Desktop.
Save andrewdavey/2051062 to your computer and use it in GitHub Desktop.
// General resource format:
{
metadata: [ // array of metadata objects
{ "<any-string1>": <any-json> },
{ "<any-string2>": <any-json> },
"<any-string3>" // short hand for { "<any-string3>": null },
...
],
data: <any-javascript-value> // e.g. string, number, boolean, object, array
}
This resource format is parsed into a ViewModel object:
function ViewModel(resource) {
this.data = ko.observable(resource.data);
var behaviors = Application.getBehaviors(resource.metadata); // returns behaviors that match the metadata.
behaviors.forEach(function(behavior) {
// a behavior modifies the view model, adding properties, methods, etc.
behavior.applyTo(viewModel);
});
}
var vm = new ViewModel(resource);
// bind to UI, etc..
// Example Promotion resource
{
// Metadata about the resource data
metadata: [
"PromotionResource", // Imagine that the PromotionResourceViewModel class is a behavior that provides resource-level customization
],
// Resource data is stored in the 'data' property
data: [
{
metadata: [
{ name: "Promotion Name" } // client will look for a behavior called 'name' to apply. It will set a name property on the view model.
],
data: "10% off Nike trainers"
},
{
metadata: [
{ name: "Description" },
"newlineToBr" // client should generate <br/> tags for "\n" in the data
],
data: "Get 10% off Nike trainers when you spend over $100 this Spring.\nAct fast, offer ending soon!"
},
{
metadata: [
{ name: "Schedule" },
"link" // client should render something like: <a href="{href}" rel="{rel}">{title}</a>
],
data: { href: "...", rel: "schedule", title: "Spring 2012" }
},
{
metadata: [
{ name: "Trigger" },
"/trigger-types/order-total"
],
data: [
{ data: "Trigger on order total", metadata: [ { name: "Trigger type" } ] },
{ data: 100, metadata: [ { "currency": "USD" } ] },
{ data: 60, metadata: [ { "currency": "GBP" } ] },
{ data: 120, metadata: [ { "currency": "EUR" } ] }
]
},
{
metadata: [
{ name: "Reward" },
"/reward-types/percentage-discount-on-product"
],
data: [
{ metadata: [ "percentage", { name: "Amount off product" } ], data: 0.1 } },
{ metadata: [ "link" ], data: { href: "/skus/NIKE1234", rel: "sku", title: "Nike Air Trainers" } }
]
},
{
metadata: [
{ form: { confirmation: "Delete this promotion?" } }
],
data: {
rel: "delete",
method: "DELETE",
href: "...",
title: "Delete Promotion"
}
},
{
metadata: [ "link" ],
data: { rel: "edit", href: "...", title: "Edit Promotion" } // linking to edit form as separate resource. Could make an inline form as well.
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment