samedi 31 janvier 2015

Ember-Data Embedded Polymorphic BelongsTo not working

I've been trying to get polymorphic associations working for me in Ember Data, but I haven't had any luck yet. Hopefully someone can have a look and let me know if I'm missing something.


I'm using Ember 1.8.1 and Ember-Data 1.0.0-beta.14.1. Also, we are using the ECMAScript6 syntax (import, export default).


Basically, we just have one embedded polymorphic relationship that doesn't seem to be working for us. If anyone has any suggestions or ideas about why this isn't working, I'd love some help. I've been stuck on this one for a few days now.


That's basically what we are having trouble with. The error that I get returned is:

Error: Assertion Failed: You can only add a 'metadata' record to this relationship





// /app/models/metadata.js:
export default DS.Model.extend({
type: DS.attr('string'),
lastModified: DS.attr('number');
});

// /app/models/metadata-story.js
import Metadata from '/app/models/metadata';
export default Metadata.extend({
body: DS.attr('string')
});

// /app/models/metadata-photo.js
import Metadata from '/app/models/metadata';
export default Metadata.extend({
url: DS.attr('string'),
width: DS.attr('number'),
height: DS.attr('number')
});

// /app/models/post.js
export default DS.Model.extend({
headline: DS.attr('string'),
metadata: DS.belongsTo('metadata', {polymorphic: true})
});


// /app/serializers/post.js
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin,{
attrs: {
metadata: {embedded: 'always'}
}
});


// /app/routes/posts.js
// Here is the code that is being run to load the records:
export default Em.Route.extend({
model: function(params){
var query = {
start: params.start,
offset: params.offset
};
return this.store.find('post', query);
}
});


// Also, here is a sample of the Payload that the normalizePayload function is returning:
{posts:[
{
id: 0,
headline: 'Well, that is SOME story!',
metadata: {
body: 'This is the body...'
},
metadataType: 'metadata-story'
},
{
id: 1,
headline: 'Well Hello',
metadata: {
url: 'http://ift.tt/16eiYus',
width: 450,
height: 350
},
metadataType: 'metadata-story'
}
]}

/*
Another thing that I should mention is that I have tried setting the Ember.MODEL_FACTORY_INJECTIONS flag to both true and false, but it has not seemed to make any difference at this point.
*/






advice on using subcomponent in ember table

I have an ember-table with editable cells, via overriding TableCell. I would like to use ic-autocomplete in the edit widget. Is there any way to specify that the ic-autocomplete actions be targeted at the tablecell-derivative (view), rather than having them hit the ember-table component, which is the "controller" in this context?


Alternately, I thought of using a "render" tag and creating a controller specific to the table row. But then it would seem that the edit widget would be just the render tag and the I would have to create yet another template w/ the ic-complete layout. Is this really the case, or can I somehow simplify?





Access model in controller-action?

I'm editing an object with a form and want to save the changed object from within the controller-action which is bound to the submit-button. I don't want to bind the values directly to the template.


Here's the admin/edit.hbs



<form>
<label>Title
<input name="title" type="text" {{ bind-attr value=title }} />
</label>
<label>Permalink
<input name="permalink" type="text" {{ bind-attr value=permalink }} />
</label>
<label>Post
{{textarea value=body cols="80" rows="12"}}
</label>
<button {{ action 'submitAction' }}>Submit</button>
</form>


This is the controller admin/edit.hbs import Ember from 'ember';



export default Ember.ObjectController.extend({
actions: {
submitAction: function() {
var newTitle = this.get('title');
// how to access the model here?
}
}
});




Npm trows 'Cannot find module 'strip-ansi' while creating new ember app

I have a trouble with creating a new app in Ember: Error: Cannot find module 'strip-ansi'. I have tried to fix it with npm install -g npm as it was described in similar topic but it does nothing. Do anybody know how to fix it ?





Reusable master/detail view best practice ember

I've been grappling with this relatively simple problem in Ember JS in a variety of my apps. I know this may seem like its been answered seven ways to Sunday but I haven't found a solution that I can actually map to my problem.


