ember-model
A lightweight model library for Ember.js
This screencast : http://www.embercasts.com/episodes/getting-started-with-ember-model used Ember.model
to create a person model like this:
App.Person = Ember.Model.extend({
name : Ember.attr()
})
The docs give this example using Ember.Object
App.Person = Ember.Object.extend({
say : function(thing) {
alert(thing);
}
});
Further, under defining models section this example is given which uses DS.model
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
birthday: DS.attr('date'),
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName')
});
What is the difference between these three and when to use which?
Source: (StackOverflow)
I've got this ember application:
Ember : 1.3.2
Ember Model : 0.0.11
Handlebars : 1.3.0
jQuery : 1.9.1
Using this resource map:
App.Router.map(function () {
this.resource('dimensions', function() {
this.resource('dimension', { path: ':dimension_id'}, function () {
this.resource('value', { path: 'values/:value_id' });
});
});
});
And this allows me to embed {{outlet}} in "dimensions" template that fills with "dimension" template, and embed {{outlet}} in "dimension" template that fills with "value" template as well.
All works very well except for the link-to helper in the "value" template, that does not accept more params nor accepts other models as described in ember API documentation.
Which is the best way of dealing with link-to in deeply nested routes?
I've got this fiddle to show my problem:
http://jsfiddle.net/vsiguero/pQpE3/5/
Thanks for your help!
Source: (StackOverflow)
I have extended the program given in this stackoverflow answer to have a program that deletes all the records all at once. However, the deletion happens only in batches and does not delete everything all at once.
Here is a snippet of the function I am using in this JSBin.
deleteAllOrg: function(){
this.get('store').findAll('org').then(function(record){
record.forEach(function(rec) {
console.log("Deleting ", rec.get('id'));
rec.deleteRecord();
rec.save();
});
record.save();
});
}
Any idea how the program can be modified such that all records can be deleted at once?
I have also tried model.destroy() and model.invoke('deleteRecords') but they don't work.
Any help is greatly appreciated. Thanks for your help!
Source: (StackOverflow)
I have started using Ember Model, but the JSON data is not getting loaded into the view. Moreover, I am not getting errors or warnings on console.
Here's my app.js,
App = Ember.Application.create({});
App.IndexRoute = Ember.Route.extend({
renderTemplate : function(controller) {
this.render('MyTemplate', {
controller : 'Index'
});
},
model : function() {
return App.MyTemplateModel.find();
}
});
App.IndexController = Ember.ArrayController.extend({
});
App.MyTemplateModel = Ember.Model.extend({
id : Ember.attr(),
last_name : Ember.attr(),
first_name : Ember.attr(),
suffix : Ember.attr(),
expiration : Ember.attr()
});
App.MyTemplateModel.url = "http://ankur1.local/index.php/api/example/users/";
App.MyTemplateModel.adapter = Ember.RESTAdapter.create();
var existing = App.MyTemplateModel.find();
App.MyTemplateModel.camelizeKeys = true;
and Here's my HTML,
<body>
<script type="text/x-handlebars" data-template-name="myTemplate">
<input type="text" id="name" placeholder="name!"/>
<button {{action clickButton}} >Button</button>
{{view Ember.TextField valueBinding="userName"}}
<label >{{userName}}</label>
{{#each item in model}}
<tr><td>
{{id}} <small> {{item.first_name}}</small>
</td></tr>
{{/each}}
</script>
<script type="text/x-handlebars">
<h1>Application Template</h1>
{{outlet}}
</script>
</body>
What I might be missing in my code?
Moreover, I can get individual values on the console using,
var u = App.MyTemplateModel.find(1);
u.get('first_name');
Source: (StackOverflow)
I have a collection of comments and a collection of posts.
App.Router.map(function () {
this.resource("posts", {
path: "/posts"
});
this.resource("post", {
path: "/:post_id"
}, function () {
this.resource("comments", {
path: "/comments"
});
});
});
App.Post = Ember.Model.extend({
id: attr(),
name: attr(),
comments: Ember.hasMany("App.Comment", {
key: 'comments'
})
if embedded = comments: Ember.hasMany("App.Comment", {
key: 'comments',
embedded: true
})
});
App.Post.url = "/posts";
App.Comment = Ember.Model.extend({
id: attr(),
message: attr(),
post: Ember.belongsTo('App.Post', {
key: 'post'
})
});
How can I either:
- Create a new embedded comment.
- Create a non-embedded comment and have that creation add the
comment_id
into comment_ids: []
on the Post model.
I can get the post_id
to enter into the comments if non-embedded, but am having difficulty getting the comment_id
added into the post.
Source: (StackOverflow)
I'm using a cross domain REST api.
I have defined my custom REST adapter to trigg my API.
Pb is to remove the ".json" automaticaly set by ember-model.
How to configure my adapter to avoid setting my "replace function" (url=url.replace('.json', '');)
App.Book.adapter = Ember.RESTAdapter.create({
ajaxSettings: function(url, method) {
var authorization= "Basic " + btoa("login" + ":" + "pwd");
url=url.replace('.json', '');
return {
url: url,
type: method,
dataType: "json",
headers: {
"Authorization": authorization
},
};
}
});
App.Certificate.url='http://mysite/api/v1/books';
Source: (StackOverflow)
With the following queries exposed by my back end:
GET /api/foos
- returns a list of all Foos, suitable for display within a master list
GET /api/foos/:foo_id
- returns a single Foo, with more detailed information, suitable for display within a detail view
My front end displays a list of Foos on the left and when one of them is clicked, the outlet on the right (in the outlet) displays its detailed version.
{{#each foo in model}}
{{#link-to 'foo' foo}}{{foo.name}}{{/link-to}}
{{/each}}
{{outlet}}
I am using ember-model to store my models, and have implemented App.Foo.adapter
's find
and findAll
hooks, such that when they are invoked, they hit the back end APIs described above correctly.
When my app hits the GET /api/foos
(via findAll
) first, and then subsequently when the user clicks on the Foo, and ember-model doesn't hit GET /api/foos/:foo_id
because it doesn't invoke the find
hook, because it realises that that particular model is already in the cache.
This is great, because why fetch something again, when we know that we already have it in memory.
However, in my app, this assumption is insufficient. I have to further check if I have got the full version of that Foo, e.g. !!aFoo.get('propertyOnlyInDetailedVersion')
, and otherwise I would like to force Foo to fetch again.
How can I go about doing this - how do I make ember-model re-fetch an object that has already been fetched prior?
Source: (StackOverflow)
I have created FIXTURES
using ember-model, but i am not able to use following node on template
"logged_in": {
"id" : "1",
"logged": true,
"username": "sac1245",
"account_id": "4214"
}
I have implemented belongsTo
relation for this node but it throwing one error : Uncaught Error: Ember.Adapter must implement findQuery
Here i have listed my model code :
Astcart.Application = Ember.Model.extend({
name: Ember.attr(),
logo_url : Ember.attr(),
list: Ember.hasMany('Astcart.List', {key: 'list', embedded: true}),
logged_in: Ember.belongsTo('Astcart.Logged_in', {key: 'logged_in'})
});
Astcart.List = Ember.Model.extend({
name: Ember.attr()
});
Astcart.Logged_in = Ember.Model.extend({
id: Ember.attr(),
logged: Ember.attr(),
username: Ember.attr(),
account_id: Ember.attr()
});
Astcart.Application.adapter = Ember.FixtureAdapter.create();
Astcart.Application.FIXTURES = [
{
"id" : "1",
"logo_url": "img/logo.jpg",
"logged_in": {
"id" : "1",
"logged": true,
"username": "sac1245",
"account_id": "4214"
},
"name": "gau",
"list": [
{
"id" : "1",
"name": "amit"
},
{
"id" : "2",
"name": "amit1"
}
]
}
];
Template code :
{{#each item in model}}
{{item.name}}
{{item.logged_in.logged}}
{{/each}}
Router code :
Astcart.ApplicationRoute = Ember.Route.extend({
model: function() {
return Astcart.Application.find();
}
});
Can any one show me how to access data of above node in template?
Source: (StackOverflow)
I have this controller where to fetch data from the server I have to fire fetchPosts
method and to add new post fire add
App.PostsController = Ember.ArrayController.extend({
actions: {
fetchPosts: function (id) {
var data = App.Post.find({category: id});
this.set('model', data);
},
add: function () {
var post = this.get('newPost');
post.save().then(function () {
this.pushObject(post);
});
}
});
The problem is that the record are adding to the bottom of the list. I want it to work like native js unshift
but now it works like push
. Looking for something like unshiftObject
to make added object the first object in the array.
Source: (StackOverflow)
In my ember-model model I need to set a String attribute from an enumeration.
Is it possible with ember-model ?
By Example I would like to have a Book model:
App.Book({
id: Ember.attr(),
title: Ember.attr(),
author: Ember.attr(),
status: App.BookStatus ? -> How to define App.BookStatus with the 3 available values
});
and
App.BookStatus as an enum with 3 possible values "FREE", "BORROW", "LOST"
and use it:
var myBook = App.Book.create({id: 1, title: 'myBook', author: 'fred', status: App.BookStatus.FREE})
I need the equivalent to the Java Enum feature
public enum BookStatus {
FREE, BORROW, LOST
}
class Book {
BookStatus bookStatus;
}
Book book1=new Book();
book1.bookStatus=BookStatus.LOST
Source: (StackOverflow)
I have the url /tests/test-slug?extradata=data all my params are setup correctly within ember. When that extradata param is set the model updates with the new data from the (/tests/test-slug?extradata=data) response. Usually I would retrieve data using ember-model by doing:
model: function (params) {
return App.Test.findQuery(params);
}
But with the query parameter added to this nested url its giving me 'test-slug' as a param with the extradata and making a request to the server with: ?tests_slug=test-slug&extradata=data
Is there anyway I can use query params and update my model on a nested route?
Edit: this post explains it a lot better than me:
Ember data - dynamic segments and query params together?
Source: (StackOverflow)
Perhaps doing this with regular Ember application having all the code sitting in app.js would have been much easier for me. But since I'm using Ember CLI I'm having trouble accessing my model in my Route. I'm still trying to learn how to use Ember CLI so please help me out.
As I just want to fire AJAX calls and get the data to render on my UI, I downloaded and added Ember Model library to my project. I don't see a need of using Ember Data. This is the Ember Model documentation I'm referring: https://github.com/ebryn/ember-model#example-usage. With that said, here's my directory structure that Ember CLI proposed:
|-app
|-controllers
| |-customers.js
|-models
| |-customers.js
|-routes
| |-customers.js
|-templates
| |-customers.hbs
|-app.js
|-index.html
|-main.js
|-router.js
This is much simpler representation of the actual project structure that I have just to focus on the problem. As proposed in Ember Model documentation I added following code to my Customers model (model\customers.js):
export default Ember.Model.extend({
nameid: attr(),
firstname: attr(),
middlename: attr(),
lastname: attr(),
prefixname: attr(),
suffixname: attr()
});
this.url = "http://restapi/api/customers";
this.adapter = Ember.RESTAdapter.create();
Notice that I had to do the "export default" instead of "App.Customers = Ember.Model.extend...". This is the Ember CLI convention. So when I try to access the model I created in my Customers Route I get error "Error while loading route: ReferenceError: App is not defined"..
Customers Route code:
export default Ember.Route.extend({
model: function () {
App.Customers.find();
},
actions: {
addnew: function(){
//logic of saving edited customer
alert('customer created!');
}
}
});
I tried this.model() - Returns an object of type supperWrapper and this.modelFor() - Returns null.
Please suggest how to get an handle of my model in its route so that I can perform CRUD operations provided out-of-the-box by Ember Model.
Thanks!
Source: (StackOverflow)
I've been googling and scouring Stack Overflow for some sort of hint on this subject but the information is scattered at best.
I'm trying to Create a new Child Record (Comment
) and save it to an existing Parent Record (Post
). I am using Ember-Model, rather than Ember-Data, but any tips or pointers would be greatly appreciated.
At the moment, I've been successful creating a new, embedded Comment
but only when it is created with a new Post
record. So:
How do I go about loading/retrieving the currently loaded Post
(parent record) in order to apply Comments
(child records) to it?
I've been reading up on controller dependencies, using needs:
and this.controllerFor
and this.modelFor
in order to have access to another controller/model's content
but have been unable to wire these things together into something meaningful.
Anyway, here is what I've whittled my application code down to, in the hopes I might be able to stumble into the proper way of doing this...
Routes
App.Router.map(function() {
this.resource('post', { path: '/:post_id' }, function() {
this.resource('comments', { path: '/comments'} );
});
});
I removed all the other resources & routes, so I'm left with App.Post
, App.PostIndex
, and App.Comments
. I think my routes are the issue here, I assume I'm not properly implementing the methods to use the loaded Post
record in my Comments
route.
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Post.find();
},
setupController: function(controller, model) { // I'm not certain if this
controller.set('content', model); // setupController is needed?
}
});
App.PostRoute = Ember.Route.extend({
model: function(params) {
return App.Post.find(params.post_id);
},
setupcontroller: function( controller, model) { // again, unsure if this
this.controllerFor('post').get('comments'); // is correct.
controller.set('content', comments);
}
});
App.CommentsRoute = Ember.Route.extend({
afterModel: function() {
this.set('post', this.modelFor('post'));
},
setupcontroller: function( controller, model) {
this.controllerFor('post').get('comments');
controller.set('content', comments);
}
});
Controller
App.CommentsController = Ember.ArrayController.extend({
needs: "post",
actions: {
addComment: function() {
var post = App.Post.create({
title: 'static post title'
});
post.get('comments').create({
message: 'static message'
});
post.save();
}
}
});
This is my current Comments Controller, which can create a new Post
with an embedded Comment
. I've found and been given numerous examples in which to create the Comment
, but none seem to work for me. Basically, I'm struggling with defining the var post = ...
as the currently loaded record. I've implemented various approaches in an attempt at trial & error. Thus far I have attempted:
var post = App.Post.create();
, returns property undefined, as this would create a new record. However, I gave it a shot as every example i saw related to this defined their record as such.
var post = this.get('post');
, returns a cannot call 'get' on undefined. I've tried using this method of defining my current post on both the Comments
controller and Post
controller.
var post = this.get('controllers.post.content);
, returns a 'cyclic error' from the backend I'm using.
var post = App.Post.find();
, returns a cannot call 'get' on undefined.
var post = App.Post.find(1);
, Again, returns a cannot call 'get' on undefined. Figured I'd give it a shot because this is one of those recurring examples people provide. The backend I use applies its own ID to each record, and I'm unsure if I would be able to/how to have the .find()
method use a dynamic ID value and retrieve only the model I just loaded.
I'm guessing that I'm not properly setting up my Routes and Controller dependencies?
If anyone has a suggestion, relevant link, or fix I would be very grateful.
This one (seemingly simple) issue/use case has me at wit's end at this point.
Source: (StackOverflow)
Im trying to understand the proper way to sideload data using ember-model
I have json coming back like so ( i slimmed it down a bit from the actual json for sake of space here )
{
"classrooms" : [
{
"classroom_name" : "Class 1",
"id" : 1,
"teacher_id" : 3,
"grade" : 5,
"assignments" : [
],
"students" : [
{
"id" : 5,
"last_name" : "Ford",
"first_name" : "Henry",
"district_id_number" : "MD454"
}
]
},
{
"classroom_name" : "Class 3",
"id" : 2,
"teacher_id" : 3,
"grade" : 4,
"assignments" : [
{
"id" : 5,
"assignment_overview" : "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.\r\n\r\nNam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.",
"assignment_title" : "Fractions",
"story" : null
}
],
"students" : [
{
"id" : 5,
"first_name" : "Henry",
"last_name" : "Ford",
"district_id_number" : "MD454"
},
{
"id" : 3,
"first_name" : "Jake",
"last_name" : "Strong",
"district_id_number" : "WH6879"
},
{
"id" : 6,
"first_name" : "Bryan",
"last_name" : "Dobson",
"district_id_number" : "B453"
}
]
}
]
}
In my Classroom Model i have a computed property like so where i loop over the embedded student objects, load them into the sideloaded data, then use the find to pull them out.
classroomStudents: function () {
var studentObjects = [],
students = this.get('students');
Msmapp.Student.load(students);
students.forEach(function(student) {
studentObjects.pushObject(Msmapp.Student.find(student.id));
});
return studentObjects;
}.property('students')
Im thinking that this.get('students')
may not be what the Msmapp.Student.load(students);
expects. I assume that it expects data in a raw format and Im not 100% positive that this.get('students')
is that.
This is what this.get('students')
when i debug
[Object
resource_document_ids: Array[0]
resource_ids: Array[0]
resource_image_ids: Array[0]
resource_video_ids: Array[0]
__proto__: Object
district_id_number: "MD454"
first_name: "Henry"
id: 5
resource_document_ids: Array[0]
resource_ids: Array[0]
resource_image_ids: Array[0]
resource_video_ids: Array[0]
__proto__: Object
,Object
,Object
]
And when i debug the returned studentObjects
array i get classes but They dont appear to be correct
[Class
__ember1372909895769: undefined
__ember1372909895769_meta: Meta
_super: undefined
data: Object
isLoaded: true
isNew: false
__proto__: Object
id: 5
resource_document_ids: Array[0]
resource_ids: Array[0]
resource_image_ids: Array[0]
resource_video_ids: Array[0]
__proto__: Object
__defineGetter__: function __defineGetter__() { [native code] }
__defineSetter__: function __defineSetter__() { [native code] }
__lookupGetter__: function __lookupGetter__() { [native code] }
__lookupSetter__: function __lookupSetter__() { [native code] }
constructor: function Object() { [native code] }
hasOwnProperty: function hasOwnProperty() { [native code] }
isPrototypeOf: function isPrototypeOf() { [native code] }
propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
isLoaded: true
isNew: false
, Class
, Class
]
In my template i have something like this
<ul>
{{#if classroomStudents }}
{{#each student in classroomStudents }}
<li class="listed_item micro">
{{#linkTo "classroom_student" student }}
<div class='title'>{{ student.first_name }}</div>
{{/linkTo}}
</li>
{{/each}}
{{ else }}
<li class="item">
{{#linkTo "classroom.new_student" classNames='header_link tooltip'}}
No students assigned
{{/linkTo}}
</li>
{{/if}}
</ul>
Im not getting any of the values out because it appears that they are not being setup on the object but the linkto works correctly. I imagine its because the id is being set.
both {{ student.first_name }}
or {{ first_name }}
are undefined.
Source: (StackOverflow)