mercredi 31 décembre 2014

JSON Data using ember.js

The following is an API resonpse (sample url http://ift.tt/1wxAZMH)



{
"results":[
{
"id":"4422",
"updated":"Mon Jun 26 15:01:05 GMT 2006",
"description":"Meet fellow Social Networkers near you! Come to a local Social Networking Meetup to make valuable social connections and cultivate relationships with other elbow-rubbers in your area.",
"name":"Social Networking",
"link":"http:\/\/socialnetwork.meetup.com\/",
"urlkey":"socialnetwork",
"members":"245701"
}
],
"meta":{
"id":"",
"title":"Meetup Topics",
"count":1,
"updated":"",
"description":"API for accessing meetup topics",
"next":"",
"link":"http:\/\/api.meetup.com\/topics\/",
"method":"Topics",
"total_count":3063,
"url":"http:\/\/api.meetup.com\/topics\/\/?order=members&key=1&page=1&format=json&desc=0&offset=0",
"prev":""
}
}


Using plain javascript, I can do



var req = new XMLHttpRequest();
req.open('GET', 'http://ift.tt/1wxAZMH', false);
req.send();
json = req.responseText;
object = JSON.parse(json)['results'];
console.log(object.id);
console.log(object.link);


How do I get that using ember.js and ember-data , able to access properties ?





Multiple relationship between two objects

How do I define multiple relationships between two objects in Ember? For example A user can be either a staff or a customer the differentiator is the userType property. If a customer buys a product, the product object need to have link to the customer that bought it and the staff that facilitated the sale.





How to refresh the component?

I found several questions covering this topic, but I can't make them work.


I have the following controller. The 'latestDaily' selects the latest record of the model. The 'latestDaily' property also feeds the record to a component:



App.ActionsController = Ember.ArrayController.extend({

latestDaily: function() {
var dates = this.get('model').filterBy('actionType', 'daily').mapBy('date');
var maxDate = new Date(Math.max.apply(null,dates));
var sMaxDate = String(maxDate);
var latestAction = this.get('model').filter(function(item){
if(String(item.get('date')) == String(maxDate)) {
return true;
}
});
return latestAction[0];
}.property('model.@each'),

});


With the template:



<script type="text/x-handlebars" id="actions">

<div class='container-fluid'>
<div class="row">

<div class="col-md-6 col-lg-4"> <!-- Latest Daily -->
<div style="height: 35px">
<H2 class="text-big-light" style="color:#62D3F1">Daily BP</H2>
</div>
{{update-action action=latestDaily}}
</div>
</div>
</div>
</script>


The 'Update-Action' component may create a new action record and save it to the Ember-Data Store. When a new record is created, it should have the maximum Date of all the records and thus it should be selected by the 'latestDaily' property of the controller. Since the 'latestDaily' property listen to 'model.@each', I expect it would rerun but it does't seems to fire and the component is not updated.


How can the component be updated (re-polulated) with the new Action record just created?


The component code:



App.UpdateActionComponent = Ember.Component.extend({

/* Public API */
action: null,

/* Internal */
_user: function() {
return user = this.store.find('user', this.get('session.userID')).then(function(user) {
return user;
}, function(error) {
alert('Could not find user: ' + error );
});
}.property(),

actions: {
createAction: function() {
var _this = this;
var currAction = this.store.createRecord('action', {
date: new Date(),
conditionType: '',
period: '',
comment: '',
});

var user = this.store.find('user', this.get('session.userID')).then(function(user)
{
user.get('actions').pushObject(currAction);
currAction.save().then(user.save());
console.log('action ' + currAction.id + ' created and user updated');
}, function(error) {
alert('Could not find user: ' + error );
});

},

saveAction: function() {
var action = this.get('action');
action.set('date', moment(this.get('action.date')).toDate())
.set('comment', this.get('redactorValue'))
.save();
},
},
});


In my Application, the Ember-Data Store has been injected to all components. I imagine I should rather create the new records at the Route level by letting the action bubble up from the component with '.sendAction()' so that the component is more decoupled from the rest of the code? However, I understand that the controllers may deprecated with Ember 2.0 ( http://ift.tt/1oaN6hS ). So I'm not sure if the components will gain greater access to the Store by default? Maybe creating the records at the route level would simplify re-rendeing of the view? Or should I create the record at the controller level?


Thanks





Ember sidebar - returning from "admin" sidebar to "normal"

My application route defines my sidebar as follows (routes/application.js):



renderTemplate: function() {

this.render();

// sidebar
this.render("partials/sidebar", {
outlet: "sidebar",
into: "application" // important when using at root level
});
}


When the user enters the admin area of the app, there is a special admin sidebar which is applied as follows (routes/settings.js):



renderTemplate: function() {

this.render();

// sidebar
this.render("partials/sidebaradmin", {
outlet: "sidebar",
into: "application" // important when using at root level
});
}


This works as you would expect. However, when leaving the settings area, the sidebar becomes blank.


What is the correct way to ensure that regardless of where the user transitions to, that the standard sidebar redraws?





How do I create custom events in Ember.js, or organize asynchronous behavior?

In my controller I update some visual indexes when rows are added/removed from my two tables. For logging purposes, I need to post to the server what those changes are. Those changes happen after the data changes thanks to an observer, but I want to then notify the server of the changes after that. See below for my 'afterIndexesAreUpdated' pseudo event. If I change that to the same observer that resetIndexes listens to, it will be called before the data is actually updated. I need it to trigger after resetIndexes finishes, but I can't figure out how to do that. What do I need to do? I can't find any examples of dealing with events other than 'afterRender'.



resetIndexes: function() {
var index = 1;
this.get('listA').forEach(function(story) {
story.set('index', index);
index += 1;
});
this.get('listB').forEach(function(story) {
story.set('index', index);
index += 1;
});

// TODO: trigger event: afterIndexesAreUpdated
},

indexesObserver: function() {
Ember.run.once(this, this.resetIndexes);
}.observes("listA.@each", "listB.@each").on('afterRender'),

addToListB: function(story) {
var attrs = $.extend({}, story._attributes, story.get('_data'));
var oldIndex = story.get('index');

this.store.createRecord('story-b', attrs);
story.deleteRecord();

Ember.run.scheduleOnce('afterIndexesAreUpdated', function() {
var newIndex = story.get('index');
$.post("/move", { story_id: story.get('id'), position: newIndex, old_position: oldIndex }, function(data) {

}).fail(function() {
var storyName = story.get('title');
alert( "Something went wrong moving " + storyName );
});
});

},




Ember-Data destroyRecord stays in local store

I am on ember 1.8.1 and ember-data beta 12


If I do a createRecord and the user chooses not to save it, on the route deactivation I am trying to do model.destroyRecord() however, it continues to be available in my local store with a currentState.stateName: root.deleted.saved


I can't seem to remove it from my local store and I don't know why. Why does the record have a stateName of root.deleted.saved and still available when I do a store.find?





Ember Array binding not updating

I have an array in which I'm adding elements. Then, in the template, all the elements are being displayed. The issue is that only the first time an element is added to array, only then the template is being added, afterwards, whenever an element is added to the template, the template is not updating though the element is properly being inserted into the array.


How to make the template update every time the content of the array changes?


A worked example on JSBin: http://jsbin.com/pamequ





Ember Restore State when Routing

I have a application controller with a input bound to searchTerms and on click I am routing to search-results route. The code is from a book



Rocknrollcall.Router.map(function() {
// Add your routes here
this.route('search-results', {
path: 'search/:term'
});

});


});


Rocknrollcall.ApplicationController = Em.ObjectController.extend({ searchTerms: '', actions: { submit: function() { this.transitionToRoute('search-results',this.get('searchTerms')); } } });


In the route I am returning some data I am rendering in search results



Rocknrollcall.SearchResultsRoute = Ember.Route.extend({
model: function (query) {
// ajax call
return {artists: artists, songs: songs}
});

}


});


Everything works fine. If I go from index and enter say tom I go to this URL "http://localhost:9000/#/search/tom" with all data.


However the point is when I put the URL directly in browser I do get the data. But the search term input box in the application template is empty. I would like to populate that also somehow. My question is what is the best solution to do so in Ember properly?





How do I get attributes of Custom Session using Ember Simple Auth

PROBLEM: I don't know how to get the current session in a controller.


I have a custom authenticator, custom session, and initializer defined like so:


CUSTOM AUTHENTICATOR



var CustomAuthenticator = Base.extend({
authenticate: function(credentials) {
return new Ember.RSVP.Promise(function (resolve, reject){
var loginPromise = Ember.$.post('/api/login', {'email':credentials.identification, 'password':credentials.password} );
loginPromise.then(function (data){
resolve({
token: data.user.api_key,
userData: data.user
});
}, function(error){
reject(error);
});
});
}
});


CUSTOM SESSION



import Ember from 'ember';
import Session from 'simple-auth/session';

var CustomSession = Session.extend({
after:'simple-auth',
currentUser: function(){
return this.container.lookup('ember_simple_auth:session');
}.property('currentUser')
});

export default CustomSession;


INITIALIZER



import CustomAuthenticator from '../authenticators/custom';
import CustomSession from '../sessions/custom';

export default {
name: 'authentication',
before: 'simple-auth',
initialize: function(container) {
container.register('authenticator:custom', CustomAuthenticator);
container.register('session:custom', CustomSession);
}
};


I'm trying to get the token and userData in one of my controllers by using this.get('session') but it's giving me the following:



Class {store: Class, __ember1420041799205: "ember297", __nextSuper: undefined, __ember_meta__: Object, constructor: function…}


and I see the ember_simple_auth:session key and values in the local browser storage {"authenticator":"authenticator:custom","token":"123456789","userData":{"id":"1","email":"something@email.com","api_key":"123456789","expiry_time":"2014-12-31 14:02:56"}}


I basically need to get what's in the local storage. How do I do this?





Ember component cannot use access controller property via "needs"

I'm trying to change a controller's property from a component as follows(JSBIN example http://jsbin.com/gevuhu):



App.CategoryManagerController = Ember.Controller.extend({
selectedCategory: null,
});

App.BlogPostComponent = Ember.Component.extend({
needs: ['categoryManager'],
selectedCategory: Ember.computed.alias('controllers.categoryManager.selectedCategory'),
actions:{
selectedCategory: function (){
this.set('selectedCategory',1);
}
}
});


but getting the error Property set failed: object in path "controllers.categoryManager" could not be found or was destroyed.


Is it that we cannot use "needs" in components ?





Nested routes and array

In my app I have the following setup:


Router



this.resource('types');
this.resource('type', {path: 'types/:type_id'})


When a user navigates to types he gets a list with all the different types. When he clicks on a link he navigates to the specific type:page. Here I would like to show an array of products. Each type has an array of products. I tried to get the products doing so:



this.resource('types');
this.resource('type', {path: 'types/:type_id'}, function(){
this.resource('beers', {path: '/products'});
});


Router



model: function(){
return this.store.find('product');
}


but that didn't work. I also tried with the params but that doesn't work.


Templates


Type-template



<h3>{{name}}</h3>
<hr>
{{outlet}}


Product-template



{{#each}}
{{name}}
{{/each}}


But nothing gets loaded in the template. I don't know if this is the way to go. I had some success with removing the nested route and simply loading the two models in the afterModel hook on the typeController, but that doesn't give me access to some other models, linked to the product.


It's very frustrating that some "easy" things, like loading an array of products that belong to a type, is such a hassle.





Use ember and ember data on nodejs

I need to use my ember data models on the server to perform some CRUD operations. How do I use ember and ember data in a nodejs file?





Ember validate required input

I have a required input which is connected to a model.


Now i want to show an error message if the required field is empty. But only if the input has been changed or the form gets submitted. So initially there should be no error even if the input is empty.


My current solution is a property named "hasChanged" which gets set by an observer on init. http://emberjs.jsbin.com/tovawezide/2/edit?html,js,output


Is there a shorter solution with less boilerplate in ember? like an build in "hasChanged"? I think my way gets confusing with more inputs.


Note: im not talking about ember-data or its isDirty property nor do i ask for validation libraries.





How to insert and interact with html coming from db in ember.js

I'm tring to build a UI to customize the design of an email template.


The flow is: user chooses from a list of predefined templates, load the template style+html in the page, interact with the content with inline editor triggered by click and handled by ember.js


The problem is to interact with DOM inserted at runtime. so without all the goodness of handlebars helpers and so on. The email DOM is basically a piece of remote data, coming from a db and loaded in ember via ember-data


How do you go about it? Thanks





How to show node,js rest api data to client using ember.js

How to show node.js rest api response to client side template using ember.js and handlebars,But one condition is don't use ember data store adapters etc...


If possible please give one code example..I already saw some examples but in that they are using DS.fixture etc..Its not matching with my requirement...Waiting for quick reply


Thanks





mardi 30 décembre 2014

How do I split apart the REST calls from my IndexRoute?

I'm working on a webapp to teach myself Ember, and I've walked into one large issue:


The page halts while it is attempting to fetch json.



App.IndexRoute = Ember.Route.extend({
model: function() {

var store = this.store;
return Ember.RSVP.hash({
pokeballs: App.Pokeball.all(),
pokemon: store.find('pokemon'),
status: App.Status.all(),
levels: App.Levels
});
}
});


this.store.find('pokemon') uses the RESTAdapater, and can freeze the page from rendering anything (besides the loader) for up to 1.5 seconds.


My understanding... is the model that gets returned from the IndexRoute gets passed directly to the IndexController. I know that Ember.RSVP.hash does magic promise-like stuff to delay passing the model to the controller until everything is loaded (which is likely the core of my issue)


So my question: what is the best way to architect my IndexRoute and IndexController relationship so that the user doesn't have the page halted while the pokemon data is loaded.


Webapp Demo: http://theirondeveloper.github.io/pokemon-catch-rate


Github: https://github.com/TheIronDeveloper/pokemon-catch-rate





Accessing parent route slug from route

I have a route /settings/:setting_id/overview. In my settings.js route I can see the value of setting_id in the model function, i.e.



export default Ember.Route.extend({
model: function(params) {
alert(params.setting_id);
}
});


However, in my settings/overview.js route I get undefined for setting_id for the exact same code as above.


My router.js is defined as follows:



Router.map(function() {
//...
this.resource('settings', { path: 'settings/:settings_id' }, function() {
this.route('overview');
// ...
});
});




Ember Charts 0px width and height chart when used with Bootstrap

I am experiencing an issue where my ember-charts are being rendered by default with a 0px width and height SVG. If I change the size of the SVG manually, then it reveals a small chart (105px by 104px, chart-viewport class) which I cannot override at all.


I have tried all the chart types and the effect is the same. The main things I have at play here are ember-cli-bootstrap-sass 0.2.8, Liquid Fire 0.14, Ember 1.7.0, Ember CLI 0.1.2. I've ran into issues with Bootstrap and Liquid Fire heights before (like this) with inheriting height, so the source of the problem may not be very clear. Code extract below:


/controllers/dashboard.js



import Ember from 'ember';

export default Ember.Controller.extend({
needs: ['application', 'nav'],
chartContent: [
{
"label": "Equity",
"value": 12935781.176999997
},
{
"label": "Real Assets",
"value": 10475849.276172025
},
{
"label": "Fixed Income",
"value": 8231078.16438347
},
{
"label": "Cash & Cash Equivalent",
"value": 5403418.115000006
},
{
"label": "Hedge Fund",
"value": 1621341.246006786
},
{
"label": "Private Equity",
"value": 1574677.59
}
]
});


/styles/app.scss



.dashboard-container {
margin-top: 1em;
.chart {
height: 295px;
margin-top: 1em;
.graphic {
width: 100%;
height: 250px;
}
}
}


/templates/dashboard.hbs



<div class="container-fluid dashboard-container">
<div class="row">
<div class="col-sm-6 chart">
<p class="strong">MTD Sales Revenue</p>
<div class="graphic">
{{vertical-bar-chart data=chartContent}}
</div><!--.graphic-->
</div><!--.chart-->
</div>
</div>


Any thoughts?





Handling Validation Errors in Ember.js

I have a rails app serving json to an ember frontend.


I am trying to display validation errors from on a form on the client.


Rails is returning this json:



{"errors":{"hometown":["is too long (maximum is 64 characters)"]}}


In my handlebars template for the current route I am attempting to iterate through the errors but I don't get any output for the errors section:



<div class="form-group">
<label>Hometown</label>
{{#each errors.hometown}}
{{this}}
{{/each}}
{{input type="text" class="form-control" valueBinding="effectiveUser.hometown" disabled=entryNotAllowed size="50"}}
</div>


I also updated my RESTadapter based on this blog: https://marcqualie.com/2014/04/model-errors-in-emberjs to include:



ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"];
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}


I still really dont understand the context of what this errors object is and why my view has access to it that I but several different sources seem to say this setup should work. Any insight would be appreciated.





run a function when an Ember.Object is created

I need to run a function when a particular object is created to validate the environment is setup correctly.


This works on an Ember.Controller but not on an Ember.Object.



checkEnvironment : function() {

...

}.on('init'),


Is there a way to hook into the contructor somehow?





Ember-Cli-Simple-Auth Authorizer

I followed the tutorial at here on the basics of setting up an OAuth with Google. I've also implemented the extra bit at the end, that allows for gathering extra data from Google (name, email, profile pic, etc.)


To an extent, it works: the google login comes up, logs in, grabs the info. However, if the user reloads the page, it stays "logged in" but all the profile data disappears. It's my understanding that this shouldn't happen.


From what I've already looked at on SO, Google and the like, it seems like I need to implement an authorizer and/or authenticator to regrab this data. To be honest, I'm just not getting it. It seems like the authorizer I've implemented gets called on the initial pass, before my app has the data from Google, and doesn't get called subsequently.


Has anyone overcome this using this tutorial or sees what needs to be done to correct this?


Many thanks!





Ember.JS - Cannot filterBy or filter on computed properties

I'm trying to filter the result of my hasMany-Array async-get with filterBy and condition "isRoot" == true. The "isRoot" property is a computed property and it seems that the filterBy function of ember doesn't wait for the promise to resolve. Here my code:


Model for Directory



App.Directory = DS.Model.extend(App.ModelEventHandler, {
name: DS.attr('string', {defaultValue: ''}),
users: DS.hasMany('user', {async: true}),
isRootOfShare: DS.attr('boolean', {defaultValue: false}),
directories: DS.hasMany('directory', {async: true, inverse: 'directory'}),
directory: DS.belongsTo('directory', {async: true, inverse: 'directories'}),
shares: DS.hasMany('share', {async: true}),
files: DS.hasMany('file', {async: true}),
isRoot: function () {
var directoryPromise = this.get('directory');
return directoryPromise.then(function (directory) {
var isRoot = directory === null;
return isRoot;
}.bind(this));
}.property('directory')}


Model for User



App.User = DS.Model.extend(App.ModelEventHandler, {
// Attributes begin
email: DS.attr('string'),
isCurrentUser: DS.attr('boolean', {defaultValue: false}),
// Relationships
directories: DS.hasMany('directory', {async: true}),
shares: DS.hasMany('share', {async: true}) }


The statement I'm using to filter the directories:



user.get('directories').then(function (directories) {
//TODO: Fix isRoot
var filteredDirectories = directories.filterBy('isRoot', true);
return filteredDirectories;
});


Someone here with knows a solution for my problem? Thx in advance!





Calling code after {{#each}} has rendered in ember.js?

I am trying to call some code after an Ember {{#each}} tag has finished looping through its items. I have seen other questions that looked similar and the answer always implemented didInsertElement on the view. This does not seem to work for me as I am trying to access html objects that are not rendered with the view because they are in the {{#each}}.


Here is what my html looks like.



<script type="text/x-handlebars" id="user">
{{#if isEditing}}
<div class="well">
{{partial 'user/edit'}}
<button {{action 'doneEditing'}} class="btn btn-default">Save</button>
<button {{action 'cancelEditing'}} class="btn btn-default">Cancel</button>
</div>
{{else}}
<button {{action 'edit'}} class="btn btn-default">Edit</button>
{{/if}}
</script>

<script type="text/x-handlebars" id="user/edit">
{{#view 'editor'}}
<div id="sList" class="btn-group-vertical" role="group">
{{#each s in model}}
<button class="btn btn-default">
{{s.theme}}
</button>
{{/each}}
</div>
{{/view}}
</script>


And my javascript



App.UserRoute = Ember.Route.extend({
model: function(params) {
return this.store.all('strength')
}
});

App.UserController = Ember.ObjectController.extend({
isEditing: false,
actions: {
edit: function(){
this.set("isEditing", true);
},
doneEditing: function(){
this.set("isEditing", false);
},
cancelEditing: function(){
this.set("isEditing", false);
}
}
});

App.EditorView = Ember.View.extend({
didInsertElement: function() {
//Do something to the button elements
}
});


When I try to run this, as soon as I hit the edit button the partial loads and I get an error in the console after didInsertElement tried to access the button elements. It as if the elements in the div have not rendered yet. So how can I tell if the {{#each}} is done inserting elements into the html? I know this may be confusing but any and all help is appreciated.





EmberJs: Component action not triggered in pagination example

I followed this pagination tutorial but can't get the "next-page" / "prev page" to work. http://webcloud.info/blog/2014/11/01/building-a-real-world-pagination-with-ember-js-the-right-way/


JSBIN - http://emberjs.jsbin.com/manetavule/2/


The alert never runs in the click event, any idea what I'm doing wrong?



Myapp.PaginatonBaseComponent = Ember.Component.extend({
tagName: 'button',
classNames: 'btn btn-default'.w(),
attributeBindings: ['disabled'],
enabled: true,
disabled: Ember.computed.not('enabled'),
action: null,
click: function(){
alert('not triggered!');
this.sendAction();
}
});




Multiple serializers for a single model

I have a User model that hasMany Reminders.


When a User is first created, I want the reminders to be embedded. When it is updated, I don't want its reminders to be embedded. How can I do this?


My strategy was to create a custom new-user-serializer that had DS.EmbeddedRecordsMixin and



reminders: { embedded: 'always' }


and use that in my UserAdapters createRecord method, but I couldn't get it working.





ember.js - swap out a nested resource from any route

I have routes with nested dynamic segments, for example /:locale/products/:product_id/items/:item_id etc nesting. I want to swap out the locale in an action in the locale route. I don't want to transition to the base /:locale route when I change the locale.


locale route action:



actions: {
localeChanged: function(locale) {
var route = this.controllerFor('application').get('currentRouteName');
this.transitionTo(route, locale);
}
}


This only works when I'm not deeply nested. I would like to avoid implementing the localeChanged action in every route to provide the exact models needed for a given route.





each vs each foo in model, differences and issue with link-to undefined

I'm trying to do a list of product items and make them so when you click the image or title it will show a single page/template with the more info, etc.


But, when ever I use {{#each product in model}} the link-to just returns an undefined.


Heres what I have



App.Router.map(function(){
this.route('about', { path: '/aboutus' } );
this.resource('products');
this.resource('product', { path: '/products/:title' } );
this.resource('contacts');
});

App.ProductsRoute = Ember.Route.extend ({
model: function(){
return App.PRODUCTS;
}
});

// Logging out Params from the Route
App.ProductRoute = Ember.Route.extend ({
model: function(params){
return App.PRODUCTS.findBy('title', params.title);
}
});

App.PRODUCTS = [
{
title: 'Flint',
price: 99,
description: 'Flint is a hard, sedimentary cryptocrystalline form of the mineral quartz, categorized as a variety of chert.',
isOnSale: true,
image: 'images/flint.png'
},
{
title: 'Kindling',
price: 249,
description: 'Easily combustible small sticks or twigs used for starting a fire.',
isOnSale: false,
image: 'images/kindling.png'
}
];


when I use this method {{#each product in model}} i get undefined



<script type='text/x-handlebars' data-template-name='products'>
<h1>Products</h1>
<ul class="list-unstyled col-md-8">
{{#each product in model}}
<li class='row m-b'>
{{#link-to 'product' this }}<img {{bind-attr src='product.image'}} class='img-thumbnail col-md-5' alt='product-image' />{{/link-to}}
<div class="col-md-7">
<h2>{{product.title}}</h2>
<p class="product-description">{{product.description}}</p>
<p><button class="btn btn-success">Buy for ${{product.price}}</button></p>
</div>
</li>
{{/each}}
</ul>
</script>
<script type='text/x-handlebars' data-template-name='product'>
<div class="row">
<div class="col-md-7">
<h2>{{title}}</h2>
<p>{{description}}</p>
<p>Buy for ${{price}}</p>
</div>
<div class="col-md-5">
<img {{bind-attr src='image'}} class='img-thumbnail img-rounded' />
</div>
</div>
</script>


but when I use just {{#each}} it returns normally BUT it warns me this: DEPRECATION: Using the context switching form of {{each}} is deprecated. Please use the keyword form ({{#each foo in bar}}) instead.



<script type='text/x-handlebars' data-template-name='products'>
<h1>Products</h1>
<ul class="list-unstyled col-md-8">
{{#each}}
<li class='row m-b'>
{{#link-to 'product' this }}<img {{bind-attr src='image'}} class='img-thumbnail col-md-5' alt='product-image' />{{/link-to}}
<div class="col-md-7">
<h2>{{title}}</h2>
<p class="product-description">{{description}}</p>
<p><button class="btn btn-success">Buy for ${{price}}</button></p>
</div>
</li>
{{/each}}
</ul>
</script>


which one should I use and how do I fix the undefined error? I'm guessing it has to do with the App.ProductRoute but can't figure it out, still new to ember :l





In a RESTful system, how to make request to a unique server api that doesn't have an id

Now my system has some api that doesn't have an unique id, so how to make request from ember data.


Because find method needs an id, but i don't have it.


Current, my solution is use pure AJAX call to fetch this kind of data.


So is there have any better solution to make this happen.





Route with ID in ember-cli

I'm trying to generate a settings page for my Ember-Cli app. The URL I would like is /settings/:id/ with separate routes such as /settings/:id/overview and /settings/:id/password.


How do I create nested routes using Ember CLI? I've found plenty of examples for Ember, but not for CLI.





lundi 29 décembre 2014

Attempted to handle event `becameInvalid` while in state 'root.loaded.saved'

I've implemented DS.Errors for my RestAdapter, thanks to Alex Spellers tutorial on server side validation.


However, in this part of my app I want to do a simple client side check to see if the form is complete. (Why not have DS.Errors handle all the errors?)



process: function(upload) {
var form = upload.get('form');

if (!isComplete(form)) {
upload.get('errors').add('field', 'field isempty');
return;
}
// else "Processing..."


The logic here is somewhat simplified, but errors.add() should invalidate, and add an error to the model. However I'm getting the following error:



Uncaught Error: Attempted to handle event `becameInvalid` on <@model:upload:54a1f298ef912a2ace760b0f> while in state root.loaded.saved.


I have read about the state manager, but am unsure as to how, and what state I should transition to before adding an error to my model.


Thanks in advance!



Ember : 1.8.1
Ember Data : 1.0.0-beta.11
Handlebars : 1.3.0
jQuery : 1.11.2




How can i rollback a belongsTo model


DEBUG: ------------------------------- ember-1.9.1.js:3935
DEBUG: Ember : 1.9.1 ember-1.9.1.js:3935
DEBUG: Ember Data : <%= versionStamp %> ember-1.9.1.js:3935
DEBUG: Handlebars : 2.0.0 ember-1.9.1.js:3935
DEBUG: jQuery : 1.11.1 ember-1.9.1.js:3935
DEBUG: -------------------------------


i have to model just like this:



Hwv.Car = DS.Model.extend({
number: DS.attr('string'),
owner: DS.belongsTo('user')
});
Hwv.User = DS.Model.extend({
name: DS.attr('string'),
phone: DS.attr('string'),
email: DS.attr('string')
});


then i use a select input in the template:



{{#if isEditing}}
{{view "select" id = "owner" class="form-control"
content=owners
optionLabelPath="content.name"
optionValuePath="content.id"
prompt="--please select a user--"
selection=selectedOwner
}}
<span class="glyphicon form-control-feedback"></span>
{{else}}
<p class="form-control-static">{{owner.name}}</p>
{{/if}}


and my controller is like this:



Hwv.CarController = Ember.ObjectController.extend({
needs:["application","session"],
isEditing:false,
isNew:false,
owners:function(){
var model = this.get('model'),
store = this.store;
return store.filter('user', function (user) {
return true;
});
}.property(),
selectedOwner:function(k,v){
var model = this.get('model');
if(!model){
return;
}
if (v === undefined) {
return model.get("owner");
} else {
debugger;
model.set('owner', v);
debugger;
return v;
}
}.property("model.owner"),
selectedOwnerDidChange: function() {
debugger;
//if i remove this row ,the car model can't be dirty when the owner of the car is changed by the select input.
this.get('model').send('becomeDirty');
}.observes('selectedOwner'),
actions:{
cancel:function(){
//this row will work when i change the car number only and then click the cancel button
//but when i change the car owner by the select input,the car model can't rollback successfully.
this.get("model").rollback();
}
}
});


The problem seem to point out the ember data can't rollback a belongsTo model successfully, and even it can't mark the dirty property of the model exactly when a belongsTo property has changed.


My ask: How can i code to fix the rollback issue with the car owner belongsTo model just like above.





Component sharing variable for some reason

I have some weird behaviour with a wrapped component I have created.




  1. When I change the route, the steps[] seems to stick around so that if I go back and forth between two routes, my steps array does no get reinitialized and gets bigger and bigger thus I need to manually reinitialize it:



    setup : function() {
    this.set('steps', []);
    }.on('init'),



Why do I need to do this? I thought components were regenerated when you visit the route again.



  1. Another very weird behaviour is that if I have two of these components on the same page and don't use the setup function above, they are sharing the same steps[]. How can this be since components are completely separated from each other? It is almost like the step[] is a global variable or something.


wizard-for.js



export default Ember.Component.extend({
tagName:'div',
attributeBindings:['role', 'model', 'guided'],
role : 'tabpanel',
model : null,
tab:'tab',

steps : [],

guided : true,
notGuided : Ember.computed.not('guided'),

setup : function() {
this.set('steps', []);
}.on('init'),

showNext : function() {
this.$('.nav-tabs > .active').next('li').find('a').tab('show') ;
},

showPrevious : function() {
this.$('.nav-tabs > .active').prev('li').find('a').tab('show') ;
},

actions : {
tabClicked : function() {
return false;
}
}

});


wizard-for.hbs



<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
{{#each step in steps}}
<li role="presentation" {{bind-attr class="step.isActive:active guided:disabled"}}>
{{#if guided}}
<a aria-controls="{{unbound step.elementId}}">{{step.title}}</a>
{{else}}
<a aria-controls="{{unbound step.elementId}}" href="{{unbound step.tabLink}}" data-toggle="tab" role="tab">{{step.title}}</a>
{{/if}}
</li>
{{/each}}
</ul>

<!-- Tab panes -->
<div class="tab-content">
{{yield}}
</div>


wizard-step.js



export default Ember.Component.extend({
tagName:'div',
attributeBindings:['role', 'title'],
classNames : ['tab-pane'],
classNameBindings : ['isActive:active'],
isActive : false,
role : 'tabpanel',
title : '...',

guided : Ember.computed.alias('parentView.guided'),
notGuided : Ember.computed.alias('parentView.notGuided'),

tabLink : function() {
return '#' + this.get('elementId');
}.property(),

setup : function() {
var steps = this.get('parentView.steps');
steps.pushObject(this);
}.on('init'),

model : Ember.computed.alias('parentView.model'),

actions : {
next : function() {
var parent = this.get('parentView');
parent.showNext();
},

previous : function() {
var parent = this.get('parentView');
parent.showPrevious();
}
}

});


wizard-step.hbs



{{yield}}

{{#if guided}}
<div>
<button type="button" class="pull-right btn btn-primary" {{action "next"}}>Next</button>
<button type="button" class="pull-left btn btn-default" {{action "previous"}}>Previous</button>
</div>
{{/if}}


Example Usage



{{#wizard-for model=model2 guided=true}}
{{#wizard-step isActive=true title='Step 1'}}
hello
{{/wizard-step}}

{{#wizard-step title='Step 2'}}
world
{{/wizard-step}}
{{/wizard-for}}


<h3>Wizard - Not Guided</h3>
{{#wizard-for model=model3 guided=false}}
{{#wizard-step isActive=true title='Step 3'}}
hello
{{/wizard-step}}

{{#wizard-step title='Step 4'}}
world
{{/wizard-step}}
{{/wizard-for}}




Ember.js QUnit Test Only Visible Elements With find()

I'm trying to TDD my first Ember app. I want to display one <article> element at a time. I'm getting several articles from the server. My show view defines isVisible() so that only one <article> is displayed to the user at a time.


In my test, I want to do something like:


equal(find('article').text(), 'foobar');


The problem is that it finds all the articles whether they're visible or not.


I'm fairly new to Ember so I have some ideas of what to do from here but none seems ideal.


I could look for the enclosing <div id="embernnn" class="ember-view> tags and reject the instances where Ember has applied the inline display:none style. But that would rely on the implementation rather than the abstraction.


I could use the view to add a class to the current <article> but if I have to do that then why would Ember provide the isVisible property in the View?


I'm guessing there's a better way?





How to define multiple hasMany relationships of same(parent) type on model?

I want to define multiple hasMany relationships on Ember Data model of parent type, but I don't have a clue how to specify inverses for this:



Profile = DS.Model.extend
# ...
friends: DS.hasMany 'profile', async: true
observed: DS.hasMany 'profile', async: true
observers: DS.hasMany 'profile', async: true


It would be easy for me to handle such properties in database, however Ember Data doesn't support this. Is this possible to have this 3 hasMany relationships defined without creating another models (eg. Friend, Observer).


Error I'm getting:



Error: Assertion Failed: You defined the 'friends' relationship on app@model:profile:, but multiple possible inverse relationships of type app@model:profile: were found on app@model:profile:. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses






Sideloading with Ember ActiveModelAdapter and Rails

I have two models:



user: [
firstName: DS.attr('string'),
lastName: DS.attr('string'),
animals: DS.hasMany('animal', { async: true })
]

animal: [
name: DS.attr('string'),
user: DS.belongsTo('user', { async: true })
]


When I see animals route all works fine, the JSON that rails return is like:



{"animals":[{"id":1,"name":"Wiskey","user_id":3}


and Ember call a GET for the user/3.


When I try to find all users what I have is this json:



{"users":[{"id":3,"firstName":"Bob","lastName":"Marley","animal_ids":[4,8,14]}


but no GET was call for the animals 4, 8 and 14. What is the problem? The adapter that I use is ActiveModelAdapter.


Thanks!





EmberJS: Where to place a function for computed properties?

For some of my models I’d like to use the same computed property. But instead of writing the same function in every single model like this:



imageURL: function(){
var path = '/images/',
ext = ".jpg";
return path + this.get('shortID') + ext;
}.property('shortID')


I would like to to something like this



imageURL: function(){
return makeImageURL(this.get('shortID'));
}.property('shortID')


And have this makeImageURL function somewhere:



makeImageURL = function(shortID) {
var path = '/images/',
ext = ".jpg";
return path + shortID + ext;
}


But where? BTW I am using Ember-CLI.





How to implement a subtotal of all orders?

The following, renders: Subtotal: P[object Object]


It seems that subtotal is returning the promise object instead of th sum of all orders. VARIATION 2 also returns a promise.


How should I go about calculating the subtotal of all products?



// app/controllers/application.js
import Ember from 'ember';

export default Ember.ObjectController.extend({
subtotal: function() {
// VARIATION 1:
var productCollectionPromises = this.get('orders').getEach('product');
var sum = 0;

return Ember.RSVP.all(productCollectionPromises).then(function(productCollections){
productCollections.forEach(function(product){
sum += product.get('amountInCents');
});

return sum;
});

// VARIATION 2:
// return this.get('orders').mapBy('product').reduce(function(previousValue, product) {
// return previousValue + product.get('amountInCents');
// }, 0) / 100;
}.property('orders.@each.total'),
});

// app/templates/application.hbs
<br /><strong>Subtotal:</strong> ${{subtotal}}




How to fetch all data in one request in Ember Data?

I am using the ember 1.8.1, ember data 1.0.0-beta 11. I have two types name A and B the relationship is like



A = DS.Model.extend({
bs: DS.hasMany('B', {async: true})
});
B = DS.Model.extend({
a: DS.belongsTo('A')
});


According this post: http://thau.me/2014/09/ember-data-mastering-async-relationships/


When I try to fetch the bs in a.model in template like this: {{#each b in model.bs}}


The ember's RESTAdapter will send a http request like this: URL/bs?ids[]=1&ids[]=2


But it will send several request like this: URL/b/1 URL/b/2


Is the behavior of ember data changed in new version? How can I combine the requests to 1 request?





Ember model not saving changes from itemController

In a parentController I'm trying to save changes that are made in an itemController. I can see that the model is changed in the store but when I save the model the changes are gone. The team model has a members hasMany relationship and I. All of this happens in a modal dialog.


My code is something similar to this:



// editing in the itemController

.....
var members = this.get('model.members'),
currentMember = this.get('activeMember.content'),
isChecked = this.get('isChecked');

if (isChecked === true)
members.pushObject(currentMember);
else
members.removeObject(currentMember);
.....


-



// saving in the parentController

.....
this.store.find('team').then(function(team){
team.save();
}
.....




Why is keyword not being rendered?

I've got the following. All works well. But {{keyword}} in app/templates/search/results.hbs is not being rendered at all...


Any pointers?



// app/router.js
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
location: config.locationType
});

Router.map(function() {
this.resource('search', { path: '/search' }, function() {
this.route('results', { path: ':keyword' });
});
};

// app/routes/application.js
import Ember from 'ember';

export default Ember.Route.extend({
actions: {
search: function(keyword) {
this.transitionTo('search.results', keyword);
}
}
});

// app/routes/search/results.js
import Ember from 'ember';

export default Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
products: this.store.find('product', { name: params.keyword, status: 'available' })
});
}
});

// app/templates/application.hbs
<form {{action "search" keyword on="submit"}}>
{{input type="text" value=keyword placeholder="search" class="search"}}
</form>

// app/templates/search/results.hbs
<h3>Searching "{{keyword}}"</h3>
{{product-list products=products action='addToCart' fromRoute='index'}}




dimanche 28 décembre 2014

Is Ember data support ie8,if not,what can i do to fix it


DEBUG: ------------------------------- ember-1.9.1.js:3935
DEBUG: Ember : 1.9.1 ember-1.9.1.js:3935
DEBUG: Ember Data : <%= versionStamp %> ember-1.9.1.js:3935
DEBUG: Handlebars : 2.0.0 ember-1.9.1.js:3935
DEBUG: jQuery : 1.11.1 ember-1.9.1.js:3935
DEBUG: -------------------------------


it throw an error:"the object don't support the property or function" when i give the code blow:



Hwv.Login = DS.Model.extend({
name: DS.attr('string'),
password: DS.attr('string')
});

Hwv.LoginRoute = Ember.Route.extend({
model:function(){
debugger;
var login = this.store.createRecord("login");//if i remove this row,it don't throw any error;
debugger;
// when it in this debugger,it don't throw any error;
//but when all of the script runned completed,it just throw an error message like above;
return login;
//if i change 'return login' to 'return {}',the issue still appear;
// return {};
}
});


My ask:'Is Ember data support ie8,if not,what can i do to fix it.',thanks.





Ember - linking to JSON file

I'm working through a tutorial/example from codeschool. It's all working nicely but the example is using



App.ApplicationAdapter = DS.FixtureAdapter.extend();


and I would like to now keep everything exactly as it is, but move the product data to an external JSON file.


Here is my app.js file:



var App = Ember.Application.create({
LOG_TRANSITIONS: true
});

App.Router.map(function(){
this.route('about', {path:'/aboutus'});
this.resource('products', function() {
this.resource('product', { path: '/:product_id' });
});
});

App.ApplicationAdapter = DS.FixtureAdapter.extend();

App.IndexController = Ember.Controller.extend ({
productsCount: 6,
logo: 'images/logo.png',
time: function() {
return (new Date()).toDateString()
}.property()
});

App.Product = DS.Model.extend({
title: DS.attr('string'),
price: DS.attr('number'),
description: DS.attr('string'),
isOnSale: DS.attr('boolean'),
image: DS.attr('string'),
reviews: DS.hasMany('review', {async:true})
});

App.Review = DS.Model.extend ({
text: DS.attr('string'),
reviewedAt: DS.attr('date'),
product: DS.belongsTo('product')
});

App.ProductsRoute = Ember.Route.extend({
model: function() {
return this.store.findAll('product');
}
});



App.Product.FIXTURES = [
{
id: 1,
title: 'Flint',
price: 99,
description: 'Flint is a hard, sedimentary cryptocrystalline form of the mineral quartz, categorized as a variety of chert.',
image: 'images/products/flint.png',
reviews: [100,101]
},
{
id: 2,
title: 'Kindling',
price: 249,
description: 'Easily combustible small sticks or twigs used for starting a fire.',
image: 'images/products/kindling.png',
reviews: [100,101]
}
];

App.Review.FIXTURES = [
{
id: 100,
product: 1,
text: "Sarted a fire in no time"
},
{
id: 101,
product: 1,
text: "Not the brightest flame of the flame"
}
];


Here is my HTML (index.html) file:



<!DOCTYPE html>
<html>
<head>

<script src="jquery-1.10.2.js"></script>
<script src="handlebars-v2.0.0.js"></script>
<script src="ember-1.9.1.js"></script>
<script src="ember-data.js"></script>
<script src="app.js"></script>
<script src="products.json"></script>
<link rel="stylesheet" href="bootstrap.css">

</head>


<body>


<script type='text/x-handlebars' data-template-name='application'>
{{#link-to 'index'}}Homepage{{/link-to}}
{{#link-to 'about'}}About{{/link-to}}
{{#link-to 'products'}}Products{{/link-to}}

<div class='navbar'>..</div>
<div class='container'>{{outlet}}</div>
<footer class='container'>..</div>
</script>

<script type='text/x-handlebars' data-template-name='index'>
<h1>Welcome to the Flint & Flame!</h1>
<p>There are {{productsCount}} products</p>
<img {{bind-attr src='logo'}} alt='logo' />
<p>Rendered on {{time}}</p>
</script>

<script type='text/x-handlebars' data-template-name='about'>
<h1>About the Fire Spirits</h1>
</script>

<script type='text/x-handlebars' data-template-name='products'>
<div class='row'>
<div class='col-md-3'>
<div class='list-group'>
{{#each}}
{{#link-to 'product' this classNames='list-group-item'}}
{{title}}
{{/link-to}}
{{/each}}
</div>
</div>
<div class='col-sm-9'>
{{outlet}}
</div>
</div>
</script>

<script type='text/x-handlebars' data-template-name='product'>
<div class ='row'>
<div class ='col-md-7'>
<h1>{{title}}</h1>
<p>{{description}}</p>
<p>Buy for $ {{price}}</p>
</div>
<div class='col-md-5'>
<img {{bind-attr src='image'}} class ='img-thumbnail' 'img-rounded' />
</div>
<h3>Reviews</h3>
<ul>
{{#each reviews}}
<li>{{text}}</li>
{{else}}
<li><p class='text-muted'>
<em>No reviews yet</em>
</p><li>
{{/each}}
</ul>
</div>
</script>


<script type='text/x-handlebars' data-template-name='products/index'>
<p class='text-muted'>Choose a product</p>
</script>

</body>
</html>


The tutorial says to create a json file with the following in it:



{"products": [
{
"id": 1,
"title": "Flint",
"price": 99,
"description": "Flint is a hard, sedimentary cryptocrystalline form of the mineral quartz, categorized as a variety of chert.",
"isOnSale": true,
"image": "images/products/flint.png",
"reviews": [100,101]
},
{
"id": 2,
"title": "rfgergerg",
"price": 34,
"description": "sdfdfsdfsdfsdf, categorized as a variety of chert.",
"isOnSale": false,
"image": "images/products/flint.png",
"reviews": [100,101]
}
],
"reviews": [
{"id": 100, "product":1, "text": "efefefefefe"}
]
}


and then to change



App.ApplicationAdapter = DS.FixtureAdapter.extend();


to:



App.ApplicationAdapter = DS.RESTAdapter.extend();


etc.


I can't seem to link to this JSON file. I just wanted to know, should I add anything else to the above ApplicationAdapter? Am I right to include the JSON file in the head of my HTML file?


Basically just need some assistance in making the above example, which works fine, use an external JSON file instead.


Thanks!





Ember-CLI - How to dynamically add component?

I am trying to add a new component dynamically using the following code:



var view = Ember.View.create({
template: Ember.Handlebars.compile('{{image-upload}}')
});
Ember.run(function() {
view.appendTo(document.body);
});


but I get the error:


Uncaught Error: Assertion Failed: You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.


Can someone point me in the right direction please?





Propagate action from nested component to AppController

I have a component nested several levels down in other components. I'm trying to propagate an action all the way up to the AppController in order to open a modal.


The only way I know of doing this is to pass in the action to each component - but this seems extremely impractical. Is there a better way to access the AppController from a nested component?


See my jsbin for the code



App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
});

App.AppController = Ember.Controller.extend({
actions: {
openModal: function(){
alert('this would open the modal')
}
}
})

App.MainComponentComponent = Ember.Component.extend({})

App.SubComponentComponent = Ember.Component.extend({
actions: {
triggerModal: function(){
// need to trigger the openModal action on the AppController
this.sendAction('openModal')

}
}
})


.



<script type="text/x-handlebars" data-template-name="index">
<h1>Index</h1>

{{main-component model=model}}
</script>

<script type="text/x-handlebars" data-template-name="components/main-component">
<h2>Main component</h2>

{{#each color in model}}
{{sub-component color=color}}
{{/each}}
</script>

<script type="text/x-handlebars" data-template-name="components/sub-component">
<button {{action "triggerModal"}}>{{color}}</button>
</script>


EDIT: I'm aware that I can render a template into the modal outlet:



this.render(modalName, {
into: 'application',
outlet: 'modal'
});


But I'm trying to access an action on the AppController.





Ember class attributes for falseys are not being assigned when rendering page

Ember class attributes for falseys are not being assigned when rendering page. I have two button elements Yes / No. The inactive button has a class rendering the opacity : .3 That is working fine. However I need to set a default behavior on these buttons so that on rendering the page the Yes is inactive. Should be simple I just set the property accordingly. However it isn't adding the appropriate class for the false value.


Hope it is clear what I am trying to do and what the problem is. Thank you for your time.


I made a JSbin http://jsbin.com/vixayatuda/1/edit?html,css,js,output



window.App = Ember.Application.create();

App.ApplicationController = Em.Controller.extend({
takingTrade: false,

actions: {
makeTrade: function() {
this.set('takingTrade', true);
},
makeNotTrade: function() {
this.set('takingTrade', false);
}

}
});


<script type="text/x-handlebars">
<button {{action 'makeTrade' this}} class="btn btn-success" {{bind-attr class="takingTrade::inactive"}}>YES</button>
<button {{action 'makeNotTrade'}} class="btn btn-success" {{bind-attr class="takingTrade:inactive"}}>NO</button>
<p>{{takingTrade}}</p>
</script>




ember event trigger order is different in app and tests

I have written this simple demo component to demonstrate a problem. The component code is below



App.FocusOutComponent = Em.Component.extend({
attributeBindings: ['tabindex'],

tagName: 'focus-out',

setFocus: function() {
console.log('clicked focus-out container');
this.$().find('button').focus();
console.log('focus set to button');
}.on('click'),

focussedOut: function() {
console.log('focussedOut from outer container');
}.on('focusOut'),
});

{{#focus-out id="focus-container" tabindex="-1"}}
<button id="text-button">Test Button</button>
{{/focus-out}}


When I run this and click on the focus-out element, this is the order of the logs. Link to demo



  1. clicked focus-out container

  2. focussedOut from outer container

  3. focus set to button


Now when I am trying to write acceptance tests for this with the following code.



test('test visit / and click button', function() {
expect(0);
visit('/').then(function() {
find('focus-out').click();
console.log('after click in test');
});
});


The order of the logs are different. Link to demo .



  1. clicked focus-out container

  2. focus set to button

  3. after click in test

  4. focussedOut from outer container


The focusOut log got printed at the very end instead before the after click log.


Im not sure if this is a bug or something wrong with my code.


I also noticed another problem while executing tests. If I have focus on the chrome dev-tools while the tests are running, the focusOut event will not trigger at all.


Some help with this is much appreciated.





samedi 27 décembre 2014

Non-resourceful routes in Ember Data

I'm writing a signup form on the home page of my web app. The form has a user model and a reminder model, both Ember Data models.


When the form submits it POSTs to /api/signups. The back-end creates the user, creates the reminder, and sends an email. There is no actual signup record created in a database.


How can I send my reminder + user data to this URL using Ember Data? I'm able to embed the reminder in the user and thereby get all the data over in one payload, but I'm not sure the most idiomatic way to tell Ember Data's adapter to POST to /api/signups (instead of e.g. /api/users or /api/reminders.





Does iron:router have an equivalent to Ember's transitionToRoute?

I need the ability to programmatically route to different pages. As far as I can tell the only way to actually render a route is from within the Route declaration as such:



Router.route('/', function() {
this.render('index');
});


What I'm looking for is the ability to from some arbitrary part of the code to transition to another route. i.e. if(whatever) Route.transionToRoute('homepage');


I by snooping around found that I could use Router.dispatch, but I got some buggy behavior that I believe originated from that usage, in addition I got some strange debug warnings in the console. It appears to be an internal method as I can't find any documentation on it.


Can what I've described be done with iron router?


Thanks for any help :)





getting a 500 error when trying to update http-mock in ember

I'm getting a 500 server error in the console when trying to update a record from an http-mock generated in ember-cli.


Here is what I'm trying to do



model: function(params) {
return this.store.find('user', params.pin);
},
actions: {
check_out: function(checkedUser) {
var model = this.modelFor(this.routeName);

model.set('checked_in',false);

model.save().then(function(){
self.transitionTo('volunteer-check-out-success');
});
}
}


but I'm receiving this error in the console



PUT http://localhost:4200/api/users/2 500 (Internal Server Error)


the get request works just fine so it's odd that I'm getting 500 with the put request.


Does anyone have a good overview of how to use http-mock? Maybe even in it's earlier stages before it was called http-mock? I'm still a little confused on how this works inside of ember-cli and documentation and examples are kind of sparse from what I've been finding. And I think reading up on some info on how this works in theory would help me troubleshoot it on my own.





Model is undefined after transitioning away then back to a route

I have a route.



import Ember from 'ember';

export default Ember.Route.extend({
model : function (params) {
return Ember.RSVP.hash({
eventTypes : this.store.find('event-type'),
game : this.store.find('game', params.game_id)
});
},

setupController : function (controller, model) {
controller.set('game', model.game);
controller.set('eventTypes', model.eventTypes);
}
});


When I first visit this route all is well. The models get loaded and I can access game and eventTypes from my template. If I am to transition away from this route and then revisit the route both eventTypes and game are undefined. Why would the route transition with out error and return undefined models?





vendredi 26 décembre 2014

Setting "active" state on Twitter Bootstrap dropdown in Ember with "each" helper rendering dropdown items

Using Twitter Bootstrap and Ember, I'm trying to set the "active" state on the dropdown when a child item is selected, when that child was rendered using an "each" loop.


e.g.:


Snippet of my navbar in emblem:



ul.nav.navbar-nav
link-li
link-to 'index' | Home
link-li classNames='dropdown'
a.dropdown-toggle href='#' data-toggle='dropdown' Items <span class='caret'></span>
ul.dropdown-menu
each item in items
link-li
link-to 'item' item
= item.name
link-li
link-to 'items.new' | Create New...


link-li helper from Add "active" class to bootstrap dropdown menu when dropdown link selected (with Ember link-to)



export default Ember.Component.extend({
tagName: 'li',
classNameBindings: ['active'],

active: function(){
return this.get('childViews').isAny('active');
}.property('childViews.@each.active')
});


This works great in these cases:



  • Home is highlighted when on the index route

  • Each item is highlighted when on each item route

  • The Create New link is highlighted when on the items.new route

  • The dropdown itself is highlighted when on the items.new route


But, the dropdown does not get highlighted when on each of the individual item routes.


I've investigated as far as finding out that this.get('childViews') only returns the one "Create New" view, seemingly ignoring the other items. It appears to be related to the each helper, because any additional regular links added under "Create New" will work just fine. And that's where my n00b Ember knowledge ends.


Any help would be appreciated!





Handling a click and a tap but not a scroll

I have an Ember.View that handles both the click and touchEnd events, for both desktop and mobile interactions.


Unfortunately, touchEnd also gets fired when scrolling, which is not intended. How do I handle the click and tap, but avoid the scroll event?



Ember.View.extend({
click: function() {
// not handled in a mobile browser
},
touchEnd: function() {
// handled in a mobile browser, but unfortunately also on scroll
}
});




Is Ember RESTAdapter namespace inheritable?

Suppose we have the following code:



App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: '/webapp_name'
host: 'http://localhost:8080'
});

App.PersonAdapter = DS.RESTAdapter.extend({
namespace: '/foo/bar'
});


So, is the model App.Person targeting at http://localhost:8080/webapp_name/foo/bar/person or http://localhost:8080/foo/bar/person?





Why is my model.reload() in afterModel redirecting to a related model?

For some reason calling model.reload() in my afterModel is redirecting to a related model's route, and I can't seem to figure out why.



SkillRoute = Ember.Route.extend
model: (params) ->
@store.find('skill', {slug: params.slug}).then (model) =>
model.get('firstObject')
afterModel: (model) ->
model.reload() # offending line




after render / didInsertElement only fires on first transition

JS BIN - http://ift.tt/1roUTdB


I have a sample jsbin above with a single route "conversation/:id". I want to run some jquery each time the view has rendered the new model but using the "didInsertElement" and "afterRenderEvent" hook only runs my code on the first transition.


I read about the same issue here http://ift.tt/1BcKn97 but wasn't able to find a solid solution.


Below is the code I hope to run each time



App.ConversationView = Ember.View.extend({
afterRenderEvent: function() {
alert('this should run on each transition');
}
});


Is there a completely different approach that I need to take? Or perhaps a minor tweak?





Why does the ember.js starter kit include jQuery 1 and the NuGet package requires v2?

I would like to use the Ember.js NuGet package but I need to support IE 8 which means I will need to use jQuery v1. That's also what's in the starter kit. Is the NuGet package really dependent on jQuery 2? Is there any way to configure my app to use NuGet for jQuery 1 and Ember?





Access the store from a model's static (aka class-level) method?

I've got this:



Post.reopenClass({
myStaticMethod: function() {
// I need to access the store here!
// this.store => undefined
}
});


PS Why can't i just import the store or something?





Rails: change default JSON structure

I'm new in Rails and I use the version 4.2.0.


Let's suppose that we have the following JSON at the url localhost:3000/users



[{id: 1, "firstName": "John","lastName": "Smith"},
{id: 2, "firstName": "John","lastName": "Red"}]


but this is not what I want, I expect something like:



{ users :[
{id: 1, "firstName": "John","lastName": "Smith"},
{id: 2, "firstName": "John","lastName": "Red"}
]}


How can i do? Thanks everybody.





Implementation of Site-wide arrayController in Ember

I have been looking to a solution to this for about a week now with no luck. We have an ember application which has a sidebar that is present on all routes which displays a list of user posts. It is important that the posts update in real-time as they are submitted as well as sort with the newest post at the top of the list, which from what I've read will require an array controller. The problem is, I cant find any way (or rather dont understand) to use an array controller and specific model that is not directly referenced to the current route. I have tried rendering the sidebar with the following code in the application route:



Destination.ApplicationRoute = Ember.Route.extend({

model: function(model) {

var self = this;

return new Em.RSVP.Promise(function (resolve, reject) {

new Em.RSVP.hash({

post : self.store.find('post')

}).then(function (results) {

resolve({

post: results.post

});
});
});
},

renderTemplate: function(controller, model) {

this.render();

this.render('sidebars/postBar', {

outlet: 'postbar',

into: 'application',

controller: 'posts',

model: 'post'

});
}


Then I have the following code for my array controller



Destination.PostsController = Ember.ArrayController.extend({

itemController: 'post',

sortProperties: ['id'],

sortAscending: false

});


However this doesnt work at all and I'm having trouble finding any examples of how to accomplish this.





Is there any example for reflexive relation?

I am trying iterate json response which more likely mentioned below and I want achieve this model through reflexive relation.



{
folders : [

{
id : 1,
folders [ { id : 1, folders : [] } ]
},
{
id : 2,
folders : [{ id : 1, folders : [ {id:1 , folders : [] }] }]

}

]
}


I here is my try children: DS.hasMany('folders', {inverse: 'parent'}), parent: DS.belongsTo('folders', {inverse: 'children'})

But does't work at all . is there any example ?





How to load a custom location in Cordova+Ember when user click on system notification?

I have an app made in Cordova using Ember framework.


When I receive a system notification I want to open a custom location based on id that notification send me. Notification call a method out of Ember route/controller system.


How I can call a ember router to load a custom location based on notification id if the method are not inside Ember managed code?


Regards.





jeudi 25 décembre 2014

ember different controller for a property

I have a session and a test. Session holds many tests - so in the model it is a DS.HasMany.


The view has a tests table, and I want it to be sortable. So the question is - how can I define a tests controller to the tests "property" in session


session.hbs:



<div class="main-container">
<h1>session {{id}}</h1>

<table class="tests-table table table-bordered">
<tr>
<th>ID</th>
<th>Logical ID</th>
<th>name</th>
</tr>
{{#each test in tests}}
<tr>
<td>{{test.id}}</td>
<td>{{test.logicalId}}</td>
<td>{{test.name}}</td>
</tr>
{{/each}}
</table>
</div>


routes/session.js:



import Ember from 'ember';

export default Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
session: this.get('store').find('session', params.session_id),
tests: this.get('store').find('test', {
session_id: params.session_id
})
});
},

setupController: function(controller, model) {
controller.set('model', model.session);
var testsController = this.controllerFor('tests');
testsController.set('model', model.tests);
}
});




Looping over an ArrayController fails as it is not an Array even though the Controller has the correct model with data

I am attempting to use an ArrayController to handle displaying some data that will be swapped out on user clicks. I currently get this error, Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed App.CurrentListController but If I look at Ember Inspector I can see the CurrentListController and it has the model and the data in it. Basically the Stat page lets you see a bunch of stats and clicking on a specific stat pops up a modal and shows all the record that relate to that stat. If I just store the records on the StatController it works fine but then I cant sort/filter using the ArrayController. So it all works except for when I try and display the contents of CurrentListController it freaks out.


Thanks for any help or direction.


CurrentListController:



App.CurrentListController = Ember.ArrayController.extend({
sortProperties: ['name'], //Initial sort column.
sortAscending: true,
});


StatController:



App.StatController = Ember.ObjectController.extend({
needs:['currentList'],
currentList:[],

actions: {
viewBusiness: function(ids) {
console.log(ids)
var self = this
console.log(this.get('controllers.currentList').get('sortProperties'))
this.store.findByIds('business', ids.split(",")).then(
function(results)
{
$('#editModal').modal('show');
//self.set('currentList', results.sortBy(["name"]))
self.get('controllers.currentList').set('model', results)

console.log(self.get('controllers.currentList').get('arrangedContent'))
});
},
sortBy: function(prop){
var clController = this.get('controllers.currentList')
clController.set('sortProperties', prop)
clController.set('sortAscending', !clController.get('sortAscending'));
}
}
});


Stat Template:



{{#each business in App.CurrentListController}}
<tr {{bind-attr id=business.id}}>
<td>{{business.name}}</td>
<td>{{business.city}}</td>
<td>{{business.state}}</td>
<td>{{business.zip}}</td>
<td class="text-center">{{business.numVendors}}{{/link-to}}</td>
<td class="text-center">{{business.numClients}}{{/link-to}}</td>
</tr>
{{/each}}




Saving two new related objects in one request

I have two models in Django:



class Thread(models.Model):
entity = models.ForeignKey(Entity, null=True, blank=True)
...

class ThreadMessage(models.Model):
thread = models.ForeignKey(Thread, related_name='messages')
author = models.ForeignKey(User)
...


Now a client wants to create a new thread with first message in it. It has first to do a POST /threads to create a new thread and find out its id and then do POST /messages passing the found id in thread field.


I am thinking if it's reasonable and possible to do all of this in one request from Ember like:



POST /messages
{"message": {"text": "text", ...},
"thread": {"entity": 1}}


And the response would be:



{"message": {"text": "text", "id": 5678, "thread": 1234, ...},
"thread": {"entitity": 1, "id": 1234, ...}}




How to make ember component fetch data from server. put AJAX call inside the component seems not a good practise to handle this

An Ember Component needs to fetch data from serve, however i think put AJAX call inside the component is not a good practise.


Or use the Route to fetch data, then pass data to component.But the route's method can't share easily between different routes.





Ember.js How to bind isSelected class to the clicked view?

I have some views which will expand and show details when clicked.


For now, all the views can be clicked and expand, but the question is


How to expand only the latest clicked view?


For example, when I clicked view #1, it expand. So when I clicked view #2, the view #1 will collapse and view #2 expand etc.


I know we can bind a isSelected classname to the clicked view, but how do we tell the view to check "If any other view is selected" ?


Do we use CollectionView ? But how?


FYI this is the working JSBin.





How do I set a dynamic model attribute in the fixture?

As the title describes, I am running into trouble making a dynamic attribute on the Fixture layer.


Here is an example model:



App.Pokeball = DS.Model.extend({
name: DS.attr('string'),
ballRate: DS.attr('number'),
battleAttributes: DS.belongsTo('battleAttributes')
});


And my Fixture:



App.Pokeball.reopenClass({
FIXTURES : [
{
id: 1,
name: 'PokeBall',
ballRate: 1
},
{
id: 23,
name: 'Dusk Ball',
ballRate: function() {
// Some logic that applies only model #23
return 2;
}.property('battleAttributes')
}
]
});


I scoured online trying to find out the right way to do this, but have instead ran into a dead end. :(





One-way relationships with ember-data

I am trying to set up a simple platform for employees to give feedback to each other. I am using ember-data (from beta branch).


Models:



App.Employee = DS.Model.extend({
name: DS.attr()
})

App.Feedback = DS.Model.extend({
text: DS.attr(),
employee: DS.belongsTo('employee', {async: true})
})


Router (simplyfied):



App.Router.map(function(){
this.resource('profile', {path: 'profile/profile_id'})
})

App.ProfileRoute = Ember.Route.extend({
model: function(params){
return this.store.find('employee', params.profile_id);
}
})


Data:



App.Employee.reopenClass({
FIXTURES: [
{ id: 1, name: 'Trek'},
{ id: 2, name: 'Tom'}
]
});

App.Feedback.reopenClass({
FIXTURES: [
{ id: 1, text: 'Topic1', employee: 1},
{ id: 2, text: 'Topic2', employee: 2},
{ id: 3, text: 'Topic3', employee: 1},
{ id: 4, text: 'Topic4', employee: 2}
]
});


I can't get a list of feedbacks to display in the template profile.


Template:



{{#each feedback in model.feedback}}
{{feedback.text}}
{{/each}}


I can't figure out, what I'm doing wrong.


Should I specify feedbacks: DS.hasMany('feedback') under App.Employee? Or should I do this through the controller?





data from http-mock not showing in template

I set up an http-mock like so on the get http verb



usersRouter.get('/:pin', function(req, res) {
res.json({
"users": {
"id": 1234,
"pin": 1234,
"first_name": "John",
"last_name": "Doe",
"email": "email@example.com",
"phone": 8436376960
}
});
});


my route is looking up this information like so with a pin number passed as a param from a form input on a previous page



model: function(params) {
this.store.find('user', params.pin);
}


my template is simply trying to display them like so



<span class="name">{{first_name}} {{last_name}}</span>
<span class="email">{{email}}</span>


Also my model for reference



pin: DS.attr('number'),
first_name: DS.attr('string'),
last_name: DS.attr('string'),
email: DS.attr('string'),
phone: DS.attr('number')


I'm not getting an error in the console but there is nothing displayed on the page, in the ember inspector in the data tab I see my data correctly being passed to the route


Is there some piece I'm missing here? This is my first ember-cli app.





Binding values on controllers

I have two controllers, SidebarCategoriesController and MainLinksController. I have a property selectedCategory on SidebarCategoriesController and MainLinksController needs this property when rendering templates.



App.MainLinksController = Ember.ObjectController.extend({
needs: "sidebarCategories"
});

App.SidebarCategoriesController = Ember.ObjectController.extend({
selectedCategory:2,
actions: {
setCategory: function (id){
this.set('selectedCategory',id);
}
}
});


I also have a templete(below) whose controller is MainLinksController:



<script type="text/x-handlebars" data-template-name="main_links">
<h2 class="panel-title">All links:{{controllers.sidebarCategories.selectedCategory}}</h2>
</script>


The issue is that when selectedCategory is being updated in SidebarCategoriesController, the template which is using selectedCategory from MainLinksController via {{controllers.sidebarCategories.selectedCategory}} is not getting updated. How can i make the binding so that as soon as the selectedCategory changes in SidebarCategoriesController, {{controllers.sidebarCategories.selectedCategory}} also changes in the template ?





How can I derive the content of my select view from records in ember?

I have this:



App.LoginRegisterController = Ember.ObjectController.extend({
init: function () {
this.set('products', this.store.find('product'));
},
subscriptionOptions: function () {
return this.get('products').map(function (product) {
return {id: product.id, title: product.title};
});
}.property('products')
});


Then in my template:



{{view "Ember.Select"
content=subscriptionOptions
optionValuePath='content.id'
optionLabelPath='content.title'}}


However subscriptionOptions only get called once before the products are populated. If I change the template to:



{{view "Ember.Select"
content=products
optionValuePath='content.id'
optionLabelPath='content.title'}}


The data gets populated correctly, but I need to insert an option into the select that isn't related to any of the models, so I need to populated it with references. How can I get the select to update from subscriptionOptions as products change?