Okay, so I need a class master/detail view with a route structure like:



  • Admin Dashboard

    • Dashboard

    • Students page (displays a master list of students in a sidebar)

    • Student page (upon selecting a sidebar item, it is selected and "details appears"




This pattern is reused exactly at three different dashboards in my site. The only difference is the record array of students is different for each one. I'm asking what is the most Ember-esque way to accomplish this?


I have tried multiple solutions but each one has its own problems. Using the {render} helper to render some universal "students" template breaks because I am leveraging the router and <li> tags inside to automatically apply the active class to the selected student, and students.student isn't a route in my router. If I add that route, then it routes away from the dashboard parent route (with the navbar, etc).


I basically want to package this view into a component almost and pass it the array to display, but then how do I add the "active" class? Surely there is an easier way then manually adding and removing the class.


Thoughts?


I apologize if my question isn't super clear! Its a subtle distinction.





How to have two different models within a route and its subroute?

I'm making a simple web chat system with Ember.


I have a route /chatrooms that lists a few chatrooms, and then I also have /chatrooms/:chatroom_id that should show the actual chatroom with messages.


The second route is within the first one, like this:



this.resource('chatrooms', function() {
this.route('show', {
path: ':chatroom_id'
});
});


When I access /chatrooms, a call is made to the server (/api/chatrooms) is a list of rooms is returned and displayed, like expected.


When I click a room, the application transitions to /chatrooms/id, but no call is made to retrieve the messages (available at /api/chatrooms/id), even when I try to define a model.


I have a similar scenario with the users. A list of users is retrieved, then displayed. When a name is clicked, the profile is shown. No second call is made, but that's okay since Ember knows everything about the user already.


In my current case, when a list is first returned, it includes all the information except the messages. I believe that would be too much otherwise (10 chatrooms * 100 last messages = 1000 elements in my JSON for each request). So I want to call the server for messages only when a chatroom is selected.


Do you know how to do it, or maybe there's something wrong I'm doing in the first place?





Ember Nested Routes and rendering models

I have an invoice application generator and i want to show the invoices with all his transactions in 2 different ways, at the moment i can only do it in 1 way ( Edit Link)



  1. On Edit link where i can see all my invoices and transactions together ( it s how it works now)

  2. On View link where i want to see only the specific Invoice information with his own transactions and not any of the other invoices and informations


I have reproduced my case here


This is the route code



App.Router.map(function(){
this.resource('invoices', function(){
this.resource('invoice', { path:'/:invoice_id' }, function(){
this.route('edit');
});
this.route('create');
});

});


The problem is that as long as i am inside the invoices resources i am sharing the invoices templates where everything is generated, but is there a way where i can see only my single invoice with his own transactions inside the invoices route? Is it achievable with the same Route Code? What's the best way to get this done?



<script type="text/x-handlebars" id="invoices">
<div class="large-12 columns">
{{#link-to "invoices.create"}} Add Invoice {{/link-to}}
</div>
<ul class="fatturas-listing">
{{#each invoice in model}}
<li>
{{#link-to "invoice" invoice}}
Edit {{invoice.title}}
{{/link-to}}
</li>
<li>
{{#link-to "invoice" invoice}}
View {{invoice.title}}
{{/link-to}}
</li>
{{else}}
<li>no fatturas… :(
</li>
{{/each}}
</ul>
{{outlet}}
</script>




Template without application.hbs as root?

I've got an Ember-Cli App and would like to create an admin-interface for my application which looks nothing like the page set up in application.hbs.


How do I make the admin-interface independent from that one?





Is the ember cli addon installation broken in Ember Cli 0.1.11?

I'm using ember cli for some small test projects to evaluate the concepts. Normal use of ember cli works for me. After 10 created small projects and using blueprints and the pod structure I decided to try the development and usage of addons. The creation of addons was not the real problem.


The problem is I can not successfully install a created addon. I also tried to install other addons created by other ember-cli users. The result is always the same. I got no error message and the addon could be found inside the node_modules directory of the addon consuming application but there is nothing installed in the app directory and it's sub directories !!!


What can I do to find the problem ? Do you have a public available addon which could be installed definitely without problems ?


Are there log files which could be inspected to see more details (hidden error messages) ?


Best regads


Andreas





vendredi 30 janvier 2015

Setting Up EmberJS

I'm trying to set up EmberJS. This is my first website attempting this so please excuse my noobness. Currently nothing is outputting to the screen but the body's grey background color. I'm not sure where I went wrong in setting up my EmberJS page. Here's the code and if you need to see it in action you can view it here http://ift.tt/1zWsu1Q HTML



<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Site Demo</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/header.css">
<link rel="stylesheet" type="text/css" href="css/mainPage.css">


</head>

<body>

<script type='text/x-handlebars' data-template-name='application'>

<div class="container">
<div class="header">
<div class='col-md-1'>
Logo
</div><!--end header container-->
<div class='col-md-2 col-md-offset-1'>
<div class='link1'>
<a href="#">Link1</a>
</div>
</div>
<div class='col-md-3'>
<div class='link2'>
<a href="#">Link2</a>
</div>
</div>
<div class='col-md-2'>
<div class='link3'>
<a href="#">Link3</a>
</div>
</div>
<div class='col-md-2'>
<div class='searchBar'>
<input type="text" class="form-control" placeholder="Search Box">
</div>
</div>
<div class='col-md-1'>
<div class='searchButton'>
<button class="btn btn-search" type="submit">Search</button>
</div>
</div>

</div>

</div>

<div class="container">
<div class='underHeader'>

</div>
</div>

<div class="container">
<div class='whiteBox'>
<div class='newProducts'>
</div>
{{outlet}}
</div>
</div>
</script>
<script type='text/x-handlebars' data-template-name='index'>
<h1>Testing the page</h1>
</script>
</body>

<script src="js/jquery.easing-1.3.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/menu.js"></script>
<script type="text/javascript" src="js/libs/handlebars-v2.0.0.js"></script>
<script type="text/javascript" src="js/libs/ember-1.9.1.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</html>


CSS



var App = Ember.Application.create();

App.Router.map(function() {
// put your routes here
});

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




Why does ember ui hang during long promise call

I have a long running call that is encapsulated by a promise,


from my understanding of promises, it allows us to do asynchronous tasks that will be dealt with when they return, and until they return the function should continue.


in my example,




  1. the action is entered




  2. Updates a variable that changes the ui



  3. executes somethingLongRSVP


it should then exit the function and update the ui, but insted it waits for the promise to resolve before updating the ui.


http://ift.tt/1A9FHEF





How can I test if a function is returning a promise in Ember?

In Ember, I sometimes run into the situation where I need to check if a function is returning a promise. For example, if I have a route that is derived:



MyRoute = ParentRoute.extend({
beforeModel: function() {
this._super().then(function() {
// do something...
});
}
});


But although beforeModel can return a promise, it might not. In particular, if it's the default Ember.K implementation, then it doesn't. I'd rather not always be doing:



var res = this._super();
if (typeof res.then === "function") {
res.then(function() {
// do X
});
} else {
// do X
}


I assume there's a way to wrap something that one doesn't know if it's a thenable, and then chain regardless. But I couldn't find it in the documentation.


The above is undesirable because it's verbose, and requires having the code for X twice.


Thoughts?





My select view is loading all data at once

Here are the routes in my router -



this.resource('sources', { path: '/sources' }, function() {
this.resource('source', { path: '/:source_id' }, function() {
this.resource('notes', { path: '/notes' }, function() {
this.resource('note', { path: '/:note_id'}, function() {
this.resource('noteRevision', { path: 'revision/:note_revision_id'}, function() {

});
});
});
});
});


Relevant App.routes -



App.NoteRoute = Ember.Route.extend({
afterModel: function(note, transition) {
var revision = note.get('revisionId');
if (transition && transition.params && transition.params.noteRevision) {
revision = transition.params.noteRevision.note_revision_id;
}
this.transitionTo('noteRevision', revision);
}
});

App.NoteRevisionRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('noteRevision', params.note_revision_id);
}
});


Here are the relevant ember data models I have -



App.Note = DS.Model.extend({
revisionId: DS.attr('number'),
locationId: DS.attr('number'),
topic: DS.belongsTo('topic'),
noteRevisions: DS.hasMany('noteRevision', {
async: true
})
});

App.NoteRevision = DS.Model.extend({
dateCreated: DS.attr('date'),
isPublished: DS.attr('boolean'),
content: DS.attr('string'),
note: DS.belongsTo('note')
});


NoteRevision handlebars file -



<div class="center-pane col-sm-6">
{{model.content}}
</div>
<div class="right-pane col-sm-2">
<div class="revisions">
{{view "revisionSelect" class="form-control" content=note.noteRevisions optionLabelPath="content.id" value=model}}
</div>
<div class="date-created">
{{model.dateCreated}}
</div>
</div>


My Revision Select View -



App.RevisionSelectView = Ember.Select.extend({
selectionDidChange: function() {
this._super();
if (this.selection && this.selection.id) {
this.get('controller').transitionToRoute('noteRevision', this.selection.id);
} else {
this.get('controller').transitionToRoute('noteRevision', this.get('controller.model.revisionId'));
}
}.observes('selection')
});


Now the issue Im having, is that I don't want all the note revisions to be loaded at once. They are very large and there can be hundreds of them. The select essentially acts as a forwarder that will automatically forward the user from /note/1 to either /note/1/revision/1 if the value selected is 1 or to /note/1/revision/2 (which is the current revision, which is on the model as revisionId).


I was hoping to access the ID's of noteRevisions in App.Note then just loop over the ID's so it wouldn't actually load the revision of the note all at once. I have not found a way to do that but I am not even sure that is the right way to do it.


The way it is now, I go to /sources/1/notes/2/revision/4 and ember makes a call for /api/v1/noteRevisions/4and then it seems that it will load the rest via /api/v1/noteRevisions?ids%5B%5D=3&ids%5B%5D=6so it can fill out the select input.





With Ember Data, is it possible to save many belongs_to relations in the same request independently of the RESTAdapter or the FixtureAdapter?

I have two models with a belongs_to relation.



App.Organization = DS.Model.extend({
name: DS.attr('string'),
projects: DS.hasMany('project', { async: true })
});

Zest.Project = DS.Model.extend({
name: DS.attr('string'),
organization: DS.belongsTo('organization', {async: true, inverse: 'projects'})
});


In a controller, I have already many projects and I want to create an organization and bind it to the projects:



var self = this,
newOrganization = this.store.createRecord('organization', {name: 'My pretty organization name'});

myProjects.forEach(function (project) {
newOrganization.get('projects').pushObject(project);
});

newOrganization.save().then(
function (organization) {
self.transitionToRoute(..., ...);
},
function (reason) {
self.set('error', ...);
}
);


In production I work with Rails and the RESTAdapter. As I prefer have only one request to save the organization (and not to do many save on all the projects), I update the serializer like that:



App.OrganizationSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
// thanks EmbeddedRecordsMixin!
projects: {serialize: 'ids', deserialize: 'ids'}
}
});


On the server, when it receives the request, it create the organization and update the projects. It's works!


I was happy BUT I had problems when I tried to test my code with FIXTURES. Indeed I noticed that after the success of newOrganization.save(), the project fixtures are not updated. If I want they are updated, I have to call the save function on all the projects like that:



newOrganization.save().then(
function (organization) {
organization.get('projects').forEach(function (p) {
p.save();
});
self.transitionToRoute(..., ...);
},
function (reason) {
self.set('error', ...);
}
);


But I don't want to do that in production because each 'save' triggers a request that I don't need


So is it possible to configure the FixtureAdapter for it saves the projects of an organization while it saves this organization ? Or should I use a better manner to save these belongs_to links ?





How would I be able to add pin in Bing Maps api with this code?

How would I be able to add pin in Bing Maps api with this code:



import Ember from 'ember';

export default Ember.Component.extend({
attributeBindings: ['style'],
classNames: ['bing-map'],
bingKey: "bing-key",
width: '45%',
height: '100%',
latitude: 0,
longitude: 0,
zoom: 0,
mapTypeId: 'r', // r:road, a:aerial

init: function(){
this._super();
if (!this.get('bingKey')){
throw('Missing bingKey');
}
this.api = Microsoft.Maps;
this.map = null;
},

style: function(){
return "position: relative; width: %@px; height: %@px".fmt(
this.get('width'),
this.get('height')
);
}.property('width', 'height'),

center: function(){
var latitude = parseFloat(this.get('latitude'));
var longitude = parseFloat(this.get('longitude'));
longitude = this.api.Location.normalizeLongitude(longitude);

return new this.api.Location(latitude, longitude);
}.property('latitude', 'longitude'),

mapOptions: function(){
return {
center: this.get('center'),
zoom: parseInt(this.get('zoom'),10),
mapTypeId: this.get('mapTypeId')
};
}.property('center','zoom','mapTypeId'),

createMap: function(){
var el = this.$()[0];
var options = this.get('mapOptions');
options.credentials = this.get('bingKey');
this.map = new Microsoft.Maps.Map(el, options);
}.on('didInsertElement'),

removeMap: function(){
this.map.dispose();
}.on('willDestroyElement'),


});


I am using ember-cli and trying to set pins on the map depending on the item that is chosen inside the template table, but I am unable to get how to set a pin on the map implemented in this code (which I need). The info in the Microsoft Bing Map api website is not helping.


Anyone know how to achieve this? Thanks in advance





Difference Between Property and Observer?

Why would a computed property in a component not recognize a dependency changed within a view, but does recognize the change as an observer?


I tried two different approaches. The first one, a computed property that depended on the outside variable (favoriteId), only recognized the change some of the time. The other, an observer, sometimes recognized the change around the same time as the computed property, but also recognized it when the computed property did not. For example, it recognized both the property and observer when it inserted the element, only recognized the observer on a page transition within the same route, and only recognized the property on a page transition to a different route. Why is that? From what I understand, a dependency set on a computed property is similar to an observer, so why would it have trouble?


This is the component using the computed property:



import Ember from "ember";

export default Ember.Component.extend({
isFavorite: function() {
console.log("property");
// returns true or false
}.property("favorites", "favoriteId")
});


This is the component with an observer:



import Ember from "ember";

export default Ember.Component.extend({
isFavorite: null,

observesFavorite: function() {
console.log("observer");
// sets isFavorite to true or false
}.observes("favorites", "favoriteId")
});


Why do these two work differently? How would I be able to get the component to recognize the changes to favoriteId all of the time?





Allow Ember syntax into CKEditor

Issue: CKEditor removed Ember.js annotations.


I'm using the inline version of CKEditor with Ember.js. This post explains how to stop CKEditor filter functions: CKeditor strips <i> Tag


I implemented the following solution into the config.js file:



CKEDITOR.editorConfig = function( config ) {
}

CKEDITOR.config.allowedContent = true;


I'm now able to have empty tags with class and id in CKEditor (the tags are use with Font Awesome). However, CKEditor still remove the Ember annotation. Example: I would like to have the below tag in CKEditor:



<i class="fa fa-square-o" {{action "todoToggle"}}></i>


CKEditor still filter the tags and return:



<i class="fa fa-square-o"></i>


Question: How could I have CKEditor retains the {{action "todoToggle"}} annotation?


End goal: My goal is to allow users to click the font awesome sign and change it to another font awesome sign (from todo not complete to todo completed). The {{action "todoToggle"}} allow to create this toggling action with Ember.





How to filter items in a table with all checked variables in ember?

Im trying to filter items in a table based on checked values but I am only able to filter one of the values at a time. What should I do to filter all the checked values?


This is the JavaScript:



App = Ember.Application.create();

App.Router.map(function() {
this.resource('employees', function(){});
});

App.EmployeesRoute = Ember.Route.extend({
model: function(){
return App.EMPLOYEES;
}
});

App.EmployeesController = Ember.ArrayController.extend({

inFinance: false,
inMarketing: false,

filtered: function(){
var inFinance = this.get('inFinance');
var inMarketing = this.get('inMarketing');
var model = this.get('model');
var newModel = model;

if(inFinance){
newModel = model.filterBy('department', 'Finance');
}
if(inMarketing){
newModel = model.filterBy('department', 'Marketing');
}

return newModel;
}.property('inFinance', 'inMarketing')
});

App.EMPLOYEES=[
{
name: 'Ricky',
department: 'Finance'
},
{
name:'George',
department:'Marketing'
},
{
name:'Jonah',
department: 'Finance'
}
];


Here is the HTML:



<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="http://ift.tt/1x2iORp">
<script src="http://ift.tt/1ryZ1pe"></script>
<script src="http://ift.tt/1HQ7eLT"></script>
</head>
<body>

<script type="text/x-handlebars">
<nav class="navbar navbar-default navbar-fixed-top" sytle='padding:'>
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
{{#link-to 'index' tagName='a' classNames='navbar-brand'}}Test{{/link-to}}
</div>

<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>{{#link-to 'employees' tagName='a'}}Employees{{/link-to}}</li></li>

</ul>

</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>



<div class="container">
{{outlet}}
</div>

<nav class="navbar navbar-default navbar-fixed-bottom" sytle='padding:'>
Created by the almighty burrito. EmberJs Testing 2015
</nav>
</script>

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

<h1 style='padding:30px'>{{#link-to 'employees' tagName='a'}}Click for Employees{{/link-to}}</h3>

</script>

<script type="text/x-handlebars" data-template-name="employees">
<h3 style='padding:15px'> Filter</h3>
{{input type='checkbox' checked=inFinance}} Finance
{{input type='checkbox' checked=inMarketing}} Marketing

<h2 class="sub-header" >Employees</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>name</th>
<th>department</th>
</tr>
<tbody>
{{#each employee in filtered}}
<tr>
<td>{{employee.name}}</td>
<td>{{employee.department}}</td>
{{/each}}

</thead>
</script>





</body>
</html>


Thanks in advance! Here is the jsBin Here





Ember Save a change to an attribute

Very new to Ember, quick question please: How do I save/persist a change to an attribute? Have the following action in the controller:



actions: {

togOnField: function(){

if (this.get('onField')){
this.set('onField', false);
} else {
this.set('onField', true);
}
}

}


Looking around I've found



this.get('model').save


At the moment, using this, the attribute is immediately reverting back to its previous state. Does this mean the save is unsuccessful? Working with a Sails API and Postgres DB, both seem to be working fine.


And what are the different options for how I might save from this action? Thanks a lot.





Cannot get basic emberjs application to work on rails platform

I have a rails app that contains a StaticController with an index action:



class Private::StaticController < PrivateController

def index

end
end


routes.rb:



get 'static' => 'private/static#index'


I want to start an emberjs application in the corresponding view:



<%= javascript_include_tag 'ember_application' %>
<h1>Hello</h1>
<script type="text/x-handlebars">
<div>{{outlet}}</div>
</script>


For that I created a basic emberJS router:



PlatformUI.Router.map(function() {
this.route('test', { path: '/test' });
});

PlatformUI.Router.reopen({
rootURL: '/static/'
});


The template (in app/assets/javascripts/templates/test.handlebars) contains:



<script type="text/x-handlebars" data-template-name="test">
<h2>Something</h2>
</script>


When running the application, just the word 'Hello' is displayed on the page. The ember inspector (chrome plugin) says that emberjs is correctly loaded. Is there a problem with the routes? How can I debug this??


Gemfile:



gem 'ember-rails'
gem 'ember-source', '~> 1.9.1'




EmberJS calls to an MVC Web API result in a CORS message when authorization fails

I am using EmberJS to communicate with an MVC Web API using Auth0 for authorization. When I have a valid bearer token I can communicate and retrieve data from the Web API just fine. When the token expires the Web API returns an an expected 401 the following message is displayed in the browser console:


No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200'


The ajaxError method of the RESTAdapter is called as expected, but the jqXHR.status field is 0.



export default
DS.RESTAdapter.extend({
namespace: 'api',
host: webApiUrl,

headers: function() {
return {
"Authorization": 'Bearer ' + localStorage.getItem('userToken'),
};
}.property().volatile(),

ajaxError: function(jqXHR) {
var error = this._super(jqXHR);

if (jqXHR && jqXHR.status === 401) {
Ember.Logger.info("Not Authorized");
}

Ember.Logger.info("Error " + jqXHR.status + " calling API redirecting to login.");

}
});


Here is a sample of the response returned from the API:



HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcU291cmNlXFBheWNvckRldlxTb3VyY2VcSW50ZWdyYXRpb25cR2VuZXJhbFxNYWluXFBheWNvci5JbnRlZ3JhdGlvbi5PcGVyYXRpb25zXFBheWNvci5JbnRlZ3JhdGlvbi5PcGVyYXRpb25zLkFwaVxhcGlcbG9nZ2luZ0V2ZW50cw==?=
X-Powered-By: ASP.NET
Date: Fri, 30 Jan 2015 16:45:35 GMT
Content-Length: 927


I have tried XML and plan/text Content-types, but the result is the same.


I don't believe this is an actual CORS issue because this problem only occurs when the API returns an error; otherwise I'm downloading and displaying the data just fine.


Does anyone know what the issue might be?


Thanks in advance.





Ember.js get 2 nested models in one route in asynchronous way

I have 2 calls to server, which proceed a long time (10-20 seconds). I need update information on page after first request (doesn't matters which) was finished. After second request finished - i need also update part of page.


How can be realised, because I've tried realise which Promises



App.IndexRoute = Ember.Route.extend({
model: function(){
return Ember.$.getJSON('url').then(firstMethod).then(secondMethod)
}
})


but it doesn't work, because secondMethod will be executed after firstMethod will be finished.


Also I tried use this code:



App.IndexRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
first_data: Ember.$.getJSON('url1'),
second_data: Ember.$.getJSON('url2')
});
}
});


But I have the same trouble - data will be return after 2 calls will be finished.


How run asynchronously these 2 requests and do independent update part of data on page ?





Ember - Get Value From Ember Data Array

I am trying to loop over some objects in Ember in a controller, and return an array of their name attributes. I am however confused with what Ember is returning from the findAll function.


In a controller, I have the following function -



possibleGenres: function() {
var genres = this.store.findAll('genre');
var genreNames = genres.map(function(item, index, enumerable){
return item.get('name');
});
return genreNames;
}.property(),


Logging genres.get('length') gives me 0.


I have proven that there are genres available in the findAll function, as when returning the returned genres from just the findAll function, they are displayed in the template.


Am I misunderstanding something crucial about Ember controllers here?


As ever, any help is much appreciated.





classNameBindings not working

In a component I have three properties defined in my classNameBindings:



classNames: ['ui-selectize'],
classNameBindings: [ 'touchDevice', 'fingerFriendly', 'selected:selected:not-selected' ]


What I'd expect is that if at run-time the properties 'fingerFriendly' or 'touchDevice' were true that the classnames 'finger-friendly' and 'touch-device' would be added respectfully. That is almost happening but I'm getting some pretty odd behaviour. Also annoying is that this DID used to work but I can't figure out what is now interfering.


So in a situation where both touchDevice and fingerFriendly are true I can look at the inspector and see the following:


correctly associated to binding


The above looks right but if I look at the classNames property I have:


touch-device is included?


I'm a little surprised that touch-device is showing up here considering it's not a statically bound property. However, what surprises me the most is that if it is included than surely finger-friendly should be included too, right?


For actual code you can find it all here:


http://ift.tt/1JSYXIh





Ember.js: Transition somewhere else if a model exists

I want to implement logic that goes something like this:


If an value exists in storage, redirect here, else redirect there.


I'm doing it something like this:



App.IndexRoute = Ember.Route.extend({
beforeModel: function () {
var context = this;
this.store.find("thing").then(function (things) {
var thing = things.get("firstObject");
if(thing) {
context.transitionTo("some.where");
} else {
context.transitionTo("somewhere.else");
}
});
}
});


I have a feeling I am not doing it right. What is the best way to do this?


Thanks





jeudi 29 janvier 2015

Ember.js - Error while processing route if URL hit directly

I keep getting the following error from the route handler for a single object (user). If I click the link to view/show a single object (user) it works fine, but when I refresh the page at this route's url I keep getting this error.


URL that causes the error when visiting directly:



/users/:user_id


Error message in console:



Error while processing route: users.show Assertion Failed: Expected an
object as `data` in a call to `push`/`update` for ember-app@model:user:,
but was undefined Error: Assertion Failed: Expected an object as `data`
in a call to `push`/`update` for ember-app@model:user: , but was undefined


app/router.js



Router.map(function() {
this.resource('users', function() {
this.route('show', { path: '/:user_id' });
});
});


app/routes/users/show.js



export default Ember.Route.extend({
model: function(params) {
console.log('show route model hook'); //Hook firing on refresh
return this.store.find('user', params.user_id);
}
});


I am using Ember 1.8.1 and Ember-Data 1.0.0-beta.12. Any help will be greatly appreciated!





Ember - Can't access injected object in controller

I have an initializer for my Ember application and I've registered/injected a currentUser object into all of my controllers and routes. The initializer seems to be working, because I was able to access the currentUser in my Application Route. However, when I tried to access the currentUser object in an ObjectController, I get the following error:


Uncaught TypeError: undefined is not a function


Here's the initializer for the Ember app:



Ember.Application.initializer({
name: 'currentUserLoader',

initialize: function(container, application) {

application.deferReadiness();

Ember.$.ajax('http://localhost:5000', {
type: 'GET',
dataType: 'json',
success: function(data) {
var user = Ember.Object.create().setProperties(data[0]);

container.register('user:current', user, {instantiate: false, singleton: true});

container.injection('route', 'currentUser', 'user:current');
container.injection('controller', 'currentUser', 'user:current');

application.advanceReadiness();
},
error: function(err) {
console.log(err);
}
});

}
});


Here's the ApplicationRoute (and this is working correctly - I'm able to access currentUser in my Handlebar templates):



App.ApplicationRoute = Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
currentUser: this.get('currentUser')
});
}
});


Here's my ObjectController (and here, it isn't working and throwing an error instead. NOTE: I know this Controller looks pointless right now, but this is more of a proof of concept for the injection, because we can't seem to get the injection working at all):



App.ConnectController = Ember.ObjectController.extend({
currentUser: this.get('currentUser'), // throws an undefined error
});


What exactly am I doing wrong here? Is it an issue with the reference of this? Or is there something wrong with my initializer setup?


Thanks in advance!





Error in connection establishment: net::ERR_CONNECTION_REFUSED

I'm creating live chat application using laravel + emberJS. I follow the tutorials in the website. But when I comes to the end, I got connection establishment error on my port. Currently I'm running localhost from XAMPP, open with google chrome. I'm completely newbie to EmberJS, I don't know how they actually run the server. All I knew about my problem is my port is not match with the browser I surf.


Here's the tutorials I followed. Their source codes also get the same errors.





Ember - after saving model, how to get id in success callback from promise

Simple scenario in Ember-1.9.2, Ember-Data 1.0.0-beta.14.1:



model.save().then(function(savedModel){
debugger
self.transitionToRoute('model', savedModel);
}).catch(failure);

function failure(reason) {
this.set('showError', true);
}


Why can't I get the id of the saved model in the success callback (where the debugger statement is) ? It does transition successfully, but with a null id in the route. This then causes problems if you want to edit the newly created model, after transitioning.


Have also tried reloading the savedModel in the callback, which is not actually possible without the model's id. It seems as though the id isn't available until the Store is reloaded on the synchronous page refresh, updating it with the server and the server's id for the model. How is this possible to update the store within the callback?





Ember Simple Auth on Firefox: authentication throws Error

I am extending Ember Simple Auth's base authentication class to allow authentication with Google. So far, it works on Safari 8 and Chrome 41 (both on Yosemite) with no errors. However, on Firefox 35, it throws an Error that does not occur on the other browsers. Here is my Google authenticator class:



App.GoogleAuthenticator = SimpleAuth.Authenticators.Base.extend({
// constants for Google API
GAPI_CLIENT_ID: '140682596441-gqjefmvll1rishgo9235sjrlkle4gvqp.apps.googleusercontent.com',
GAPI_SCOPE: ['email'],
GAPI_TOKEN_VERIFICATION_ENDPOINT: 'http://ift.tt/1fx4kzd',

// method for scheduleing a single token refresh
// time in milliseconds
scheduleSingleTokenRefresh: function(time) {
var self = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.run.later(self, function() {
gapi.auth.authorize({
client_id: self.GAPI_CLIENT_ID,
scope: self.GAPI_SCOPE,
immediate: true
}, function(data) {
if (data && !data.error) {
resolve(data);
} else {
reject((data || {}).error);
}
});
}, time);
});
},
// WIP: recursive method that reschedules another token refresh after the previous scheduled one was fulfilled
// usage: scheduleTokenRefreshes(time until token should refresh for the first time, time between subsequent refreshes)
// usage: scheduleTokenRefreshes(time between refreshes)
scheduleTokenRefreshes: function(time1, time2) {
var self = this;
// if there is a time2, schedule a single refresh, wait for it to be fulfilled, then call myself to schedule again
if (!Ember.isEmpty(time2)) {
self.scheduleSingleTokenRefresh(time1)
.then(function() {
self.scheduleTokenRefreshes(time2);
});
// if there isn't a time2, simply schedule a single refresh, then call myself to schedule again
} else {
self.scheduleSingleTokenRefresh(time1)
.then(function() {
self.scheduleTokenRefreshes(time1);
});
}
},

// method that restores the session on reload
restore: function(data) {
var self = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
console.log(data);
if (Ember.isEmpty(data.access_token)) {
reject();
return;
}
// schedule a refresh 15 minutes before it expires or immediately if it expires in < 15
var timeNow = Math.floor(Date.now() / 1000);
var expiresAt = +data.expires_at;
var timeDifference = expiresAt - timeNow;
var schedulingDelay = Math.floor(timeDifference - 15 * 60);
schedulingDelay = schedulingDelay < 0 ? 0 : schedulingDelay;
self.scheduleTokenRefreshes(schedulingDelay * 1000, 45 * 60);
resolve(data);
});
},
// method that authenticates
authenticate: function() {
var self = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
gapi.auth.authorize({
client_id: self.GAPI_CLIENT_ID,
scope: self.GAPI_SCOPE
}, function(data) {
if (data && !data.error) {
// schedule a refresh in 45 minutes
var schedulingDelay = 45 * 60;
self.scheduleTokenRefreshes(schedulingDelay * 1000);
resolve(data);
} else {
reject((data || {}).error);
}
});
});
},
// method that logs the user out and revokes the token
invalidate: function(data) {
var self = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// send a GET request to revoke the token
Ember.$.ajax({
type: 'GET',
url: 'http://ift.tt/1j4gPSy' + self.get('session.access_token'),
contentType: 'application/json',
dataType: 'jsonp'
})
.done(function(successData) {
resolve(successData);
})
.fail(function(error) {
reject(error);
});
});
}
});


