Created
July 22, 2012 17:01
-
-
Save danmartens/3160287 to your computer and use it in GitHub Desktop.
Ember.Resource::find
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var pathToObject = function(path) { | |
var i, parent, part, parts, _len; | |
parent = window; | |
parts = path.split('.'); | |
for (i = 0, _len = parts.length; i < _len; i++) { | |
part = parts[i]; | |
parent = parent[part] || (parent[part] = {}); | |
} | |
return parent; | |
}; | |
Ember.Resource.reopenClass({ | |
find: function(resourceId) { | |
var controller, resource; | |
resourceIdField = this.resourceIdField || 'id'; | |
/* This needs to be set after you define the model class. | |
* App.Post = Em.Resource.extend({}); | |
* | |
* App.Post.reopenClass({ | |
* controller: 'App.store.posts' | |
* }); | |
*/ | |
controller = pathToObject(this.controller); | |
resource = controller.findProperty(resourceIdField, resourceId); | |
if (!resource) { | |
resource = this.create(); | |
resource[resourceIdField] = resourceId; | |
resource.findResource(); | |
controller.pushObject(resource); | |
} | |
return resource; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.App = Em.Application.create(); | |
App.Post = Em.Resource.extend({ | |
resourceUrl: '/', | |
resourceName: 'post' | |
}); | |
App.store = {}; | |
App.store.posts = Em.ResourceController.create({ | |
resourceType: App.Post, | |
content: [] | |
}); | |
App.Post.reopenClass({ | |
controller: 'App.store.posts' | |
}); | |
console.log(App.Post.find(1)); // returns instance of App.Post, fetches from server if necessary | |
// Custom primary key: | |
App.Organism.reopenClass({ | |
controller: 'App.store.organisms', | |
resourceIdField: 'genus' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment