Real example of Ember.js - ember.js

Please give me real example of emberjs. This example will help me understand how to write in emberjs.
Description of example:
Please open this link first:
http://jsfiddle.net/kwladyka/KhQvu/2/
(this is prototype to better understand what i am talking about)
And then read:
Emberjs download Groups.owner by JSON from json.php?name=groups-owner&user_id=58 and Groups.member from json.php?name=groups-member&user_id=58. Both in Groups.all.
In object Groups i have all values of arrays what i read from JSON. I want example read something like that: owner[2][name].
Then from CreateGroupsSelect i want read Groups.all and create ListBox with values group_id and names name. And when i change select i want change <p>You select {{name}} with id {{id}}</p> and refresh data in other View emberjs objects.
I will be really gratefull for help. I am trying learn emberjs but i totally block with this example.
Ok, so i have many questions :)
1)
How to bind value form input select to attribute in controller
var val = $('select option:selected').val();
Where can i find list of possible ussage like a "select option:selected". Any documentatin for that? Where?
2)
"didInsertElement"
How can i know i should use this? How should i looking in documentation to know that? Why not Ember.Select.Change for that?
3)
Why author use "View", i thought for select i should use class "select"?
4)
Seriously this is my first language when i fill all is so random and i dont have any idea how to know what i can write and where. I fill really stupid with that. Any hint how to understand that?
5)
Ok so step by step...
First of all i want read JSON and prepare data to use.
Organizer.Groups = Ember.Object.extend({
owner: [],
member: [],
all: function(){
var owner = this.get('owner');
var member = this.get('member');
return owner.concat(member);
}.property('owner', 'member'),
});
a) "Object" is good choice for that?
b) I want fill "owner" by array from "json.php?name=groups-owner&user_id=58". How to do that? Did i define "owner" corretly or i should write "ArrayController" or something else for that? Mayby just "Array" or "ArrayProxy"? I am filling so confuse now.
c) How should i initiate load data from JSON? I want do this only one time on the beginning.
PS Sorry if you fill my questions are so stupid but i really dont know answers and i dont hide this :)

Here is an example of how to work with select menu in Ember js
select dropdown with ember
Here is an example of working with routes and outlet helper
Right way to do navigation with Ember
If you use routing make sure you have ember latest, routing is still not released.
Router / StateManager - can't make it work
When using latest emberjs refer to documentation in source code, the documentation in ember site will be for present stable release.
https://github.com/emberjs/ember.js
The links to routing is provided from your fidle title "Router with dynamic routes"
It will be hard to solve your complete problem, give it a try starting with the routing example from above, when you are stuck ask more specific questions, we'll be happy to help.
EDIT : Some of the links are already outdated.

Related

Not possible to use shorthand route handlers if RestSerializer is used? (ember-cli-mirage)

I set up a simple Ember Twiddle to show you my error that is occurring when trying to update a model.
It's considerable that I'm using ember-cli-mirage for mocking the data.
According to the docs, I created a shorthand route that should handle the PUT request.
It does, but with the error: Your handler for the url /api/shops/1 threw an error: Cannot convert undefined or null to object
When using the JSONAPISerializer, everything is working with shorthands (mirage/config.js) and I'm able to update models, but in my case I have to use the RESTSerializer with serialized IDs in the responses.
The request payload when I'm sending the model's attrs are without Id at the end of the property name, f.e.:
// attrs object in PUT request
{
name: "Shop 1",
city: "1" // belongsTo relationship,
}
Now Mirage is trying to find those properties on the respective database model that has to be updated, but cannot find it, because in the database it's cityId and not just city...
I also found this issue report and it’s working, but I was hoping I could avoid something like this. As far as I can remember, in previous versions of ember-cli-mirage (v0.1.x) it was also not needed to override the normalize method in the serializer to be able to make use of the RestSerializer with serializedIds…
My question is:
Is there a way to stick to shorthand route handlers only, or do I really have to write a helper or other custom solution only because I have to use the RestSerializer?
That would be really sad, but at least I would know then.
Thanks for your support!
Short answer: it looks like you need the custom serializer for now until the bug fix for it is merged.
Long answer: that issue looks to be an issue that occurred in the 0.2 -> 0.3 upgrade for Mirage, likely because of underlying DB changes made in Mirage. It'll probably get fixed, but for now you'll need to work around it.

Computed property doesn't update

