Emberjs route model with view - ember.js

My app has a page where I'm using the view to display the data from other template with my view like this :
<script type="text/x-handlebars" data-template-name="enquiry">
[...] // some other information display before
{{view App.EnquirySelectedVehicleView}}
</script>
<script type="text/x-handlebars" data-template-name="selectedVehicle">
// Here is my content
</script>
My map looks like this :
this.resource('enquiry', { path: '/enquiry/:enquiry_id'}, function() {
this.route('selectedVehicle');
});
After reading the doc I just did this in my view :
App.EnquirySelectedVehicleView = Ember.View.extend({
templateName: 'selectedVehicle'
});
So far so good, its showing the text from my template. But I need to return data from an ajax call in this template (selectedVehicle) automatically, like its fetching the data when you are on /enquiry/1/.
I've done this in my router :
App.EnquirySelectedVehicle = Ember.Object.extend({});
App.EnquirySelectedVehicleRoute = Ember.Route.extend({
model: function() {
console.log('DEBUG: SelectedVehicle Model');
App.SelectedVehicle.vehicleStock(this)
}
});
App.EnquirySelectedVehicle.reopenClass({
vehicleStock: function(that) {
console.log('DEBUG: Fetch vehicle stock');
// Here come the ajax call
}
});
But my issue is that route is never call.. How can I return some value from my selectedVehicleRoute when I'm on the /enquiry/1 page in a view template ? (not sure if I ask it correctly)
Thanks for the help !
[edit]
#Fanta : I think I begin to understand how I can do that :
App.EnquiryRoute = Ember.Route.extend({
beforeModel: function(transition) {
this.controllerFor('login').send('isSession', transition);
},
model: function(param) {
var promise = new Ember.RSVP.Promise(function(resolve, reject) {
var modelData = {enquiry: {}, vehicleStock: {}};
Ember.$
.get(host + '/enquiry/' + param['enquiry_id'], function(data) {
console.log('DEBUG: Enquriry GET OK id = ' + param['enquiry_id']);
modelData.enquiry = data.enquiry;
Ember.$.get(host + '/vehiclestock/' + data.enquiry.VehicleStockId, function(data) {
console.log('DEBUG: VehicleStock GET OK id = ' + data.enquiry.VehicleStockId)
console.log(data);
modelData.vehicleStock = data.vehicleStock;
resolve(modelData);
});
});
});
return promise;
}
});
It seems to work, now I have to figure it out how to display my Object :) but thank you for your help, that actually make me resolve it by a different way !

For future reference, just go to https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md and you'll see two links, one to JSFiddle and one to a JSBin with the basic setup.
Are you sure the route is not being called ? I created a Fiddle, http://jsfiddle.net/NQKvy/817/ if you check the JS console, you'll see in the log:
DEBUG: SelectedVehicle Model
DEBUG: Fetch vehicle stock

Related

integrate hammerJS with emberJS

I'm trying to integrate HammerJS v2.0.2 with EmberJS 1.6.1.
I used many code samples but non of them work, I get different errors. lets take the simplest one.
I implemented this view:
ListApp.ScrollerView = Ember.View.extend({
setupTap: function() {
var self = this;
this.hammer = new Hammer(this.get('element'));
console.log(this.get('element'));
var tap = new Hammer.Tap();
tap.set('enable', true);
this.hammer.add(tap);
this.hammer.on('tap', function() {
console.log('before tap!');
self.tap();
});
}.on('didInsertElement'),
tap: function() {
console.log('tap!');
}
});
but I get the following error after the page is loaded:
Uncaught TypeError: Object.keys called on non-object
any idea why I see this?
Here is working bin with hammer integrated to a view.
Here's the relevant code on how you integrate hammer into a view
App.Hammer = Em.View.extend({
templateName: 'hammer',
setupTap: function() {
Hammer(this.$()[0]).on("tap", this.tap.bind(this));
}.on('didInsertElement'),
tap: function() {
alert('My tamplate name is ' + this.get('templateName'));
}
});

Ember.js - Duplicate record in Store that clears after refresh