When the popup window closes after a successful login on Google's end, this error appears on Firefox's console:



Error: Assertion Failed: Error: Permission denied to access property 'toJSON' ember.js:13749
"__exports__.default<.persist@http://ift.tt/1vbYJsE
__exports__.default<.updateStore@http://ift.tt/1JQxoPB
__exports__.default<.setup@http://ift.tt/1vbYMos
__exports__.default<.authenticate/</<@http://ift.tt/1JQxoPG
tryCatch@http://ift.tt/1vbYMEL
invokeCallback@http://ift.tt/1JQxoPP
publish@http://ift.tt/1JQxoPR
@http://ift.tt/1JQxp65
Queue.prototype.invoke@http://ift.tt/1vbYJsM
Queue.prototype.flush@http://ift.tt/1JQxmHI
DeferredActionQueues.prototype.flush@http://ift.tt/1vbYJJ2
Backburner.prototype.end@http://ift.tt/1vbYMEZ
createAutorun/backburner._autorun<@http://ift.tt/1JQxmY0
" ember.js:29488


The most confounding thing is that this only appears on Firefox. Is it a bug in Ember Simple Auth or Ember? How do I fix it?





Assigning model to deeply nested view in Ember.js

I have a template that has a nested view. The nested view in turn has its own nested view. The views should all be rendered under the same route and use their own specific models. The browse template does not have an associated model.