I have the following Ember.js code (in a model):
subdata: DS.hasMany('App.Subdata'),
message_subdata: function() {
return this.get('subdata').filterBy('tag', 'message');
}.property('subdata', 'subdata.#each')
This worked just fine in RC7. In RC8+, I know they made changes to the way that observers fire, but for the life of me, I can't figure out how to get it working again. I know it says to make sure to call get before observing the property, but I'm using this property in a template, so doesn't the template have to get the property?
Right now, when the page first loads, none of the data gets shown because none of the subdata is loaded yet. That's how it's always been. But in RC7, as soon as the records were loaded, it would fire the observers and update the page. Now, for some reason, the observers aren't being update and the page won't update. The only way I can seem to force it to update is by changing the subdata property (or simulating a change with notifyPropertyChange).
How can I get my properties to work as they did in RC7?
EDIT: I thought I would give a quick update on how I did sorting AND filtering. It's probably not the best way, but I fiddled for a while to land on this solution.
subdata: DS.hasMany('App.Subdata'),
message_subdata_filtered: Ember.computed.filterBy('subdata', 'tag', 'message'),
message_subdata: Ember.computed.sort('message_subdata_filtered', function(a,b) {
return a.get('timestamp') - b.get('timestamp');
});
There might be a way to do it in one line, but this works for me.
I guess the new way of doing computed arrays is by using something like this:
subdata: DS.hasMany('App.Subdata'),
message_subdata: Ember.computed.filterBy('subdata', 'tag', 'message')

RESTful API and Foreign key handling for POSTs and PUTs

I'm helping develop a new API for an existing database.
I'm using Python 2.7.3, Django 1.5 and the django-rest-framework 2.2.4 with PostgreSQL 9.1
I need/want good documentation for the API, but I'm shorthanded and I hate writing/maintaining documentation (one of my many flaws).
I need to allow consumers of the API to add new "POS" (points of sale) locations. In the Postgres database, there is a foreign key from pos to pos_location_type. So, here is a simplified table structure.
pos_location_type(
id serial,
description text not null
);
pos(
id serial,
pos_name text not null,
pos_location_type_id int not null references pos_location_type(id)
);
So, to allow them to POST a new pos, they will need to give me a "pos_name" an a valid pos_location_type. So, I've been reading about this stuff all weekend. Lots of debates out there.
How is my API consumers going to know what a pos_location_type is? Or what value to pass here?
It seems like I need to tell them where to get a valid list of pos_locations. Something like:
GET /pos_location/
As a quick note, examples of pos_location_type descriptions might be: ('school', 'park', 'office').
I really like the "Browseability" of of the Django REST Framework, but, it doesn't seem to address this type of thing, and I actually had a very nice chat on IRC with Tom Christie earlier today, and he didn't really have an answer on what to do here (or maybe I never made my question clear).
I've looked at Swagger, and that's a very cool/interesting project, but take a look at their "pet" resource on their demo here. Notice it is pretty similar to what I need to do. To add a new pet, you need to pass a category, which they define as class Category(id: long, name: string). How is the consumer suppose to know what to pass here? What's a valid id? or name?
In Django rest framework, I can define/override what is returned in the OPTION call. I guess I could come up with my own little "system" here and return some information like:
pos-location-url: '/pos_location/'
in the generic form, it would be: {resource}-url: '/path/to/resource_list'
and that would sort of work for the documentation side, but I'm not sure if that's really a nice solution programmatically. What if I change the resources location. That would mean that my consumers would need to programmatically make and OPTIONS call for the resource to figure out all of the relations. Maybe not a bad thing, but feels like a little weird.
So, how do people handle this kind of thing?
Final notes: I get the fact that I don't really want a "leaking" abstaction here and have my database peaking thru the API layer, but the fact remains that there is a foreign_key constraint on this existing database and any insert that doesn't have a valid pos_location_type_id is raising an error.
Also, I'm not trying to open up the URI vs. ID debate. Whether the user has to use the pos_location_type_id int value or a URI doesn't matter for this discussion. In either case, they have no idea what to send me.
I've worked with this kind of stuff in the past. I think there is two ways of approaching this problem, the first you already said it, allow an endpoint for users of the API to know what is the id-like value of the pos_location_type. Many API's do this because a person developing from your API is gonna have to read your documentation and will know where to get the pos_location_type values from. End-users should not worry about this, because they will have an interface showing probably a dropdown list of text values.
On the other hand, the way I've also worked this, not very RESTful-like. Let's suppose you have a location in New York, and the POST could be something like:
POST /pos/new_york/
You can handle /pos/(location_name)/ by normalizing the text, then just search on the database for the value or some similarity, if place does not exist then you just create a new one. That in case users can add new places, if not, then the user would have to know what fixed places exist, which again is the first situation we are in.
that way you can avoid pos_location_type in the request data, you could programatically map it to a valid ID.