I have a basic Rest API and when I visit my newPost page, there is a form I can fill in with 'title' and 'text' fields as well as a submit button. After I create the record, I save it with the controller and transitionToRoute('posts').
When I view the 'posts' page, the input I just entered is displayed twice. I checked the Ember inspector and it looks like the record is put into the data store twice, once as I click the create button and one after the page refreshes. When I refresh the browser again, the duplicate is removed.
How do I get rid of the duplicate record in the store? Cheers for any suggestions.
EDIT: I believe I have solved my issue by using a filter to remove posts that hadn't been persisted yet.
Updated Routes:
App.PostsRoute = Ember.Route.extend({
model: function() {
return this.store.find('post');
},
setupController: function() {
var posts = this.store.filter('post', function (post) {
return !post.get('isDirty');
});
this.controllerFor('posts').set('model', posts);
}
});
App.NewPostRoute = Ember.Route.extend({
model: function(){
return this.store.createRecord('post');
}
});
Routes:
/* Routes */
App.Router.map(function() {
this.resource('posts');
this.resource('newPost');
});
App.PostsRoute = Ember.Route.extend({
model: function() {
return this.store.find('post');
},
setupController: function() {
var posts = this.store.filter('post', function (post) {
return !post.get('isDirty');
});
this.controllerFor('posts').set('model', posts);
}
});
App.NewPostRoute = Ember.Route.extend({
model: function(){
return this.store.createRecord('post');
}
});
NewPostController:
actions:
createPost: function() {
...
var post = this.get('store').createRecord('post', {
title: title,
text: text
});
this.set('title', '');
this.set('text', '');
post.save();
this.transitionToRoute('posts');
...
newRecord: function() {
this.set('content', App.Post);
}
Thanks!

emberjs: transitionToRoute Error no method 'addArrayObserver

From the 'job' route I am trying to transition to 'careers' route using following code.
<script type="text/x-handlebars" data-template-name="job">
<button {{action 'backToCareers' this}}>Back</button>
</script>
The controller with following gives 'Uncaught TypeError: Object # has no method 'addArrayObserver' ' error.
CareerApp.JobController = Ember.ObjectController.extend({
backToCareers: function(){
this.transitionToRoute('careers');
}
});
If I change the code(see below) to provide model object the error changes to 'Uncaught More context objects were passed than there are dynamic segments for the route: careers '
CareerApp.JobController = Ember.ObjectController.extend({
backToCareers: function(){
var jobs = CareerApp.Job.findAll();
this.transitionToRoute('careers', jobs);
}
});
Following is the code of my Model and the router
CareerApp.Job = Ember.Model.extend({
refNo: '',
title: ''
});
CareerApp.Job.reopenClass({
findAll: function(){
return $.getJSON("http://site/jobs").then(
function(response){
var jobs = Ember.A();
response.forEach(function(child){
jobs.pushObject(CareerApp.Job.create(child));
});
return jobs;
}
);
}
});
Router code
CareerApp.Router.map(function(){
this.resource('careers', {path: '/'});
this.resource('job', {path: '/jobs/:job_id'});
});
CareerApp.CareersRoute = Ember.Route.extend({
model:function(){
return CareerApp.Job.findAll();
}
});
CareerApp.CareersController = Ember.ArrayController.extend({
gradJobCount: function () {
return this.filterProperty('isExp', false).get('length');
}.property('#each.isExp')
});
The model hook is expected to return an array but you return a jQuery promise object. findAll should return an empty array which is filled when the callback is executed.
findAll: function() {
var jobs = [];
$.getJSON("http://site/jobs").then(function(response){
response.forEach(function(child){
jobs.pushObject(CareerApp.Job.create(child));
});
});
return jobs;
}
As you pass jobs to CarreersController, this one needs to be an ArrayController, maybe you have to define it manually

Emberjs serialize doesn't call model on {{linkTo}}

I have a route with the following format #/books/book/:bookId
When i am on the #/books and i click into the {{linkTo}}, then my model is not being
executed and the following error is being returned.
Error while loading route: TypeError {}
Uncaught TypeError: Object 4 has no method 'addArrayObserver'
I know that a model is only being executed when you refresh the page with your browser,
so i used the serialize, which according to the docs it should allow my model to be executed
when i click into the {{linkTo}, but it doesn't. It returns the above error.
utils.get is an Ajax call which returns a json back...
Could you tell me what i am doing wrong?
Thank you.
App.Router.map(function() {
this.resource("books", function() {
this.resource("book", {path: "/book/:bookId"});
});
});
var BookModel = Ember.Object.extend({});
BookModel.reopenClass({
find: function(bookId) {
var assets = Ember.A();
utils.get('book/' + bookId, function(response) {
response.assets.forEach(function(c) {
assets.pushObject(BookModel.create(c));
})
});
return assets;
}
});
var BooksModel = Ember.Object.extend({});
BooksModel.reopenClass({
findAll: function() {
var books = Ember.A();
utils.get('books', function(response) {
response.books.forEach(function(c) {
books.pushObject(BooksModel.create(c));
})
});
return books;
}
});
var BookRoute = Ember.Route.extend({
model: function(params) {
return BookModel.find(params.bookId);
}
,serialize: function(model, params) {
return { bookId: model };
}
});
<h2>books</h2>
<ul class="nav nav-tabs nav-stacked">
{{#each item in model}}
<li>
{{#linkTo "book" item.id}}{{item.name}}{{/linkTo}}
</li>
{{/each}}
</ul>
{{outlet}}
Basically every object (like your BookRoute) needs to be under your App namespace for ember to be found:
App.BookRoute = Ember.Route.extend({
...
});
Also you should pass the model object to the linkTo helper:
{{#linkTo "book" item}}{{item.name}}{{/linkTo}}
and then in your serialize hook you then do:
serialize: function(model) {
return { bookId: model.id };
}
Hope it helps.

Load model like a refresh without ember-data

I'm writing a little ember app without using Ember-Data (using TheMovieDB API) and I don't understand why model is not load when I click on a {{#linkTo}} link, but when I refresh the page manually datas are loaded correctly.
Here is my App.js :
window.App = Ember.Application.create();
App.Router.map(function() {
this.route('about');
this.resource('movie', {
path: '/movie/:movie_id'
})
});
App.IndexRoute = Ember.Route.extend({
setupController: function (controller) {
var movies = [];
$.ajax({
url: "http://api.themoviedb.org/3/movie/popular?api_key=5b088f4b0e39fa8bc5c9d015d9706547",
type: "GET",
async: false,
success: function (data) {
var length = data.results.length;
data.results.forEach(function (item) {
if (item.backdrop_path != null) {
var tmp = item.backdrop_path;
item.backdrop_path = "http://cf2.imgobject.com/t/p/w500/"+tmp+"?api_key=5b088f4b0e39fa8bc5c9d015d9706547"
movies.push(item);
}
})
}
});
controller.set('content', movies);
}
});
App.MovieRoute = Ember.Route.extend({
model: function (param) {
var infos;
/* Important !! */
var promise = Ember.Deferred.create();
$.ajax({
url: "http://api.themoviedb.org/3/movie/"+param.movie_id+"?api_key=5b088f4b0e39fa8bc5c9d015d9706547",
type: "GET",
success: function (data) {
var tmp = data.backdrop_path;
data.backdrop_path = "http://cf2.imgobject.com/t/p/w500/"+tmp+"?api_key=5b088f4b0e39fa8bc5c9d015d9706547";
// infos = Ember.Object.create(data)
promise.resolve(data);
}
});
console.log("MODEL");
return promise;
},
setupController: function (controller, model) {
controller.set('content', model);
}
});
App.Movie = Ember.Object.extend({})
Thanks for your help !
Since you have not specified which model you mean, I'm assuming you mean the movie model, and with my assumption I'm trying to answer.
I think your problem is that your template expects the model coming from a MovieIndexController because you specified a resource in your router map instead of a simple route.
That said, the solution might be to rename your controller to MovieIndexController and respectively the route MovieIndexRoute.
Here the reference my answer is based on, under the paragraph Resources.
Hope it helps