How to bind content with JSON in Ember.js - ember.js

All the examples are using fixed data source in the arraycontroller.content, while I am using dynamic data source which is generated from anther web service and returns a JSON, it won't create an object that I declared in Ember,
here is the code sample:
ET.AppYear = Ember.Object.extend({
text:null,
value:null
});
ET.EmailTypes = Ember.Object.extend();
ET.appYearController = Ember.ArrayController.create({
content: [],
loadYears: function (year) {
if (year != null) {
for (var i = -5; i < 5; i++) {
this.pushObject({ text: year + i, value: year + i });
//.AppYear.create({ text: year + i, value: year + i });
}
}
}
});
ET.selectedAppYearController = Ember.Object.create({
selectedAppYear: '2011',
alertChange: function(){
alert("selected App Year is now " + this.get('selectedAppYear'));
}.observes('selectedAppYear'),
isChanged: function () {
if (this.appYear != null) {
this.set('selection',this.get('content'));
//LoadETByAppYearETTypeID(this.selectedAppYear, ET.selectedEmailTypesController.emailType.email_template_type_id);
}
} .observes('selectedAppYear'),
AppYear: function() {
var ay = ET.appYearController.findProperty('text',this.get('selectedAppYear'));
return ay;
}.property('selectedAppYear')
});
As you can see, I will call ET.appYearController.loadYears(JSON) in an AJAX post back, which will create the content by using this.pushObject, but this is not the ET.AppYear object schema, while I call ET.selectedAppYearController.selectedAppYear, it returns an undefined object, and which really returns an object with {text:xx,value,xx} schema. That's why the selectionBinding also won't work in this case.
So what's the typical solution for this to import JSON elements as defined object and put into content?!

Take a look at the Ember-data library, it was made for your use-case and related use-cases:
https://github.com/emberjs/data

[2014-02-19: Deprecated - I no longer support ember-rest because it is overly simplistic, and would recommend using ember-data for most ember projects. Check out the Ember guides for an overview of ember-data as well as this example project ]
I've created a very simple library to handle working with REST interfaces from Ember:
https://github.com/cerebris/ember-rest
I'm also writing a series of posts about using this library from Rails. The first is here:
http://www.cerebris.com/blog/2012/01/24/beginning-ember-js-on-rails-part-1/
My next post, hopefully coming later today, deals precisely with loading data via AJAX into a collection of Ember objects. For now, you can see this behavior in the sample app as well as the ember-rest.js readme.
If you'd like to avoid using this lib, you might still want to check out the source. The deserialize() method on Ember.Resource is used to import JSON and could also be used with a generic Ember.Object.

Related

Ember - Issue with HTTP POST request