The templates look like this:



<script type="text/x-handlebars" data-template-name="browse">
{{render "category" category}}
</script>

<script type="text/x-handlebars" data-template-name="category">
{{render "sort" sort}}
</script>

<script type="text/x-handlebars" data-template-name="sort">
<ul>
{{#each m in model}}
<li>{{m.sortType}}</li>
{{/each}}
</ul>
</script>


I'm returning all the models I need under the browse route:



App.BrowseRoute = Ember.Route.extend({
model: function () {
var store = this.store;
return new Em.RSVP.Promise(function (resolve, reject) {
new Em.RSVP.hash({
category: store.find('category'),
sort: store.find('sort')
}).then(function (results) {
resolve({
category: results.category,
sort: results.sort
});
});
});
}
});


I have no problem attaching the category model to the category template this way, but I'm unable to attach the sort model to the sort template. The sort model data is being returned, I just cannot figure out how to associate it with the sort template. Is it because the sort template is nested two levels deep?


Thanks!





Ember.js - Index route vs. "top-level" resource route?

When creating a "standard" crud resource in Ember.js, what is the difference between the index route and the "main" route?


For example, a users resource:



// app.router.js

Router.map(function() {
this.resource('users', function() {
this.route('new);
this.route('show', { path: '/:user_id'});
this.route('edit', { path: '/:user_id/edit'});
});
});


Which route should contain the following "main" model hook?



// app/routes/users/index.js OR app/routes/users.js?

export default Ember.Route.extend({
model: function() {
return this.store.find('user');
}
});


In other words, should I use the UsersRoute or the UsersIndexRoute? I find this very confusing. Any help is greatly appreciated.





Handlebars select and pass jquery contains by condition

he its abit complicated qustion...


i am useing Handlebars.registerHelper in a app and i have a problem my hbs is divided to two


hbs:



{{#if isFirstPlace}}
<div id="main">
<h1><a>{{n}}</a><a>{{name}}</a></h1>
<a>{{img}}</a>
</div>
{{else}}
</div>
<a><a id="place">{{n}}.</a><a id="img">{{img}}</a><a id="name">
{{name}} </a></a>
{{/if}}


so i need help with the function... the page is rendring and display result in ul-il div and i need to search if inside #n is there text like "1" and get it parent so i get this code:



$("[id=place]:contains('1')").parent();


so i need the function to select the element and pass it to the top option on the Handlebars registerHelper {{#if isFirstPlace}}. so i wil get a difrent strecture for the specific element and evryting else need to stay in the bottom page the {{else}}.


i have try to append() the html and prependTo(#div) but i cant pass the {{name}} {{n}} {{img}} tag inside append. i have try evryting i am lost can anaybody help me? thanks!





How to implement bing maps api in ember-cli using a component?

I successfully implemented bing maps api in my ember-cli app but everything is in the index.html file, so what I would like to do is implement bing maps in a component to be able to change the longitude and latitude variables with values I get from a fixture or json. How would I be able to do this?





Ember query params for nested routes

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?





handlebars "include" "partial" ember CLI

I would like to abstract out pieces of html in an ember project.


For example... keep the <head> in a different file and "include" it in index.hbs or something. (think php <?php include('something'); ?>)


The naming conventions in ember CLI are a little foreign so far - and I'm not finding what I thought would be pretty standard...


My guess would have been `{{#include 'head.hbs'}}' or something


There has got to be a convention for this... But I think I'm using the wrong search terms.


Thanks.





View not recognizing id change after action is triggered

In my app, I have a model called projects, and another called users. In the user model, it has an array that contains the ids of certain projects. I have a component that, when clicked, calls an action within a controller. That action simply adds or removes a project id from that array in the user's model. However, if I click on the component, then switch to another project's show page, Ember doesn't recognize that the project's id changed. It recognizes the rest of the project's properties, except for its id. Any idea why this may be the case?


In the component:



click: function() {
this.toggleProperty('isFavorite');
this.sendAction('action', this.get('projectId'), this.get('isFavorite'));
}


The action in the controller:



updateFavorites: function(id, isSelected) {
var user = this.get('currentUser');

user.then(function(user) {
var favorites = user.get('favorites');

if (isSelected) {
favorites.pushObject(id);
} else {
favorites.removeObject(id);
}
user.set('favorites', favorites);

user.save();
});
}


Note that it switches views normally if the user simply switches from one project show page to another. It's only when they click on the component that it stops working properly.


Any ideas? Thoughts?





Transition to a route mantaining the previous content in ember

I've a generic route /login that displays the login form inside a modal. Now I want the content behind to remain the same of the previous url.


How do you go about this? Thank you





ember need to refresh browser to get the model data

I follow the ember guide and with a little modification to show the post data. I defined a posts route which will generate links and a post route with dynamic segment to show the detail. however, if I click the link '/posts/1', it navigates to the post route with id. however, I do not see the post detail unless I refresh the browser. does anyone knows why? and can anyone explain what the route serialize hook does? I do not understand the explanation from the ember guide.


Handlebars



<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>

{{outlet}}
</script>

<script type="text/x-handlebars" id="posts">
<ul>
{{#each post in model}}
<li>{{#link-to 'post' post}}{{post.name}}{{/link-to}}</li>
{{/each}}
</ul>
</script>

<script type="text/x-handlebars" id="post">
<ul>
{{#each post in model}}
<h1>{{ post.name }} - {{ post.age }}</h1>
{{/each}}
</ul>
</script>


Ember Code



App = Ember.Application.create();

App.Router.map(function() {
this.resource('posts');
this.resource('post', { path: '/posts/:post_id' });
});

App.PostsRoute = Ember.Route.extend({
model: function () {
return [{
id: 1,
name: 'Andy',
age: 18
}, {
id: 2,
name: 'Tom',
age: 14
}, {
id: 3,
name: 'John',
age: 10
}];
}
});

App.PostRoute = Ember.Route.extend({
model: function (params) {
var obj = [{
id: 1,
name: 'Andy',
age: 18
}, {
id: 2,
name: 'Tom',
age: 14
}, {
id: 3,
name: 'John',
age: 10
}];
return obj.filter(function (item) {
return item.id === parseInt(params.post_id);
});
},
serialize: function(model) {
// this will make the URL `/posts/12` WTH is this mean????
return { post_id: model.id };
}
});




Why doesn't the newly added item render in the template?

So far my groupedItems is rendered properly in the template. But when I click on the add to cart link, which triggers the addToCart action. The template does not render the new item... I have to manually refresh the page to see it.


I check Ember Inspector, Data tab. The newly added item was appended to the list. So, if reflects in the data store, shouldn't it reflect/render in the template as well?


If I change my model hook in the routes to items: this.store.find('item'), instead of items: this.store.find('item', { status: 'queued' }). Everything works...


Any pointers?



// Routes
import Ember from 'ember';

export default Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
// items: this.store.find('item'),
// items: this.store.find('item').filterBy('status', 'queued'),
items: this.store.find('item', { status: 'queued' }),
// products: this.store.find('product', { status: 'available' })
});
},

// You can use model.items to get items, etc
// Since the model is a plain object you can just use setProperties
// http://ift.tt/1hAAP0e
setupController: function(controller, model) {
// model.reload;
controller.setProperties(model);
},

actions: {
addToCart: function(product) {
var _this = this;

var item = _this.store.createRecord('item');
item.set('product', product);

item.save().then(function() {
// _this.transitionTo(fromRoute);
});
}
}
});

// Controller
import Ember from 'ember';

export default Ember.Controller.extend({
groupedItems: function () {
var result = [];

this.get('items').forEach(function(item) {
// this.get('items').filterBy('status', 'queued').forEach(function(item) {
var hasProductId = result.findBy('productId', item.get('product.id'));

if(!hasProductId) {
result.pushObject(Ember.Object.create({
productId: item.get('product.id'),
product: item.get('product'),
item: item,
numberOfProducts: 0,
subtotalInCents: 0
}));
}

var productFromResult = result.findBy('productId', item.get('product.id'));

productFromResult.set('numberOfProducts', productFromResult.get('numberOfProducts') + 1);

item.get('product').then(function(product){
productFromResult.set('subtotalInCents', productFromResult.get('subtotalInCents') + product.get('amountInCents'));
});
});

return result;
}.property('items.@each')
});

// Template / hbs
<ul>
{{#each groupedItems}}
<li>
<a href="#" {{action "addToCart" product}}>Add</a>
/ <a href="#" {{action "removeFromCart" item 'index'}}>Remove</a>
{{numberOfProducts}} {{product.name}} P{{cents-to-pesos product.amountInCents}} / each
</li>
{{/each}}
</ul>




Ember-CLI Application + Working with Ember-CLI Addon

So I have this Ember-CLI Application that I am working on that has a shared resource Ember-CLI Addon that it uses. I am developing on both of them at the same time.


I was wondering if there was any way to setup the Application to auto reload when changes are made the the Addon. They are linked up via "npm link." It would be awesome if I can develop on the Addon and instantly see the changes within the Application without having to stop/restart the server.


Thanks!





Converting retrieved Ember Data records into plain javascript objects

I have a model, in the route I would like to query the store, convert the results to pure javascript json objects. How can I achieve this? Bellow the route:



myApp.EunitsRoute = Ember.Route.extend({
model: function() {
return this.store.find('unit');
// return this results as pure javascript objects
},
setupController: function(controller, model) {
this._super(controller, model);
controller.set('units', model);
},




Ember JS Environment.js not updating in Chrome Extension after deployment

I have an Ember App.


I am not sure if it is related to ember-cli-chrome add-on. I don't think so.


I was successful in deploying the chrome extension on local machine. I could also see the popup loading etc.


I am printing my environment.js "config" just to see the values, and I notice that these values are not updated based on my code base. If I run the same code in normal browser instance, it works fine.


I also notice that these environment.js contents are quite old (I had deployed the extension few days back) and seems like these values are coming from there - somehow!!! I uninstalled chrome and installed it back - no luck.


What could be happening?


Thanks





Ember.js: HtmlBars and the Handlebars.compile command

I get the following error when running my app: Uncaught Error: Cannot call `compile` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `compile`.


It is related to this piece of code: var CarouselView = Ember.View.extend({ template: Ember.Handlebars.compile('{{view view.itemsView}}'), elementId: 'carousel', contentBinding: 'content', ...


There is already an issue related about this problem on ember.js github: http://ift.tt/1COSVXa


However I added ember-template-compiler to my package.json and got the same error again.


I did: npm install --save-dev ember-template-compiler


Here are my package.json devDependencies: "ember-cli": "0.1.10", "ember-cli-app-version": "0.3.0", "ember-cli-content-security-policy": "0.3.0", "ember-cli-dependency-checker": "0.0.7", "ember-cli-htmlbars": "^0.6.0", "ember-cli-ic-ajax": "0.1.1", "ember-cli-inject-live-reload": "^1.3.0", "ember-cli-qunit": "0.3.0", "ember-cli-simple-auth": "^0.7.2", "ember-cli-simple-auth-cookie-store": "^0.7.2", "ember-cli-simple-auth-oauth2": "^0.7.2", "ember-cli-uglify": "1.0.1", "ember-data": "1.0.0-beta.12", "ember-export-application-global": "^1.0.0", "ember-template-compiler": "^1.8.0", "express": "^4.8.5", "glob": "^4.0.5"


Reference: the ember-template-compiler github page


Anyone has experience with HtmlBars and the compile command?





Using browsers navigator results in JShint error

I'm using the globally available navigator object that the browser exposes in an Ember-CLI project (aka, with ES6 syntax) and I'd like to avoid getting errors when referencing this valid global object.


I saw this suggestion: Ember CLI - Error when using moment.js in route and tried added ['navigator'] to the predef definition in the .jshintrc file. Didn't seem to have any impact. I also then put the following into the JS file itself:



/* global navigator: false */


That worked but I still feel the .jshintrc alternative would be nice. Is there a way to achieve this? Why didn't my attempt have the desired results in the same way that the momentjs example did?





ember-cli disable file versioning in production build

When I run ember build --production it adds versioning to each file type. This is a problem for me as I have a compilation script that compiles the ember up then takes the file out for further processing.


How can I disable versioning of file names in production?





mercredi 28 janvier 2015

Ember claims that route that doesn't exist is rendered

I have following Route.mapping



App.Router.map(function() {
this.resource("topic", {path: "topic/:id"}, function () {
this.route("section", { path: "/section/:section_id" });
});
this.resource("topics", {path: "topics/:id"});
});


and my /templates/-folder structure is as such:



templates/
|--topic/section.hbs
|topics.hbs
|topic.hbs


In topics.hbs, I use {{link-to}} helper to link-to the correct topic.section



{{#link-to 'topic.section' section}} {{section.title}} {{/link}}


When I click the link, Ember LOG_TRANSITIONS states that I have


Transitioned into 'topics.topic.section'


That route doesn't exist though (or does it??). Nothing related to App.TopicsTopicSectionRoute never fires, but App.TopicSectionRoute does, which I use to render the template topic.section over the the topics one:



renderTemplate: function () {
this.render('topic.section', {
into: 'application',
outlet: 'main'
});
}


Which sort of works, but it causes other issues along the line. My question is, how can I make that {{link-to}}-helper enters the correct route topic.section instead of topics.topic.section? Am I missing something obvious?





Returning a Promise with computed properties

I need to get hold of a value from another ember-data model in a computed property. All my belongsTo and hasMany relations are async : true.I have access to the value, however, it is displaying as '[Object, Object]' when I know the result actually resolves to the correct value from the debugger. I think it is due to my lack of understanding about promises.



displayName : function() {
return this.get('name') + ' ('+ this.get('currentGroup') + ')'; // currentGroup is displaying as '[Object, Object]' as it is pointing to the Promise I think
}.property('name'),

currentGroup : function() {
var promise = this.get('groups').then(function(groups) { //groups is async : true

//Do a bunch of complicated logic to work out a group based
//on the effective start date

return currentGroup.get('name'); // this resolves correctly in the debugger
});

return promise;
}.property()




Embedding an EmberJS application into an existing page

How would I embed the EmberJS app in an existing app? I would like to open the EmberJS app as a modal, on top of the existing app. Two main questions 1.routing; how would I open the emberJS app without interfering with routing? Not sure if this will do the job:



App = Ember.Application.create({
rootElement: '#app'
});


2.Closing the modal window to return to existing app?


Thank you for your comments





Aloha Editor and Ember

I'm having difficulties integrating the Aloha Editor http://ift.tt/1FD9D9W to Ember.


I'm able to generate an editable area. However, I cannot make the editable text Bold.


I created this JSBin: http://ift.tt/15SKgWh


This line of code aloha.ui.command(aloha.ui.commands.bold); is compiled with no error in my app but my text do not become bold. I'm using an example straight out of Aloha getting started guide: http://ift.tt/15WgPnc. See step 2 to get explanation for the button that bold the text.


I'm thinking that I should implement the step 2 in another way to make it work with Ember. I don't now how however.


Thanks for your guidance.





Rails 4.2 + Ember => unexpected identifier

I'm following Vic Ramon's tutorial. I tried to use the latest version of Rails and Ember-source and I get the following error when visiting home page: After clicking on link next to error I get this: enter image description here How can I fix that?


I ran the following commands: rails g ember:bootstrap -n App --javascript-engine coffee rails g ember:install


I removed turbolinks. I also created home controller and an empty view for home#index. Root is set to home#index. Also created following view file:



// app/assets/javascripts/templates/application.js.emblem
h1 Hello World
outlet


Ember gems im using:



Using emblem-source 0.3.18
Using ember-data-source 1.0.0.beta.14.1
Using ember-rails 0.16.1
Using emblem-rails 0.2.2




Need a strategy for implemeningt a partial update service call without re-inventing the wheel

My backend has some cool functionality that I'm struggling with implementing. Easier to explain with an example...


Say you have an order, with order lines (defined as hasMany) and products attached that the user is currently editing and they change the price on a line. Functionally you'd want to recalculate the sales tax as an example.


My backend allows me to package-up and send this transient object (along with a list of changed fields) and will determine what needs to be altered on the object tree (without actually persisting that object yet). What it returns is a sparsely-populated object with the values that have been changed server-side.


So, if I have something like this:



{
orderid: '12345',
taxamt: 0,
lines: [
{
id: 1,
product: 'ABC',
price: 99.99
}
]
}


And then let's say, the user updates the line price. If I send this to the backend:



{
orderid: '12345',
taxamt: 0,
lines: [
{
id: 1,
product: 'ABC',
price: 89.99
}
],
changelist: ['lines.price']
}


... I'll get back something like this:



{
orderid: '12345',
taxamt: 12.00,
}


...that is, I'll get enough to uniquely identify each object and then only the properties that were updated server-side.


I've got the first half of this implemented, but handling the return is proving to be difficult. I've got it partially working but it sure feels like I'm re-implementing a ton of what ember data is already doing.


Given that the server may add or delete relationship objects and may alter any property at any level, what's a good approach that leverages the existing framework the best?





Can't get simple acceptance test to function properly

the visit will happen fine and I see the live application page in the bottom right corner but then the equal assertion never happens and basically the test is always "running" and no assertions ever get made, any guidance would be greatly appreciated, I am on ember-cli 0.1.11 and ember 1.9.1, I am testing by going localhost:4200/provider/tests where my baseUrl is set to '/provider/'



import Ember from 'ember';
import startApp from '../helpers/start-app';

var application;

module('Acceptance: Login', {
setup: function() {
application = startApp();
},
teardown: function() {
Ember.run(application, 'destroy');
}
});

test('visiting /login', function() {
visit('/login');

andThen(function() {
equal(currentPath(), 'login');
});
});


my startApp looks like this



import Ember from 'ember';
import registerAcceptanceTestHelpers from './201-created/register-acceptance-test-helpers';
import Application from '../../app';
import config from '../../config/environment';
import 'simple-auth-testing/test-helpers';

export default function startApp(attrs) {
var application;

var attributes = Ember.merge({}, config.APP);
attributes = Ember.merge(attributes, attrs); // use defaults, but you can override;

Ember.run(function() {
application = Application.create(attributes);
application.setupForTesting();
registerAcceptanceTestHelpers();
application.injectTestHelpers();
});

return application;
}




Using Redactor WYSIWYG with Ember

I'm using Redactor from http://ift.tt/Wa6JqJ with Ember. I created a Ember component:



App.RedactorEditorComponent = Ember.Component.extend({

/* --- Public API --- */
redactorText: null,
color: null,

/* --- Internal --- */
tagName: 'div',

init: function() {
this._super();
this.on("focusOut", this, this._elementValueDidChange);
this.on("change", this, this._elementValueDidChange);
this.on("paste", this, this._elementValueDidChange);
this.on("cut", this, this._elementValueDidChange);
this.on("input", this, this._elementValueDidChange);
},

_updateElementValue: function() {
var $el, comment;
comment = this.get('redactorText');
$el = this.$().context;
if ($el && comment !== $el.innerHTML) {
return $el.innerHTML = comment;
}
},

_elementValueDidChange: function() {
var $el;
$el = this.$().context;
var comment = Ember.set(this, "value", $el.innerHTML);
this.sendAction('saveRedactorText', comment);
return comment;
},

didInsertElement: function() {
this.$().redactor({
plugins: ['counter']
});
this._updateElementValue();
},

});


I create a plugin. The pluging code is strait from Redactor docs (http://ift.tt/1yOD0Gy). As per instructions, I placed the code into a counter.js file:



if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
RedactorPlugins.counter = function()
{
return {
init: function()
{
if (!this.opts.counterCallback) return;

this.$editor.on('keyup.redactor-limiter', $.proxy(function(e)
{
var words = 0, characters = 0, spaces = 0;

var html = this.code.get();

var text = html.replace(/<\/(.*?)>/gi, ' ');
text = text.replace(/<(.*?)>/gi, '');
text = text.replace(/\t/gi, '');
text = text.replace(/\n/gi, '');
text = text.replace(/\r/gi, '');
text = $.trim(text);

if (text !== '')
{
var arrWords = text.split(/\s+/);
var arrSpaces = text.match(/\s/g);

if (arrWords) words = arrWords.length;
if (arrSpaces) spaces = arrSpaces.length;

characters = text.length;

}

this.core.setCallback('counter', { words: words, characters: characters, spaces: spaces });


}, this));
}
};
};
})(jQuery);


Questions: The plugin work but I understand that this plugin create a global variable. How can I make this code more compliant with Ember methodology? I did try to put the plugin code into the Ember redactor-editor component but I could not manage to make the plugin load on line plugins: ['counter'].





Rendered templates cache in Ember app

I am working on an Ember app. The page contains a infinite scroll list of files and a details pane. When a file is selected it is supposed to show a form to modify file details in the details pane.



// router.js
this.resource('files', function () {
this.route('file', { path: '/:file_id' });
});

// templates/files.hbs
{{ #my-list-component params.. }}
list-item-content
{{ /my-list-component }}
{{outlet}} // this is for the file details


There is no template for the file though. The requirement is that form template for a file is autogenerated on the server on request.



// routes/files/file
export default Ember.Route.extend({
model: function(params) {
return this.store.find('file', params.file_id);
},
afterModel: function(file, transition) {
// make ajax call to the web service
// to get form template for the current file
return Ember.$.ajax(config.APP.API_HOST + formPath).then(function(data) {
...
Ember.TEMPLATES['files/file'] = Ember.Handlebars.compile(data);
...
}
}
});


There are only few different types of forms depending on the file type, but many files. Forms are quite big with many Ember components on them. It takes time to render them(there are also some calculations on render). Is there a nice way to cache already rendered forms? So that when a file is selected, it checks if this type of form was already rendered, gets it from cache and shows as is(binding will update data from current model)?





Ember-cli taking a long time to build after app migration

I recently migrated an ember app that I was compiling using bower to ember-cli. It had already grown pretty large, but I was running into issues with my current dev environment and ember-cli seems like the cleaner solution.


Unfortunately, after updating the files for the ember-cli interface, the build isn't working. I have left it running for 5 minutes at 100% CPU, and it reached two dots after Building.. and stopped.


I am using Sublime text, but I updated my preferences under http://ift.tt/1zBzr8Y. I added broccoli-sass using npm and ember-data.model-fragments using ember install:addon. Below is my package.json



{
"name": "frontend",
"version": "0.0.0",
"description": "Small description for frontend goes here",
"private": true,
"directories": {
"doc": "doc",
"test": "tests"
},
"scripts": {
"start": "ember server",
"build": "ember build",
"test": "ember test"
},
"repository": "",
"engines": {
"node": ">= 0.10.0"
},
"author": "",
"license": "MIT",
"devDependencies": {
"broccoli-asset-rev": "^2.0.0",
"broccoli-sass": "git://github.com/aexmachina/broccoli-sass#sources-content",
"ember-cli": "0.1.11",
"ember-cli-6to5": "^3.0.0",
"ember-cli-app-version": "0.3.0",
"ember-cli-content-security-policy": "0.3.0",
"ember-cli-dependency-checker": "0.0.7",
"ember-cli-htmlbars": "^0.6.0",
"ember-cli-ic-ajax": "0.1.1",
"ember-cli-inject-live-reload": "^1.3.0",
"ember-cli-qunit": "0.3.0",
"ember-cli-uglify": "1.0.1",
"ember-data": "1.0.0-beta.14.1",
"ember-data-model-fragments": "0.2.7",
"ember-export-application-global": "^1.0.0",
"express": "^4.8.5",
"glob": "^4.0.5"
}
}


and here is my app file tree. I'm wondering if it has something to do with all the folders I added (objects, definitions, libraries, etc).



app
├── app.js
├── components
│ ├── dual-slider.js
│ ├── scroll-arrow.js
│ ├── single-slider.js
│ └── square-div.js
├── controllers
│ ├── application.js
│ ├── authentication
│ │ ├── login.js
│ │ └── signup.js
│ ├── demos
│ │ ├── derivatives.js
│ │ ├── integrals.js
│ │ └── revolutions.js
│ ├── flash.js
│ ├── index.js
│ ├── lessons
│ │ ├── index.js
│ │ ├── new
│ │ │ ├── create-step.js
│ │ │ ├── index.js
│ │ │ └── step.js
│ │ ├── new.js
│ │ ├── show
│ │ │ ├── index.js
│ │ │ └── step.js
│ │ └── show.js
│ └── subjects
│ ├── index.js
│ └── show.js
├── definitions
│ ├── animationKeys.js
│ ├── stepArray.js
│ └── typeKeys.js
├── helpers
│ ├── focus-input.js
│ └── slider-label-input.js
├── index.html
├── initializers
│ └── session-setup.js
├── libraries
│ └── mathAnimationLibrary
│ ├── dist
│ │ ├── display-library.js
│ │ └── vendor
│ │ ├── math.js
│ │ ├── three.js
│ │ ├── trackballControls.js
│ │ └── zgentilis_bold.typeface.js
│ └── src
│ ├── DisplayLibrary.js
│ └── functions
│ ├── create2DFunction.js
│ ├── createAxis.js
│ ├── createIntegralDisplay.js
│ ├── createRotationFunction.js
│ ├── createSurface.js
│ ├── mathEnvironment.js
│ └── showDerivative.js
├── mixins
│ └── animation.js
├── models
│ ├── animation-params.js
│ ├── animation.js
│ ├── choice.js
│ ├── equation-part.js
│ ├── equation.js
│ ├── explanation.js
│ ├── instruction.js
│ ├── lesson-step-type.js
│ ├── lesson-step.js
│ ├── lesson.js
│ ├── multiple-choice.js
│ ├── special-animation-params.js
│ ├── subject.js
│ └── user.js
├── objects
│ ├── flash-queue.js
│ ├── flash.js
│ └── session.js
├── router.js
├── routes
│ ├── index.js
│ ├── lessons
│ │ ├── index.js
│ │ ├── new
│ │ │ ├── create-step.js
│ │ │ ├── index.js
│ │ │ └── step.js
│ │ ├── new.js
│ │ ├── show
│ │ │ ├── index.js
│ │ │ └── step.js
│ │ └── show.js
│ ├── logout.js
│ └── subjects
│ ├── index.js
│ └── show.js
├── serializers
│ ├── application.js
│ └── lesson.js
├── styles
│ ├── app.scss
│ ├── reset.css
│ └── sass
│ ├── authentication
│ │ └── authentication.scss
│ ├── colors.scss
│ ├── components
│ │ ├── scroll-arrow.scss
│ │ ├── slider.scss
│ │ └── square-div.scss
│ ├── helpers
│ │ └── flash.scss
│ ├── lessons
│ │ ├── multiple-choice.scss
│ │ └── show.scss
│ ├── main.scss
│ ├── mixins.scss
│ └── root
│ ├── demos.scss
│ ├── header.scss
│ └── index.scss
├── templates
│ ├── about
│ │ └── index.hbs
│ ├── application.hbs
│ ├── backend.hbs
│ ├── components
│ │ ├── dual-slider.hbs
│ │ ├── scroll-arrow.hbs
│ │ ├── single-slider.hbs
│ │ └── square-div.hbs
│ ├── demos
│ │ ├── derivatives.hbs
│ │ ├── index.hbs
│ │ ├── integrals.hbs
│ │ └── revolutions.hbs
│ ├── index.hbs
│ ├── lessons
│ │ ├── equationViewer.hbs
│ │ ├── index.hbs
│ │ ├── multipleChoice.hbs
│ │ ├── new
│ │ │ ├── createStep.hbs
│ │ │ ├── index.hbs
│ │ │ └── step.hbs
│ │ ├── new.hbs
│ │ ├── show
│ │ │ ├── index.hbs
│ │ │ └── step.hbs
│ │ └── show.hbs
│ ├── login.hbs
│ ├── shared
│ ├── signup.hbs
│ └── subjects
│ ├── index.hbs
│ └── show.hbs
└── views
├── demos
│ ├── derivatives.js
│ ├── integrals.js
│ └── revolutions.js
├── flash.js
└── lessons
├── equationViewer.js
└── multipleChoice.js


I appreciate any insight that you might have.





Selecting an MVC Framework (Javascript - Front End) - Backbone, Angular, Ember

I've spent the last couple days researching different arguments for and against different MVC frameworks but what's become very apparent is that there's absolutely no correct answer to this question as it's heavily dependent on a number of different factors specific to the underlying project.


The advice I am repeatedly coming across is select a framework on the following points: Ease of use, productivity, testability, community, documentation


While that's all well and good advice, I still think that there are a few more things to consider specific to the actual code-base you'll be working on.


That being said, hypothetically if you were to arrive at work one day and asked to select the "best" Javascript MVC framework for your code base to handle the entire front end of an existing product (keeping in mind that there is a current codebase and you'd want the framework to be able to handle the "transition" period as you shifted to the new framework over time), what are the factors/questions you believe would be necessary to consider to make a well informed decision? These can be factors/considerations/questions about the MVC frameworks themselves AND/OR the current code base / technologies current in use (ie. Ruby backend, other libraries currently in use, product functionality, etc).


Scalability and performance are extremely important as this product would have a fairly large volume of users.


Just due to stability and maturity of certain frameworks alone I've factored down realistic choices to Angular, Backbone + Marionette and Ember (although this one is still up in the air). Each one is a different beast by its own right and functions very differently, hence the need for my original question on what factors and questions would you ask to figure out which is the "ideal" (I use that word very loosely) choice?





Add node module to ember CLI app

I would like to use this Node.js module http://ift.tt/15Je4Vp in my Ember-CLI application.


How do I make it available to the Ember application?


I tried it by adding this to the Brocfile.js



app.import('node_modules/remarkable-regexp/index.js');


but it fails like this:



Path or pattern "node_modules/remarkable-regexp/index.js" did not match any files






Disable hash (#) routing on Ember for hash property on elements such as nav-tabs

Is it possible to disable the router for certain # hash-based routing for elements such as the nav-tabs (or any other hash anchors)



<ul class="nav nav-tabs" role="tablist">
<li><a href="#tab-one" role="tab" data-toggle="tab">First Tab</a></li>

...

<div class="tab-content">
<div class="tab-pane" id="tab-one">


Currently that is picked up by Embers router.


Perhaps some global replace could be used for Ember hash but that seems incredibly poor.



if(window.location.hash){
window.location.href = window.location.href.replace(/#.*/,'');
}




Packaging an object for a model with a dynamic route is undefined — why?

Playing around with with EmberJS, and I'm trying to understand some behaviour with routes right now.


I'm building a test app with the intention of hooking into the Rdio API and displaying albums/songs for various artists.


Right now, there are only two views: The Index (a listing of all available albums), and an individual Album view.


The dynamic route is defined like so:



App.Router.map(function() {
this.route("album", { path: "/album/:key" });
});


And given a fixture that looks like this...



App.ALBUMS = {
"status": "ok",
"result": [
{
"key": "a5337866",
"icon": "http://ift.tt/18vcQPe",
"artist": "The Decemberists",
},
{
"key": "a5229271",
"icon": "http://ift.tt/18vcOam",
"artist": "Nicki Minaj",
},
};


...the index works just fine:



App.IndexRoute = Ember.Route.extend({
model: function() {
return {albums:App.ALBUMS.result }
}
});


(I've intentionally packaged App.ALBUMS.result in an object so that I can pack more information into it later.)


Lyrically Index Page


However, when I get to the Album view, I get a problem:



App.AlbumRoute = Ember.Route.extend({
model: function(params){
console.log(params);
console.log(App.ALBUMS.result.findBy('key',params.key)); //Logs object just fine
return App.ALBUMS.result.findBy('key',params.key); //ERROR
}
});


Packaging that return value (which should already be an object) in a second object or array though, and it works.



// THIS WORKS!:
return [App.ALBUMS.result.findBy('key',params.key)];
// THIS AlSO WORKS!:
return {album: App.ALBUMS.result.findBy('key',params.key)};


Why?


The error itself is rather unhelpful:



Error while processing route: album undefined is not a function TypeError: undefined is not a function
at EmberObject.extend._setupArrangedContent (http://ift.tt/18vcOqA)
at null._arrangedContentDidChange (http://ift.tt/1yykQUE)
at applyStr (http://ift.tt/18vcQPi)
at sendEvent (http://ift.tt/1yykRYQ)
at notifyObservers (http://ift.tt/18vcQPo)
at propertyDidChange (http://ift.tt/1yykQUL)
at iterDeps (http://ift.tt/18vcQPq)
at dependentKeysDidChange (http://ift.tt/1yykSfa)
at propertyDidChange (http://ift.tt/18vcOqL)
at iterDeps (http://ift.tt/18vcQPq)