Ember data entity id generation

When new model is created and saved with RESTAdapter its Id property is undefined, because my backend is responsible for id generation. So when I return to grid there is 2 same entities: first - with empty Id (from RESTAdapter cache, I think) and second - with correct Id returned from backend.
Any ideas? Maybe it is posiible to disable RESTAdapter cache?
UPDATE
My code for entity creation.
submit:function () {
var manager = App.store.createRecord(App.Manager, {
firstName:this.get('firstName'),
lastName:this.get('lastName'),
speciality:this.get('speciality')
});
App.store.commit();
this.get('controller').transitionTo('managers');
return false;
}
NEW UPDATE
Thanks to Mike Grassotti hints. Here some details for my issue.
One antity have Id, another have no Id.
If I remove App.store.commit() code, there is no POST to server and only entity without Id will be displayed.
This entity has isLoaded=false and isError=true.
When new model is created and saved with RESTAdapter its Id property is undefined, because my backend is responsible for id generation.
Right, but there is nothing unusual about this - ember expects id generation to be done by the backend.
So when I return to grid there is 2 same entities: first - with empty Id (from RESTAdapter cache, I think) and second - with correct Id returned from backend.
OK. What do you mean by same 2 entities - surely they are different js objects. Try logging each of them to console like this:
console.log(entityOne.toString());
console.log(entityTwo.toString());
Any ideas?
There are many things that could cause this to happen. Sounds like somehow you are creating two new records and saving just one of them. Or could be the API response does not match what ember expects, causing an extra record to get created.
Try to enable logging on your records, then watch console so you can see what's going on as your model is saved. Hopefully this will give you some insight into when/how the extra record is being created.
record.set("stateManager.enableLogging", true)
Inspect browser communication with your api and compare JSON to see if it matches what the ember rest adapter expects.
Post that JSON and the rest of your source code (model definition, etc.) to Stack Overflow, maybe a second set of eyes will help.
Check this post for some other debugging tips: http://www.akshay.cc/blog/2013-02-22-debugging-ember-js-and-ember-data.html
Maybe it is posiible to disable RESTAdapter cache?
RESTAdapter does not maintain a separate cache of model objects. And since you are not trying to do anything special, there should be no need to take a step like that.
Many thanks to Mike Grassotti, I have found an answer to my question.
The good question was
With App.store.commit() back in, what does the JSON response from
server look like?
+1 for that comment.
I can't find any info in ember-data documentation for that, so some links still would be helpful for me. I change the result returned from backend and everything works fine now.
{
"manager": {
"firstName": "test",
"lastName": "test",
"speciality": "test",
"id": "acd325ac-03eb-419e-be8a-d4ac42e8c235"
}
}

how to load data to recursive dataView in extjs?

I have a recursive template.
new Ext.XTemplate(
'<tpl for="."><div>'+
'<div class="select">{text}</div>'+
'{[this.putChildren(values)]}'+
' </div></tpl>'
,
{
putChildren:function(values){
if(values.children){
Ext.each(values.children,function(child,index,arr){
return this.apply(values.children);
}
})
I set itemSelector:'select'
The thing is that when I load the data I get an error "records[i] is undefined" and when I set a listener the event is fired on every click but I get item=undefined on every node except the root.
I cant set a treeStore because dataview only excepts store or jsonstore. (maybe I'm doing something wrong?)
so I have a simple question how can I draw a tree using data view and a store?
I couldn't find any good recourse for this...
actually I have a template like this
http://www.youtube.com/watch?v=UhBjMws1H10&t=35m52s
I just cant load the data correctly...
do I need Store or TreeStore or something else?
thnx in advance
So why not use tree Panel?
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.tree.Panel
Have you ever solved this problem? Having the exact same issue. Although I haven't spent a lot of time with it for now.
Maybe it's useful for you to iterate directly through the children.
So, instead of
<tpl for=".">
i think you can directly use
<tpl for="children">
This makes it possible to use values as a variable already for each child.