I have written a (very) simple RESTFul Web service to retrieve data from MongoDB using Node, Express and Mongoose.
On the server side, I have this code:
router.route('/products').post(function(req,res){
var product = new Product(req.body);
product.save(function(err){
if(err)
res.send(err);
res.send({message:'Product Added'});
});
When I submit a request from my Ember client, the req.body contains something like the following:
{ attributes:
{ category: 1,
name: 'y',
price: 1,
active: false,
notes: null } }
The attribute names are exactly the same as my mongoose schema. I get no error but the document created in MongoDB is empty (just get the _id and __v fields).
What am I doing wrong. Should I convert the req.body further into ???
A couple things that will help debug:
1) From a quick glance (I haven't used mongoose before) it looks like call back function passed to save takes two arguments.
2) I don't know if your code got cut off, but the sample above was missing a matching });
3) I made the function short circuit itself on error, so you will not see 'Product added' unless that is truly the case.
Try these fixes.
router.route('/products').post(function(req,res){
var product = new Product(req.body);
product.save(function(err, product){
if(err){
return res.send(err);
}
return res.send({message:'Product Added'});
});
});
The issue was related to my lack of familiarity with Ember and Node+Express. The data received in the server is slightly different from what I had first indicated: (first line was missing)
{ product:
{ attributes:
{ category: ... } } }
On the server side I can access my data using req.body.product.attributes (instead of req.body):
router.route('/products').post(function(req,res){
var product = new Product(req.body.product.attributes);
product.save(function(err){
if(err)
res.send(err);
res.send({message:'Product Added'});
});

Ember server side pagination

I'm not trying to provide pagination within the view itself.
My API returns 500 records at a time and if there are more I'd like to automatically load them.
Although my solution right now does make the requests, I don't think it is the best way, but it does work.
App.StructureAdapter = App.ApplicationAdapter.extend({
findHasMany: function(store, record, url) {
// based on the normal `findHasMany` code
var host = Em.get(this, 'host'),
id = Em.get(record, 'id'),
type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.findWithURL(this.urlPrefix(url, this.buildURL(type, id)), 1);
},
findWithURL: function(url, page) {
var that = this;
var completeUrl = url + "?page=" + page;
var nextPage = page + 1;
return this.ajax(completeUrl, 'GET').then(function(data) {
Em.Logger.log("calling then");
if (data.structures.length > 0){
that.findWithURL(url, nextPage);
}
return data;
});
}
});
My questions are:
Is there a better way to automatically get all of the pages for a given request?
How do I properly make sure the relationships are built. My Structure object has parent/children relationships on it, but only the first page of results is actually being associated correctly.
Update
Here is what my json response looks like:
{
"structures": [
{
"id": 6536,
"name": "Building",
"updated_at": "2013-05-21T07:14:54-06:00",
"person_id": 6535,
"notes": ""
},
... 499 more objects ...
]
}
It works properly, it loads the first group just fine. And I can adjust it in the extract/normalize methods if I need to.
Here is my normalize method as it is right now:
App.StructureSerializer = App.ApplicationSerializer.extend({
normalize: function(type, hash, prop) {
// adds the properly link to get children
hash.links = { "children": "structures" };
// change structure_id to parent_id
hash.parent_id = hash.structure_id;
delete hash.structure_id;
return this._super(type, hash, prop);
},
});
Again, the links makes it automatically know where to look for the has many relationship.
Looking at it closer, though the paginated pages actually do get called, they are not loaded into Ember data at all. So maybe if they did get loaded then the relationships would build properly.
Here's the best idea I have, I dunno how well it'd work and you might need to play around with it a bit.
In your StructureRoute, go ahead and return the model as normal, so:
App.StructureRoute = Ember.Route.extend({
model:function() {
return this.store.find('structure');
}
});
That'll fetch your first 500 objects and begin the route transition.
Then in your StructureController, fetch the other models using query parameters like this:
App.StructureController = Ember.ArrayController.extend({
init:function() {
this.loadNextPage(2);
this._super(); // this may not be necessary still, but the docs call for it
},
loadNextPage: function(page) {
var self = this;
var promise = this.store.find('structure',{page:page});
promise.then(function(structures) {
if(structures.get('length') < 500) {
self.loadNextPage(page + 1);
}
});
}
});
So when the StructureController initiates, it'll call the recursive function loadNextPage. This will keep running until it hits a page contains less then 500 models. Hopefully, that'll be the last page. By providing the second parameter to find, Ember should trigger a request to /structure?page=2. Inversely, you could do all of this in the route, if you don't mind the slow load time.
If at all possible, I would suggest modifying your API to add some pagination meta data to your request. Then you can use that metadata to control when to stop the recursive function. You can see how to handle metadata here.
Finally, I'm not sure if that's a typo in your json, but you may need to override your pluralization.
Anywho, hope that helps and I didn't overly simply the problem!
I really don't like this solution, but this does work. Please post if you have a much cleaner way of doing this.
Step 1: Load the Data into Ember Data
Since the data wasn't being loaded into Ember Data for the other pages I had to manually load it. I did that by adjusting the findWithURL function I created above.
findWithURL: function(url, page) {
var that = this;
var completeUrl = url + "?page=" + page;
var nextPage = page + 1;
var store = EditUserApp.__container__.lookup('store:main');
return this.ajax(completeUrl, 'GET').then(function(data) {
if (data.structures.length > 0){
that.findWithURL(url, nextPage);
}
store.pushPayload('structure', data);
return data;
});
},
I feel like there should be a cleaner way to do this, but it works.
Step 2: Rebuild the relationships
For some reason it didn't seem to be rebuilding the child/parent relationships. To take care of that I had to use the didLoad callback inside of the Structure model.
didLoad: function() {
var parent = this.get('parent');
if (parent) {
var that = this;
parent.get('children').then(function(children) {
children.addObject(that);
});
}
},
Any suggestions for how to improve this solution are welcome. Ideally I feel like there should be a better Ember way to handle this whole scenario.

Ember-Data custom adapter for Rhom - FindAll Not working

I am writing an Ember-Data adapter for the Rhom API. I have written the code. I am using it in a simple Todo App. When I create a new item, it gets into the SQLite db. But when I start the app, the already existing ones donot get loaded in the store.
I wrote a console.log in the findAll of my adapter and I can see that it gets an object array from the Rhom API and returns a promise with those results. But why does it not load into the store?
I used the localstorage-adapter as an example and did this. Here is my findAll:
extractVars: function(rhomRecord) {
return rhomRecord.vars();
},
sourceIdToId: function(record) {
record["id"] = record.source_id;
return record;
},
findAll: function(store, type) {
var records = Rho.ORM.getModel(this.model).find('all');
var results = records.map(this.extractVars);
var results = results.map(this.sourceIdToId);
console.log(results);
return Ember.RSVP.resolve(results);
},
As you can see, the console.log prints the following out and its just an array of objects that contain what I need. When I tried with the locastorate, it also returned a same kind of objects.
What do I do?
PS: The extractVars and sourceIdtoId are auxillary to propery extract the objects from the records returned by Rhom.
I'm not really sure if this will help you but I guess just because .find() returns a promise you should use the .then() callback to resolve your model:
findAll: function(store, type) {
return Rho.ORM.getModel(this.model).find('all').then(function(records) {
var results = records.map(this.extractVars);
var results = results.map(this.sourceIdToId);
console.log(results);
return Ember.RSVP.resolve(results);
});
}
Hope it helps.

Ember 1.0 Final Internet Explorer 8 and 9 (History API - pushState and replaceState)

I was under the impression that Ember was well tested under some older versions of IE. However, upon finally firing up my near complete app (form wizard). I'm noticing IE is complaining about replaceState and pushState, two methods that are not supported according to http://caniuse.com/#search=pushState
Are there any workarounds for this?
SCRIPT438: Object doesn't support property or method 'replaceState'
get(this, 'history').replaceState(state, null, path);
UPDATE: As of Ember 1.5.0+ I can confirm that they added 'auto' which should eliminate the need for the example below.
App.Router.reopen({
location: 'auto'
});
Original Answer:
Apparently you need to feature detect the history API:
if (window.history && window.history.pushState) {
App.Router.reopen({
location: 'history'
});
}
There is no work around. If you need to use real URLs (/users) instead of hash URLs (/#/users) then you have to either exclude IE 8 & 9 from your list of supported browsers, or you need to use Ember in a "progressive enhancement" manner, still serve valid content from the server for each real URL that is visited, and use feature detection to selectively enable your Ember app.
To properly support both pushSate and non-pushState browsers, you need to have a translator between the 2 different state mechanisms.
For example, let's say your rootURL is '/admin/' and you start with this URL:
/admin/users/123
For IE8/9, you'll want to redirect the user to '/admin/#/users/123' before Ember's routing mechanism takes over. Likewise, if you start with this URL:
/admin/#/users/123
...then for browsers that support pushState, you'll want to replace the state to '/admin/users/123' before Ember's routing mechanism takes over.
This is the default behavior of Backbone's router and it works fairly well.
To achieve this result in Ember, you can do something like this, which was inspired by Backbone's source code:
App.Router.reopen({
rootURL: '/admin/',
init: function () {
this.translateRoute();
this._super();
},
translateRoute: function () {
var hasPushState = window.history && window.history.pushState;
var atRoot = window.location.pathname === this.rootURL;
var fragment = decodeURIComponent(window.location.pathname);
if (!fragment.indexOf(this.rootURL))
fragment = fragment.substr(this.rootURL.length);
if (hasPushState)
this.location = 'history';
// If we started with a route from a pushState-enabled browser,
// but we're currently in a browser that doesn't support it...
if (!hasPushState && !atRoot) {
window.location.replace(this.rootURL + '#/' + fragment);
return;
}
// If we started with a hash-based route,
// but we're currently in a browser that supports pushState...
if (hasPushState && atRoot && window.location.hash) {
fragment = window.location.hash.replace(/^(#\/|[#\/])/, '');
window.history.replaceState({}, document.title, window.location.protocol + '//' + window.location.host + this.rootURL + fragment);
}
}
});

Ember-Data: How to use `DS.Adapter.findHasMany`

UPDATE
Note that this question applies to Ember Data pre-1.0 beta, the mechanism for loading relationships via URL has changed significantly post-1.0 beta!
I asked a much longer question a while back, but since the library has changed since then, I'll ask a much simpler version:
How do you use DS.Adapter.findHasMany? I am building an adapter and I want to be able to load the contents of a relationship on get of the relationship property, and this looks like the way to do it. However, looking at the Ember Data code, I don't see how this function can ever be called (I can explain in comments if needed).
There's not an easy way with my backend to include an array of ids in the property key in the JSON I send--the serializer I'm using doesn't allow me to hook in anywhere good to change that, and it would also be computationally expensive.
Once upon a time, the Ember Data front page showed an example of doing this "lazy loading"...Is this possible, or is this "Handle partially-loaded records" as listed on the Roadmap, and can't yet be done.?
I'm on API revision 11, master branch as of Jan 15.
Update
Okay, the following mostly works. First, I made the following findHasMany method in my adapter, based on the test case's implementation:
findHasMany: function(store, record, relationship, details) {
var type = relationship.type;
var root = this.rootForType(type);
var url = (typeof(details) == 'string' || details instanceof String) ? details : this.buildURL(root);
this.ajax(url, "GET", {
success: function(json) {
var serializer = this.get('serializer');
var pluralRoot = serializer.pluralize(root);
var hashes = json[pluralRoot]; //FIXME: Should call some serializer method to get this?
store.loadMany(type, hashes);
// add ids to record...
var ids = [];
var len = hashes.length;
for(var i = 0; i < len; i++){
ids.push(serializer.extractId(type, hashes[i]));
}
store.loadHasMany(record, relationship.key, ids);
}
});
}
Prerequisite for above is you have to have a well-working extractId method in your serializer, but the built-in one from RESTAdapter will probably do in most cases.
This works, but has one significant problem that I haven't yet really gotten around in any attempt at this lazy-loading approach: if the original record is reloaded from the server, everything goes to pot. The simplest use case that shows this is if you load a single record, then retrieve the hasMany, then later load all the parent records. For example:
var p = App.Post.find(1);
var comments = p.get('comments');
// ...later...
App.Post.find();
In the case of only the code above, what happens is that when Ember Data re-materializes the record it recognizes that there was already a value on the record (posts/1), tries to re-populate it, and follows a different code path which treats the URL string in the JSON hash as an array of single-character IDs. Specifically, it passes the value from the JSON to Ember.EnumerableUtils.map, which understandably enumerates the string's characters as array members.
Therefore, I tried to work around this by "patching" DS.Model.hasManyDidChange, where this occurs, like so:
// Need this function for transplanted hasManyDidChange function...
var map = Ember.EnumerableUtils.map;
DS.Model.reopen({
});
(^ Never mind, this was a really bad idea.)
Update 2
I found I had to do (at least) one more thing to solve the problem mentioned above, when a parent model is re-loaded from the server. The code path where the URL was getting split into single-characters was in DS.Model.reloadHasManys. So, I overrode this method with the following code:
DS.Model.reopen({
reloadHasManys: function() {
var relationships = get(this.constructor, 'relationshipsByName');
this.updateRecordArraysLater();
relationships.forEach(function(name, relationship) {
if (relationship.kind === 'hasMany') {
// BEGIN FIX FOR OPAQUE HASMANY DATA
var cachedValue = this.cacheFor(relationship.key);
var idsOrReferencesOrOpaque = this._data.hasMany[relationship.key] || [];
if(cachedValue && !Ember.isArray(idsOrReferencesOrOpaque)){
var adapter = this.store.adapterForType(relationship.type);
var reloadBehavior = relationship.options.reloadBehavior;
relationship.name = relationship.name || relationship.key; // workaround bug in DS.Model.clearHasMany()?
if (adapter && adapter.findHasMany) {
switch (reloadBehavior) {
case 'ignore':
//FIXME: Should probably replace this._data with references/ids, currently has a string!
break;
case 'force':
case 'reset':
default:
this.clearHasMany(relationship);
cachedValue.set('isLoaded', false);
if (reloadBehavior == 'force' || Ember.meta(this).watching[relationship.key]) {
// reload the data now...
adapter.findHasMany(this.store, this, relationship, idsOrReferencesOrOpaque);
} else {
// force getter code to rerun next time the property is accessed...
delete Ember.meta(this).cache[relationship.key];
}
break;
}
} else if (idsOrReferencesOrOpaque !== undefined) {
Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load many records but your adapter does not implement `findHasMany`", adapter.findHasMany);
}
} else {
this.hasManyDidChange(relationship.key);
}
//- this.hasManyDidChange(relationship.key);
// END FIX FOR OPAQUE HASMANY DATA
}
}, this);
}
});
With that addition, using URL-based hasManys is almost usable, with two main remaining problems:
First, inverse belongsTo relationships don't work correctly--you'll have to remove them all. This appears to be a problem with the way RecordArrays are done using ArrayProxies, but it's complicated. When the parent record gets reloaded, both relationships get processed for "removal", so while a loop is iterating over the array, the belongsTo disassociation code removes items from the array at the same time and then the loop freaks out because it tries to access an index that is no longer there. I haven't figured this one out yet, and it's tough.
Second, it's often inefficient--I end up reloading the hasMany from the server too often...but at least maybe I can work around this by sending a few cache headers on the server side.
Anyone trying to use the solutions in this question, I suggest you add the code above to your app, it may get you somewhere finally. But this really needs to get fixed in Ember Data for it to work right, I think.
I'm hoping this gets better supported eventually. On the one hand, the JSONAPI direction they're going explicitly says that this kind of thing is part of the spec. But on the other hand, Ember Data 0.13 (or rev 12?) changed the default serialized format so that if you want to do this, your URL has to be in a JSON property called *_ids... e.g. child_object_ids ... when it's not even IDs you're sending in this case! This seems to suggest that not using an array of IDs is not high on their list of use-cases. Any Ember Data devs reading this: PLEASE SUPPORT THIS FEATURE!
Welcome further thoughts on this!
Instead of an array of ids, the payload needs to contain "something else" than an array.
In the case of the RESTAdapter, the returned JSON is like that:
{blog: {id: 1, comments: [1, 2, 3]}
If you want to handle manually/differently the association, you can return a JSON like that instead:
{blog: {id: 1, comments: "/posts/1/comments"}
It's up to your adapter then to fetch the data from the specified URL.
See the associated test: https://github.com/emberjs/data/blob/master/packages/ember-data/tests/integration/has_many_test.js#L112
I was glad to find this post, helped me. Here is my version, based off the current ember-data and your code.
findHasMany: function(store, record, relationship, details) {
var adapter = this;
var serializer = this.get('serializer');
var type = relationship.type;
var root = this.rootForType(type);
var url = (typeof(details) == 'string' || details instanceof String) ? details : this.buildURL(root);
return this.ajax(url, "GET", {}).then(function(json) {
adapter.didFindMany(store, type, json);
var list = $.map(json[relationship.key], function(o){ return serializer.extractId(type, o);});
store.loadHasMany(record, relationship.key, list);
}).then(null, $.rejectionHandler);
},
for the reload issue, I did this, based on code I found in another spot, inside the serializer I overrode:
materializeHasMany: function(name, record, hash, relationship) {
var type = record.constructor,
key = this._keyForHasMany(type, relationship.key),
cache = record.cacheFor('data');
if(cache) {
var hasMany = cache.hasMany[relationship.key];
if (typeof(hasMany) == 'object' || hasMany instanceof Object) {
record.materializeHasMany(name, hasMany);
return;
}
}
var value = this.extractHasMany(type, hash, key);
record.materializeHasMany(name, value);
}
I'm still working on figuring out paging, since some of the collections I'm working with need it.
I got a small step closer to getting it working with revision 13 and based myself on sfossen's findHasMany implementation. For an Ember model 'Author' with a hasMany relationship 'blogPosts', my rest api looks like '/api/authors/:author_id/blog_posts'. When querying the rest api for an author with id 11 the blog_posts field reads '/authors/11/blog_posts'.
I now see the related blog posts being returned by the server, but Ember still throws an obscure error that it can not read 'id' from an undefined model object when rendering the page. So I'm not quite there yet, but at least the related data is correctly requested from the rest service.
My complete adapter:
App.Adapter = DS.RESTAdapter.extend({
url: 'http://localhost:3000',
namespace: 'api',
serializer: DS.RESTSerializer.extend({
keyForHasMany: function(type, name) {
return Ember.String.underscore(name);
},
extractHasMany: function(record, json, relationship) {
var relationShip = relationship + '_path';
return { url : json[relationShip] }
}
}),
findHasMany: function(store, record, relationship, details) {
var type = relationship.type;
var root = this.rootForType(type);
var url = this.url + '/' + this.namespace + details.url;
var serializer = this.get('serializer');
return this.ajax(url, "GET", {}).then(
function(json) {
var relationship_key = Ember.String.underscore(relationship.key);
store.loadMany(type, json[relationship_key]);
var list = $.map(json[relationship_key], function(o){
return serializer.extractId(type, o);}
);
store.loadHasMany(record, relationship.key, list);
}).then(null, $.rejectionHandler);
}
});
Here is my solution but it is on Ember-data 0.14, so the world has moved on, even if we are still on this code base:
findHasMany: function(store, record, relationship, details) {
if(relationship.key !== 'activities') {
return;
}
var type = relationship.type,
root = this.rootForType(type),
url = this.url + details.url,
self = this;
this.ajax(url, "GET", {
data: {page: 1}
}).then(function(json) {
var data = record.get('data'),
ids = [],
references = json[relationship.key];
ids = references.map(function(ref){
return ref.id;
});
data[relationship.key] = ids;
record.set('data', data);
self.didFindMany(store, type, json);
record.suspendRelationshipObservers(function() {
record.hasManyDidChange(relationship.key);
});
}).then(null, DS.rejectionHandler);
},
I found replacing the data with the ids worked for me.