samedi 28 février 2015

uncaught exception in webIDE when running firefox os simulator

I was running ffos 2.0 simulator in webIDE and testing world-clock example as given in http://ift.tt/1aFegb6 on windows 7 machine. This throws uncaught exception [object object] line no: unknown and white screen in simulator. In firefox browser 36, it runs fine without reporting any error in firebug.


Somebody, please help!





How to deal with github-style URL with Emberjs?

Take this url http://ift.tt/1AIhvIj as an example, the part after /tree(master/casserver-core/src/main/java/org in this url) could contain any number of segments.


Is it possible to deal with these dynamic segments with one Route, or any other suggestions?





Ember this.store with deep path /:type/:id

In my application I have a profile page, each profile have an :type and :id, both are needed for queries.


route.js:



this.route('profile', {path: '/profiles/:type/:id'});


In my route I wish search for the current accessed profile,:



export default Ember.Route.extend({
model(params) {
var network = params.network;
var id = params.id;
var profile = this.store.find('profile', network, id});
}
});


and an model profile:



var attr = DS.attr;

export default DS.Model.extend({
name: attr('string'),
description: attr('string'),
});


MOCK like model: // /:network/:id res.send({ 'profiles': [{ //... }] });


But in my this.store.find('profile', network, id}); Ember throws: "Error while processing route: profile Assertion Failed: metaForProperty() could not find a computed property with key '0'. Error: Assertion Failed: metaForProperty() could not find a computed property with key '0'"


is this because I'm using RESTAdapter? ./adapters/application


How can I resolve it ?





How to run app built by ember cli under not node.js server (django in my case)?

This is my first time trying to create an ember.js with ember-cli and I run into a little problem.


I followed this tutorial http://ift.tt/1qt2JSQ and when I launch the server (node.js by 'ember server' from terminal) I got Welcome to ember.js page. So I guess it works.


But if I get this right, ember.js should be able to run without any server, just inside a browser no? So how to 'export' this app and use it as static template in browser (my backend is developed in django, so I basiclly want the ember app will be a template).


I tried to use dist/index.html as template but when I open the page in browser, there is no welcome to ember.js and js console shows this errors:



vendor.js:1 Uncaught SyntaxError: Unexpected token < frontend.js:1


Uncaught SyntaxError: Unexpected token <


127.0.0.1/:21 Resource interpreted as Script but transferred with MIME type text/html: "http://ift.tt/1K1j3U4".


127.0.0.1/:13 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://ift.tt/1zsHbnv".


127.0.0.1/:22 Resource interpreted as Script but transferred with MIME type text/html: "http://ift.tt/1K1j1M2".


127.0.0.1/:14 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://ift.tt/1zsHa2S".






Ember-CLI app deployed to heroku with environment=production loses global app namespace

My app name is App and I have access to the App namespace when environment=developing. Only problem is that issues arise when I use the production version by running (ember server --environment=production, then I no longer have access to the App namespace as it is undefined.



Error while processing route: coming-soon Beerme is not defined ReferenceError: Beerme is not defined


Is this a security measure ember-cli takes? How can I override this?





Ember CLI / resource / wp-api slug

For practice, and because the word 'post' is too confusing these days, I'm creating a resource called thought(s) - I'm getting some wp-json with the WordPress API (so the 'posts' are 'thoughts') - I'm setting the path to /wordpress with the intention of getting urls like this: http:/site.com/wordpress/thought-slug - I'm nesting the resources, so that the path is relative to the parent.


What I don't understand is how I know what the 'dynamic' : part is - and how I choose it. In the tutorials I've found, it's always post_id or something, but the specifics aren't explained.


I have a thoughts.js with {{#link-to 'thought'}}go{{/link-to}}, and a thought.js - and I've done this in the tutorials, so I'm just missing an understanding of how that dynamic part works...


Help :/




router.js



Router.map(function() {

// WordPress
this.resource('thoughts', {
path: '/wordpress' },
function() {
this.resource('thought', {
path: ':thought???'
});
}
);

});

export default Router;




Workflow for Ember CLI, broccoli, beanstalk

I currently build projects with Ember CLI. This uses broccoli as the build tool / asset pipeline etc. So, my version control and deployment is through beanstalk / and I use gitTower much of the time to deal with git.


My issue is with tracking built files. So, my repo is dealing with new unique sheriff_djfklajfksajfiosjafioasfsa.css files and js files each time I commit.


I just keep deploying it live with beanstalk, but it seems like I shouldn't be committing those files, and maybe they should be generated locally, but not tracked in the repo - AND THEN... built on the server? or somehow passing them through but not committing them?


What's the new magic?





How do I unit test a helper that uses a service?

I'm trying to unit test a helper that uses a service.


This is how I inject the service:



export function initialize(container, application) {
application.inject('view', 'foobarService', 'service:foobar');
}


The helper:



export function someHelper(input) {
return this.foobarService.doSomeProcessing(input);
}

export default Ember.Handlebars.makeBoundHelper(someHelper);


Everything works until here.


The unit test doesn't know about the service and fails. I tried to:



test('it works', function(assert) {

var mockView = {
foobarService: {
doSomeProcessing: function(data) {
return "mock result";
}
}
};

// didn't work
var result = someHelper.call(mockView, 42);

assert.ok(result);
});




Convert Emberjs recordArray model to JSON

Disclaimer: I am new to Ember.


With that being said, I am trying to convert an Ember recordArray to a JSON string so that I can send it to my server for processing.


I have the following Ember model:



Loads.Load = DS.Model.extend({
pickupStartTime: DS.attr('string'),
pickupEndTime: DS.attr('string'),
pickupLocation: DS.attr('string'),
pickupGeocode: DS.attr('string'),
pickupWeight: DS.attr('number'),
pickupTicket: DS.attr('string'),
dropoffStartTime: DS.attr('string'),
dropoffEndTime: DS.attr('string'),
dropoffLocation: DS.attr('string'),
dropoffGeocode: DS.attr('string'),
dropoffWeight: DS.attr('number'),
dropoffTicket: DS.attr('string'),
commodity: DS.attr('string'),
isCompleted: DS.attr('boolean'),
shortPickupStartTime: function(){
var time = this.get('pickupStartTime');
if(time){
var split = time.split(" ");
return split[4];
}else{
return " ";
}
}.property('pickupStartTime'),
shortPickupEndTime: function(){
var time = this.get('pickupEndTime');
if(time){
var split = time.split(" ");
return split[4];
}else{
return " ";
}
}.property('pickupEndTime'),
shortDropoffStartTime:function(){
var time = this.get('dropoffStartTime');
if(time){
var split = time.split(" ");
return split[4];
}else{
return " ";
}
}.property('dropoffStartTime'),
shortDropoffEndTime: function(){
var time = this.get('dropoffEndTime');
if(time){
var split = time.split(" ");
return split[4];
}else{
return " ";
}
}.property('dropoffEndTime')
});


I have the following action in my controller:



var self = this;

Ember.RSVP.hash({
//loads is an array of records
loads: this.store.find('load')
}).then(function (data) {
$.ajax({
type: "POST",
data: { Loads: JSON.stringify(data.loads) },
url: "api/buildexcelsheet",
contentType: "application/json",
success: function (message) {
self.set('uri', message);
}
});
});


When I run this action from the controller I get the following error:



Uncaught Error: Assertion Failed: TypeError: Converting circular structure to JSON


Since I'm new to Ember, I'm unsure as to what I'm doing wrong.


Any help would be greatly appreciated.


Thanks!





Testing: how to assert between two sequential promises/run.laters? How to skip `run.later` waiting in tests?

Here's a simple component:



App.FooBarComponent = Ember.Component.extend({
tagName: "button",
status: "Ready",
revertStatusPeriodMs: 2000,

click: function() {
this.set('status', 'Pending');

// A fake ajax
this.run()
.then( function() {
this.updateStatus('Finished');
}.bind(this))
.catch( function() {
this.updateStatus('Error');
}.bind(this));
},

run: function() {
return new Ember.RSVP.Promise( function(resolve) {
Ember.run.later( function() {
resolve();
}, 500);
});
},

updateStatus: function(statusText) {
this.set('status', statusText);

var periodMs = this.get('revertStatusPeriodMs') || 1000;

Ember.run.later( function() {
this.set('status', 'Ready');
}.bind(this), 500);
}
});


It does a simple thing: when clicked, it displays some text. Later replaces the text with another one. Even later, it reverts the text to the initial one.


The code works fine. My problem is that i'm unable to write a test for it.



test('clicking the button should set the label', function(assert) {
expect(4);

visit('/');

assert.equal( find('button').text().trim(), 'Ready', 'Should initially be "Ready"');

andThen(function() {
click('button');
assert.equal( find('button').text().trim(), 'Pending', 'Should "Pending" right after click');
});

// This one fires too late!
andThen(function() {
assert.equal( find('button').text().trim(), 'Finished', 'Should become "Finished" after promise fulfills');
});

andThen(function() {
assert.equal( find('button').text().trim(), 'Ready', 'Should eventually return to the "Ready" state');
});
});


I have two problems:




  1. I'm unable to test the Finished state. It seems that andThen waits for all promises and run.laters to finish, while i want to test an intermediate state. How do i run an assertion between two sequential promises/run.laters?




  2. Times can be long, and tests can take forever to complete. I generally don't mind refactoring the code for better testability, but i refuse to adjust times in the app based on the environment (e. g. 2000 for dev/prod, 0 for test). Instead, i would like to use a timer mock or some other solution.


    I've tried Sinon and failed: when i mock the timer, andThen never returns. Neither of these solutions helped me.




JSBin: http://ift.tt/188EBwh (Sinon is included)





vendredi 27 février 2015

Ember communicate between view components and controllers

I have a dashboard and inside it some buttons for filter to posts.


This dashboard appear in all pages, so I a create a view dashboard with a template of same name.


to trigger filter, I have created an view filter-button:



export default Ember.View.extend(Ember.TargetActionSupport, {
tagName: 'button',
click(event) {
this._toggleComponentState();
this._dispatchAction();
},
_dispatchAction() {
this.triggerAction({
action: "filter",
target: this.get('controller'),
actionContext: this.get('context')
});
},
_toggleComponentState() {
this.$().toggleClass('active');
}
});


this action filter this sent to application controller, but I need send to an specific controller posts.index, hierarchically posts and dashboard have no connection. how can I create a communication correctly between my components?





Can't add a layout to Ember.Select

I am trying to create a custom CSS dropdown which requires me to add a wrapper class to my Select view. I've attempted to add the code by reopening Ember.Select, but the behavior is not working as intended.


In my JS, I have this defined:



Ember.Select.reopen({
layout: Ember.Handlebars.compile("<div class='select-layout'>{{yield}}</div>")
});


In my template, I have:



{{view "select" content=model}}


However, my resulting HTML is:



<select id="ember257" class="ember-view ember-select">
<option id="ember270" class="ember-view" value="red">red</option>
<option id="ember273" class="ember-view" value="yellow">yellow</option>
<option id="ember276" class="ember-view" value="blue">blue</option>
</select>


I set up a JSFiddle for this which can be found here: http://ift.tt/1wvBOsZ


If there's a trick to this, please enlighten me.





Ember-CLI Generated Acceptance Test Fails

I have a very basic Ember-CLI application running with about 75 or so QUnit assertions that all pass. When I generate an acceptance test:



ember generate acceptance-test games


Which produces:



import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../helpers/start-app';

var application;

module('Acceptance: Games', {
beforeEach: function() {
application = startApp();
},

afterEach: function() {
Ember.run(application, 'destroy');
}
});

test('visiting /games', function(assert) {
visit('/games');

andThen(function() {
assert.equal(currentPath(), 'games');
});
});


My tests then begin break on a JSHint unit test for the route:



52. JSHint - unit/routes/games: global failure (1, 0, 1)
1. Uncaught Error: Assertion Failed: calling set on destroyed object
Source: http://localhost:4200/assets/vendor.js:14407


I'm just starting with these Ember-CLI Integration tests, so perhaps there's something I'm missing? The error seems like that maybe I'm setting up something but not tearing it down properly somewhere else? Even if that's the case, I'm not sure why adding one acceptance test would produce this while without the test everything passes.


The console also shows:



WARNING: Library "App" is already registered with Ember.
ember.debug.js:3940 Uncaught Error: Assertion Failed: calling set on destroyed object


For reference, I'm on:



DEBUG: Ember : 1.10.0
DEBUG: Ember Data : 1.0.0-beta.15
DEBUG: jQuery : 1.11.2


Thanks in advance,





Reusable ember component with its own data source

I have a dropdown <select>-based component that I'd like to be able to drop into any template in the hierarchy of my ember app. This displays a list of all the Articles (the model) on the site. Whenever I use this component though, the route that I'm in needs to load the data and get passed to the template. How can I load this data once and only when the component is rendered? I've been reading this and still have yet to come up with a good solution. I'd like the component to provide the data source, but that seems to be frowned upon.


Would it be terrible to just do an ajax request in my component pre-render?





How to run bootlint over handlebars files

Is it possible to run bootlint over handlebars files? I have an ember cli-project and all my handlebars files are inside by templates folder and may be nested.


Since bootlint needs html files I have a feeling that I might need to output html files to some temp directory.


What do you recommend?





Ember 1.8.1- component link-to not working with action

I am using Ember 1.8.1. I have a component for some notifications. They use dynamic variables to determine a link-to ( I use computed properties to determine the proper route, and model to send through. This is calculating correctly.). Then within the link-to an action is defined.



{{#link-to event.routeName event.routeTarget}}
<li {{action "eventClick" event}}>
..other markup...
</li>
{{/link-to}}


Everything was working before I moved these into a component. My problem now is that while the action works, and the URL is being properly formed (on hover I can see that I have the correct URL that my link-to should be creating), when I click on the link in the UI, the action fires, but the link does not transition as it is supposed to.


I've dealt with the opposite problem before - actions within a link-to not working correctly, but never the problem this way. Is there something obvious I am missing? I've searched through the documentation and can't seem to find anything that tells me what I'm doing is wrong.


Recap: In my Ember component, why does the routing for the link-to not work, but the action within it does? Again- this all worked before making it a component, so I'm not sure what the difference is.


Thanks in advance for your help.





Ember list of checkbox on check one send rest

I have a list of checkboxes in my template:



<table>
<thead>
<tr>

<th></th>
<th>Sender</th>
<th>Title</th>

</tr>
</thead>
<tbody>

{{#each message in model.entities}}

<tr>

<td class="cell-star">
{{input type="checkbox" name=message.id tabindex=message.id class="starBox" checked=message.isStar }}

</td>
<td class="cell-broadcaster">
{{message.notification.autor.firstName}} {{message.notification.autor.lastName}}
</td>
<td class="cell-title">
{{#link-to 'notifications.details' message.notification.id}}{{message.notification.title}}{{/link-to}} {{#unless message.isRead}} (new) {{/unless}}
</td>

</tr>

{{/each}}

</tbody>
</table>


And now i want to send rest query every time when i change some of the checkbox state with id of changed checkbox. What should i write in my controller?


i have tried something like that but i cannot get data of changed checkbox:



updateStarStatus: function() {

console.log('checkbox clicked');
//here should be something like that:
//$.getJSON(apiHost + "/api/forum/star/"+id);

}.observes('model.entities.@each.isStar'),


im not using emberData. My model looks like this:



model: function() {
return $.getJSON(apiHost + "/api/forum");

},




Resolving promises on filter ember for local store only

I am creating some records locally, with the command



store.createRecord('vdpformat',{recordformat:"a",name:f.name});


Once they are created, I try to get the records which have the value of recordformat=a using the following code.



var totalvdpformats=store.all("vdpformat");
var filteredRecords=totalvdpformats.filterBy("recordformat","a");


But I get the contents of filtered records as empty as the promise doesn't get resolved.It returns an empty array when I try to console log filteredRecords.


Is there anyway to use a promise on the above?


When I try to add a promise on totalvdpformats, it tells me the function is undefined.


Please help.





Difference between using pathForType and inflector.irregular in ember

We can customize the ember pluralization in two ways;



  1. using 'pathForType' in RESTAdapter, like,





App.GroupAdapter = Ember.RESTAdapter.extend({
pathForType: function(type) {
var camelized = Ember.String.camelize(type);
return Ember.String.singularize(camelized);
}
});




  1. By using Ember.inflector.irregular() in model





Ember.inflector.irregular('group', 'group');


In both case it will make a call to 'group' instead of 'groups'. Is there any difference between both? which one to use?





Choosing Java Script Framework for Web Application

I need to design a web application which extensively is focussed on image sharing and rendering. Keeping this point in mind, Which JavaScript Framework would be best. I just have basic knowledge of Java Script Framework. Can you please suggest which Java Script framework to use ?. Thanks in advance.





How should I get the value of this input field?

I am using a subexpression at {{input value=(cents-to-dollars model.amountInCents)}}. It is using a custom helper to convert the value from cents to dollars. My API returns cents.


However in the controllers save action, console.log(this.get('model.amountInCents')); returns undefined. Am I missing something? Maybe name or valueBinding in the input helper?


If I remove the subexpression. console.log(this.get('model.amountInCents')); outputs fine.



// Routes
import Ember from 'ember';

export default Ember.Route.extend({
model: function(params) {
return this.store.find('product', params.product_id);
}
});

// Controller
export default Ember.Controller.extend({
actions: {
save: function() {
console.log(this.get('model.amountInCents')); // returns undefined
var _this = this;
var dollars = this.get('model.amountInCents');
var amountInCents = dollars / 100;

this.get('model').set('amountInCents', amountInCents);

this.get('model').save().then(function(product){
_this.transitionToRoute('admin.products.show', product);
}, function() {
// Need this promise, so we can render errors, if any, in the form
});

return false;
},
cancel: function() {
this.transitionToRoute('products.show', this.get('model'));
}
}
});

// Template
<form {{action "save" on="submit"}}>
<p>
<label>Name:
{{input value=model.name}}
</label>
</p>

<p>
<label>Amount in cents:
{{input value=(cents-to-dollars model.amountInCents)}}
</label>
</p>

<input type="submit" value="Save"/>
<button {{action "cancel"}}>Cancel</button>
</form>




Add a js variable to url path inside a function using Ember

I have a button controller that gets a 'countyId' from a ddl inside html once button is clicked. I get the countyId and need to add it to my URL just like the {{#link-to this}} does it inside App.Router.map...


My controller:



App.CresRoute = Ember.Route.extend({
model: function() {
return county;
},
actions: {
redirect: function(countyId){
alert(countyId); //For debug, knowing I have the ID
//CODE TO ADD countyId TO URL...
}
}
});


How can I do this using Ember framework?


Thanks!





Does size of the script really matter when chossing frameworks?

I know that size of the javascript file is crucial for the website success as it affects the performance.


But is the size really that important that it becomes a factor when choosing a javascript framework. Whenever I read an article on the comparion of javascript framewroks always size of the script is mentioned in big bold letters.


They say Backbone is just 6.5k, Angular at 40k, Ember at 90k but it does it really matter?


In today's world where people have high broadband connection, mobiles are equipped with high speed 4G and 3G, I think an additional 50k size more doesn't affect. I believe its the features that a framework provides should be given importance.


If a particular framework suits my needs, then even if is 50k or even a 100k more, I believe it should be picked up.


I want to know whether what I think is right?





ember.js check all checkboxes

Hi im learning ember and got stuck with checkboxes.


Heres my template (part):



<table>
<thead>
<tr>
<th class="cell-delete">
{{input type="checkbox" id=colorId name=colorId class="js-custom-checkbox" checked=allChecked}}



</th>
<th class="cell-star">
&nbsp;
</th>
<th class="cell-broadcaster">Author</th>
<th class="cell-title">Title</th>
<th class="cell-date">Date</th>
</tr>
</thead>
<tbody>

{{#each message in model.entities}}

<tr>
<td class="cell-delete">

{{input type="checkbox" id=trash name="trash[]" tabindex= message.id class="js-custom-checkbox check1" }}

</td>
<td class="cell-star">
{{input type="checkbox" name=message.id tabindex=message.id class="starBox" }}

</td>
<td class="cell-broadcaster">
{{message.notification.autor.firstName}} {{message.notification.autor.lastName}}
</td>
<td class="cell-title">
{{#link-to 'notifications.details' message.notification.id}}{{message.notification.title}}{{/link-to}} {{#unless message.isRead}} (new) {{/unless}}
</td>
<td class="cell-date">
{{formatDateWithDistance message.notification.cdate}}
</td>
</tr>

{{/each}}

</tbody>
</table>


And my question is how to enable action to check all checkboxes in this template?


Data for this are taken in router form json api:



export default Ember.Route.extend(AuthenticatedRouteMixin, {

model: function() {
return $.getJSON(ENV.apiHost + "/api/notificationdata/user/all");

},
.....




jeudi 26 février 2015

Global AJAX Error Handler in ember.js

I'm building an Ember application that has a lot of integration with a back-end API, so I'd like to set up a global AJAX error handler to display to the user if AJAX requests fail. How do I set up a global AJAX error handler in ember.js?


So far, I have an errorController:



MyApplication.ErrorController = Ember.ObjectController.extend({
errorTitle:"",
errorDescription:"",
actions: {
backToHome: function() {
this.transitionToRoute('home');
}
}
});


And I'm trying to use jQuery's ajaxError function to capture an AJAX failure:



Ember.$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
var errorController = MyApplication.controllerFor('error');
errorController.set('errorHeading', 'AJAX error');
errorController.set('errorDescription', jqXHR.responseText); //server will return the error description
MyApplication.transitionToRoute('error');
});


However, controllerFor doesn't exist in the MyApplication variable. I'm not sure what other way to access ErrorController since the error function is completely out of the scope of the Ember application.





ember-cli with orbit.js - Error: Could not find module orbit

I have trouble setting up orbit.js in an ember-cli application.


I'm trying to replace the ember-data-localstorage with the orbit.js localstorage. You can see my changes in a github-commit.


When i build and start the application i get this js error:


Error: Could not find module orbit throw new Error('Could not find module ' + name);


I thought the entries in the Brocfile.js would take care of the module loading, but obviously i did something wrong. I also updated ember-cli and the dependencies afterwards, but that didn't change anything.


Can someone please point me in the right direction?





How to access a known Ember component from console

Using Ember debug Chrome extension, I have identified this component:


<MYAPP@component:zipcode-field::ember592>


Which is shown in hierarchy as:



application
engine
myui
zipcodeField


If I edit the value property of that element in the debugger, it updates the UI and model as desired. Can I do this via a one-liner from the conosole?





Ember JS pass object as transitionTo parameter

I'm capturing information from a form in my app and then saving that in a JSON array of objects.


Here's a link to the pertinent code: http://ift.tt/1Ew9N5K


inputSubmit is the name of the method being run on form submission. the variables are getting the values stored in each text input from the form. the for in statement checks to see if the item already exists in the userList JSON array, which is where i store all the items the user is adding. it only contains user-submitted items and is empty by default.


as you can see from the snippet i've included, i'm able to pass the name added through the form to its own details page. on that page i want to simply show the user what information they've submitted.


the question is how do i pass the name, description and other info related to the unique item that i've created a page for. right now all i can get it to do is spit out a list of names of all the items and their information even though it creates the unique page correctly.


thanks!





Compile templates client side with Emberjs 1.10 without node?

We have been using Ember for our MVC app through version 1.9. Now, with 1.10 it appears as though we need node to precompile templates somehow on the client side before they are viewed in the application, is that correct?


Unfortunately, we work in a very restricted environment where node and npm are "coming", but we don't have them yet. We've simply been including the handlebars.js file with ember to make our app work at runtime. So my real question - is there a way for me to continue using the newest versions of handlebars (or HTMLbars) and ember within my app without the need for node?


Please let me know if I'm missing something. I read the blog post (http://ift.tt/1DH2hC2) and lots of other discussion on this topic and I can't seem to understand this enough to move forward. Thanks in advance for any clarification you provide.





Ember - Cli Error: spawn ENOENT

I am cloning this project to run locally.


These are the steps i have done in my Terminal



git clone http://ift.tt/1zM4kCu
cd ember soundcloud
ember install
ember server


I got this errors in my Terminal:


enter image description here enter image description here


And this is what i see in my http://localhost:4200/


enter image description here


Server is runnings, so this is good sign! but how can i fix it?





Sorting on numerical model attribute in Ember

I've got a very basic Price model that looks like this:



App.Price = DS.Model.extend({
value: DS.attr()
});

App.Price.reopenClass({
FIXTURES: [
{ id: 1, value: 29.99 },
{ id: 2, value: 39.99 },
{ id: 3, value: 49.99 },
{ id: 4, value: 55.99 }
]
});


Here's the route that's using this model:



App.PricingRoute = Ember.Route.extend({
model: function(){
return this.store.find('price');
}
});


In the controller, I set the sorting to be based on the value attribute:



App.PricingController = Ember.ArrayController.extend({
sortProperties: ['value'],
sortAscending: true
});


Then my template (in Jade) where I want them to be display in sorted order:



{{#each price in this}}
li.price-levels__value {{price.value}}
.price-levels__remove("{{action 'delete' price.id}}")
{{/each}}


Problem is they're not sorted. Interesting fact is that if I change the type of the value attribute to strings, the sorting DOES work.


eg.



{ id: 1, value: '29.99' }
{ id: 2, value: '39.99' }
etc.


So how do I get the sorting to work on a numerical model attribute?





How should I observe a dynamic set of attributes so that observers get fired any time an attribute is set or changed?

I'm relatively new to the Ember world and have run into a snag.


I've got a search grid with a variable number of filters (set dynamically) that can trigger a change of the search results. Because the filters are set dynamically, I won't know their names (and can't set properties on my controller which I would then observe).


I've set up a JSBin here that shows what I'm attempting: http://ift.tt/1AwXapu


I'm wanting to have the filterValuesWatcher observer log to the console when any value is set on the filterValues object / property. In essence I'd like to have an observes('filterValues.*') in effect.


Any suggestions on what I'm missing?





Odd behavior when using Ember Data under a high-latency network

Saving my Ember Data model causes the data store to update the record from the response from the server.


For most cases, this functionality is expected and works perfectly fine. However, I ran into a case where if the server response is slow, then any fields that were modified post-save are now reset.


We had a requirement where we needed to "save on input blur", so I reopened some of the built-in view helpers to send a 'save' event to the current controller. For example:



Ember.Select.reopen(Ember.TargetActionSupport, {
_sendSave: function() {
this.triggerAction({
action: 'save',
target: this.get('controller')
});
}.on('change')
});


As for my current solution, I am simply throttling the save action:



save: function() {
Ember.run.throttle(this, this._save, 5000); // saves the model if `isDirty`
}


I was wondering if anyone has any ideas on the best way to handle this? One solution that was mentioned from my team was to not sync the data from the incoming response. I do not think that this is a good idea, and I would prefer that the current record merges itself into the response's record. Please let me know if further elaboration is needed.





Watch addon for changes

I want to contribute to an ember-cli addon, but I don't see an easy way to check my changes quickly. Now I have the source code of the addon locally, and the package.json of my ember-cli app looks similar to this:



...
"ember-addon": "file:../path/to/addon",
...


Right now I'm re-installing the addon after every change and re-launching my app. Is it possible to watch for changes on the addon and reload my app?





Ember-Model with custom serializer

I have a project that uses Ember-Model. I cannot get the custom attributes I defined for a model to work. How can I access the date and time properties from the custom DateTime attribute I have made? This custom attribute is used on the active_date property used in the Model.


Here's a Fiddle to my code: http://ift.tt/1MVqhrM


Please don't just suggest I use Ember-Data. Ember-Model is already in place and I just want to understand what the Custom Attributes do, and how to use them.


Here's my JavaScript:



App = Ember.Application.create();

var DateTime = {
dateStr: '',
timeStr: '',

serialize: function(string) {
var pieces = string.split('T');

this.dateStr = pieces[0];
this.hours = pieces[1].replace('Z','').split(':')[0];
this.minutes = pieces[1].replace('Z','').split(':')[1];

return {
date: this.dateStr,
time: this.hours + ':' + this.minutes
};
},

deserialize: function(string) {
return this.dateStr + 'T' + this.hours + ':' + this.minutes + 'Z';
}
};

App.TheModel = Ember.Model.extend({
name: Ember.attr(),
date: Ember.attr(DateTime)
});

/*** MOCK SERVER DATA ***/
var JSON_DATA = {
"name": "John",
"active_date": "2015-01-22T01:30Z"
};

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

App.IndexRoute = Ember.Route.extend({
model: function() {
return App.TheModel.create(JSON_DATA);
}
});


Here's my template:



<script type="text/x-handlebars">
{{outlet}}
</script>

<script type="text/x-handlebars" id="index">
<h1>Index Template!!!{{active_date}}</h1>
<p>name = {{name}}</p>
<p>active_date = {{active_date}}</p>
<p>active_date.date = {{active_date.date}}</p>
<p>active_date.time = {{active_date.time}}</p>
</script>




simple method aliasing in Ember

I have the following code



var object = Ember.Object.create({
foo: Ember.computed.alias('bar'),
bar: function(){
console.log('bar');
}
});

object.foo();


It raises



TypeError: object is not a function


Is there an idiomatic way to achieve this?





simple method aliasing in Ember

I have the following code



var object = Ember.Object.create({
foo: Ember.computed.alias('bar'),
bar: function(){
console.log('bar');
}
});

object.foo();


It raises



TypeError: object is not a function


Is there an idiomatic way to achieve this?





How to append bind-attr class to initial one in Ember?

How to append dynamic CSS class to initial static one using {{bind-attr}}?


When there is a static initial class, dynamic one is not added on page load. When I change variable during application run class binding works normally.


Here is a JSFiddle example.





Binding the output from an Ember helper to the value of an Ember input helper

I wrote a Ember/Handlebars helper to format a date using Moment.js:



Ember.Handlebars.registerBoundHelper('formattedDate', function(date, format) {
var formattedDate = moment(date).format(format);
return new Handlebars.SafeString(formattedDate);
});


Now, I want to use that in tandem with an Ember input helper like so (where startDate is a property on the model in scope):



{{input id="startDatePicker" class="form-control" value={{formattedDate startDate 'MMM D'}} required=true}}


But that doesn't work and throws a syntax error. Is there any way to do this?





Ember testing: You have turned on testing mode, which disabled the run-loop's autorun

I am trying to write a simple Ember integration test and continue to get the frustrating run loop error despite using Ember.run. I've had a nightmare of a time trying to get this to work, if anyone could help me I'd be so grateful. Specifically, I can see the test sign in and begin loading the next page (as it should), but as soon as the test finishes I get that error. This is regarding the second test, the first passes (as nothing is async I believe).



import Ember from 'ember';
import startApp from 'jobs-tuftsdaily/tests/helpers/start-app';
import exists from 'jobs-tuftsdaily/tests/helpers/start-app';

var App;

module('Integration - Landing Page', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
}
});

test('Should load content', function() {
visit('/').then(function() {
ok(exists("*"), "Found HTML!");
ok(exists('label:eq(4)'), "Slug label on page");
});
});

test('Should sign in test user', function() {
Ember.run(function() {
visit('/').andThen(function() {
return fillIn("input[name=email]", "test@test.com");
}).andThen(function() {
return fillIn("input[type=password]", "password");
}).andThen(function() {
return click("button");
}).andThen(function() {
ok(1, "stupid test passed");
});
});
});




Sharing data between controllers in Ember

I'm new to Ember and I'm pulling my hair out over this.


The app I'm working on has a set of "alerts" that will be dynamically updated. I have the alerts template/controller/module all working fine. The alerts controller has a method for displaying the number of alerts that have not been dismissed. This works fine within the alerts template.


However, when I access that same method from another controller, it always returns 0.


Here's a pastebin with the controllers, templates and model


Thanks for any help!





Show files in Broccoli-tree?

My Ember-CLIs vendor.js is taking up way too much space. Therefore I'd like to be able to see which files go into its Brocolli-tree.


I tried http://ift.tt/1EuJxJ0 and added this to my Brocfile.js but upon launching ember serve nothing is output



var loggedApp = log(app.toTree(), { output: 'tree', label: 'my-app-name tree' });

module.exports = app.toTree();




Model not found on ObjectController

I have an ArrayController (documents) which displays a list of ObjectsControllers (document) for its content. Currently, when I call this.model.save() or this.model.rollback() on a document controller , I get an undefined error message. Strangely however, each document controller is correctly displaying the values from its model in its template.


My ArrayController template (Documents):



{{#each document in controller}}
{{render "document" document}}
{{/each}}


The reason I use render is because I need a separate view for each document controller. Why is the model missing from each document's object controller please?


Update


I have replaced the "each" line above as follows:



{{#each document in model}}


The model is now available, but now the sorting I have put in place on the my ArrayController using the sortProperties and sortAscending properties are no longer taking effect.





Trying to get QUnit working with Emberjs

I'm trying to setup ember-testing with QUnit to test my Ember.js application.


My problem is the app isn't rendering on the QUnit test page, and thus the visit('/') function isn't working.


index.html



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MKTS Tests</title>
<meta name="viewport" content="width=device-width" />

<link rel="stylesheet" href="./bower_components/qunit/qunit/qunit.css">
<!--
<link rel="stylesheet" href="./css/foundation.css">
<link rel="stylesheet" href="./css/app.css">
-->
<style type="text/css">
#qunit-fixture, #app-root {
position: relative;
top: 0;
left: 0;
width: auto;
height: auto;
}
</style>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>

<!-- Libraries (Dependencies) -->
<script src="../app/bower_components/requirejs/require.js"></script>
<script src="../app/bower_components/jquery/dist/jquery.min.js"></script>
<script src="../app/bower_components/handlebars/handlebars.js"></script>
<script src="../app/bower_components/ember/ember.js"></script>
<script src="../app/bower_components/ember-data/ember-data.js"></script>

<!-- App and Templates -->
<script src="../app/scripts/app.js"></script>
<script src="../app/scripts/models/fleets.js"></script>
<script src="../app/scripts/routes/application_route.js"></script>
<script src="../app/scripts/routes/index_route.js"></script>
<script src="../app/scripts/router.js"></script>
<script src="../app/scripts/store.js"></script>

<!-- Test Helpers -->
<script src="./support/test_helper.js"></script>

<!-- Test Library -->
<script src="./bower_components/qunit/qunit/qunit.js"></script>

<script src="./spec/integration.js"></script>
<script src="./spec/unit.js"></script>

</body>
</html>




integration.js



test('hello world', function() {
//debugger;
//expect(1);
MarketSetupAdminUi.reset();
visit("/").then(function() {
var title = find('title');
equal(title.text(), 'Market Setup Tool', 'Title check');
});
});




test-helper.js



(function (host) {
var document = host.document;
var App = host.MarketSetupAdminUi;

var testing = function(){
var helper = {
container: function(){
return App.__container__;
},
controller: function( name ){
return helper.container().lookup('controller:' + name);
},
path: function(){
return helper.controller('application').get('currentPath');
}
};
return helper;
};

Ember.Test.registerHelper('path', function() {
return testing().path();
});

Ember.Test.registerHelper('getFoodController', function() {
return testing().controller('food');
});

// Move app to an element on the page so it can be seen while testing.
document.write('<div id="test-app-container"><div id="ember-testing"></div></div>');
App.rootElement = '#ember-testing';
App.setupForTesting();
App.injectTestHelpers();

function exists(selector) {
return !!find(selector).length;
}

}(window));




How to apply 'Blink' feature in Ember Table?

in Ember Table, I need to change style of cell with the change of particular cell content. i need to add color to cell with value update (that i have already done) and remove styles after 1 second(that i want to do).


I have called to setTimeout when applying color and removed color within setTimeout. It does not work all the time. some cell colors are not removed. (this gets worse when scrolling). i assume after 1sec ember cannot find particular cell element. I use Ember table component and assigned contentBinding and columnBinding. and added a template for Ember.Table.TableCell component and added class names.


This is my table component



App.MyTableCellView = Ember.Table.TableCell.extend({
templateName: 'cell_view',
previousColumnValue: -1,
param: null,
clearStyles: Ember.computed(function () {
var self = this;
var currentVal = this.get('previousColumnValue');
setTimeout(function () {
self.set('param', -1);
}, 1000);
return null;
}).property('cellContent'),
customColor: Ember.computed(function () {
var column, row, _ref, preVal, currentVal, cellColor;
preVal = this.get('previousColumnValue');
currentVal = this.get('cellContent');
if (preVal && currentVal && preVal !== -1 && currentVal !== -1) {
if (preVal > currentVal) {
cellColor = 'red';
} else if (preVal < currentVal) {
cellColor = 'green';
} else if (this.get('param') === -1) {
cellColor = '';
this.set('param', 0);
}
}
this.set('previousColumnValue', currentVal);
return cellColor;
}).property('cellContent', 'param'),

styles: Ember.computed(function () {
var x = this.get('clearStyles');
return "height:30px; background-color:" + this.get('customColor') + ";'";

}).property('customColor', 'previousColumnValue')


this is html



<script type="text/x-handlebars" data-template-name="cell_view">
<div {{bind-attr style="view.styles" }}>
<span>
{{ view.cellContent}}
</span>
</div>
</script>


Please tell a way to remove style of a cell after 1 sec.





Uncaught TypeError: undefined is not a function on getAttribute method

I have a function where I need to get the 'id' of an element in an array (county).



function returnCountyId(){
var countyName = findCountyMatchFromServer();
var foundCounty = county.findBy('title', countyName);
var countyId = foundCounty.getAttribute('id');
return countyId
}


I find the name (countyName) but somehow



foundCounty.getAttribute('id');


returns error: Uncaught TypeError: undefined is not a function


Rest of the code:



function findCountyMatchFromServer(){
var county = getElementAsString("ddlCounty");
return county;
};

var county = [{
id: '1',
title: "Harjumaa",
avgPrice: '1234',
avgSurface: '23',
}, {
id: '2',
title: 'Hiiumaa',
avgPrice: '5345',
avgSurface: '243',
}]


Thank you!





Ember Model Custom Relationships

I have several models that I am working with:


invoice-group.js



import DS from 'ember-data';

export default DS.Model.extend({
name: DS.attr('string'),
primary: DS.attr('number'),

//relationships
invoiceGroupMembers: DS.hasMany('invoiceGroupMember'),
billables: DS.hasMany('billable'),
matter: DS.belongsTo('matter')
});


invoice-group-member.js



import DS from 'ember-data';

export default DS.Model.extend({
billSplit: DS.attr('number'),

// relationships
invoiceGroup: DS.belongsTo('invoiceGroup'),
firm: DS.belongsTo('firm')
});


firm.js



import DS from 'ember-data';

export default DS.Model.extend({
name: DS.attr('string'),
tmNum: DS.attr('number'),
phone: DS.attr('string'),
address: DS.attr('string'),
suite: DS.attr('string'),
city: DS.attr('string'),
state: DS.attr('string'),
zip: DS.attr('string'),
region: DS.attr('string'),
industry: DS.attr('string'),
rating: DS.attr('string'),
scBusiness: DS.attr('string'),

// relationships
invoiceGroupMembers: DS.hasMany('invoiceGroupMembers')
});


firm-has-matter.js



import DS from 'ember-data';

export default DS.Model.extend({
//define me so they are available in a model:instance

billSplit: DS.attr('number'),
primary: DS.attr('string'),
firmMatterNumber: DS.attr('string'),
status: DS.attr('string'),

//relationships
firm: DS.belongsTo('firm'),
matter: DS.belongsTo('matter')
});


So in the template, I need to loop through the invoice-groups, and inside of that loop i need to get all of the loop through all of the firms that are assigned to the particular matter. The problems is that invoice-groups model has a matter attribute, and firm-has-matter has a matter attribute, but i don't know how to relate the two together so that i can loop through the firms that are related with the matter that is set in the invoice group record.


this is pseudocode, but I would like to be able to do something like:



{{#each ig in invoice_groups}}
{{input style="float:left;" value=ig.name type="text" name="name"}}
{{#each firm in ig.firms}}

{{/each}}
{{/each}}


Obviously, no such relationship exists, but I was just wondering how you would go about facilitating such a relationship while still using Ember data, or is it something where I am going to have to break with Ember data and build and object in the controller that I pass into the template.


I am converting an existing app from codeigniter, to restapi with an ember client side. In the existing app, we are just querying everything we need and manipulating the data in the model to pass a custom array into the view.



public function getMatterGroups($matters_id)
{
$invoice_groups = $this->db->select("i.*")
->from('invoice_groups as i')
->where('matters_id', $matters_id)
->get()
->result_array();

//format for easy access and prep firms
$groups = array();
foreach ($invoice_groups as $group) {
$group['firms'] = array();
$groups[$group['id']] = $group;
}

$members = $this->db->select("m.*, f.name as firm_name")
->from('invoice_group_members as m')
->join('invoice_groups as i', 'i.id = m.invoice_groups_id')
->join('firms as f', 'f.id = m.firms_id')
->where('matters_id', $matters_id)
->get()
->result_array();

// now load all related firms into that invoice group
foreach ($members as $member) {
// register the firm with the invoice group
$groups[$member['invoice_groups_id']]['firms'][] = $member;
}

// count all invoices for each group
foreach ($groups as $key => $group) {
$group['invoice_count'] = $this->db->select("id")
->from('invoices')
->where('invoice_groups_id', $key)
->where('matters_id', $matters_id)
->get()
->num_rows();

// update group
$groups[$key] = $group;
}

return $groups;
}


So ultimately we end up with an array like so:



$invoice_groups = array(
2 => array(
'id' => '2',
'matters_id' => '378',
'name' => 'All',
'primary' => 0,
'firms' => array(
'0' => array(
'id' => '3',
'invoice_groups_id' => '2',
'firms_id' => '34',
'bill_split' => '16.0000',
'firm_name' => 'FIRMS NAME'
),
'1' => array(
etc.
),
)
),
);


So how can you achieve this using Ember-data, and if that is not possible, how would you accomplish this in your controller or route?





What is the proper way in ember to use scheduleOnce that is test friendly?

Not too uncommon we'll need to schedule an update after rendering completes in reaction to a property change. Here is an example



page_changed: function() {
Ember.run.scheduleOnce('afterRender', this, this.scroll);
}.observes('current_page')


This doesn't work for testing since there is no runloop at the time scheduleOnce is called. We can simply wrap scheduleOnce in an Ember.run



page_changed: function() {
Ember.run(function() {
Ember.run.scheduleOnce('afterRender', that, that.scroll);
});
).observes('current_page')


..but I'm being told that's not the right way to go about it. I thought I'd reach out and get some other ideas.


For reference here is the issue that I opened up in ember.js#10536





Don't deliver sourcemaps?

I've got an Ember-applications and would like to stop delivering the sourcemaps of the minified resources to the user as they take up a vast amount of space.


How can I stop them from being delivered when Ember is built in production-mode?





Where do I use Pretender to enable Ember Qunit integration tests with rails-csrf?

We are using rails-csrf in our ember-cli app. The README on rails-csrf says:



Be sure to mock out the call to the csrf server endpoint. Otherwise your tests will fail with


"error while processing route: [route]"


messages in the browser console. For example:




server = new Pretender(function() {
this.get('/csrf', function(request) {
return [200, {"Content-Type": "application/json"},
JSON.stringify({
"authenticity_token": "token"
})
];
});
});


I understand the problem here (our integration tests are indeed showing this error) and I understand how Pretender solves it. I've got Pretender installed via ember-cli-pretender.


What I don't understand is how this code snippet - configuration for a Pretender mock - should be included to be useful. Should it go in the setup hook of an integration test? (I've tried that, and it hasn't worked yet, but that doesn't mean it won't.) Should it go in tests/helpers/start-app.js along with the integration test setup?


I tried this, but it isn't working:



module('Integration test', {
setup: function() {
App = startApp();

var server = new Pretender(function() {
this.get('/csrf', function(request) {
return [200, {"Content-Type": "application/json"},
JSON.stringify({
"authenticity_token": "token"
})
];
});
});
},
teardown: function() {
Ember.run(App, App.destroy);
}
});


Or should we just be using ember-pretenderify? Does that handle this sort of case?


(This question is superficially similar to this older one, but the available tools for handling this in Ember have changed significantly.)





Ember - async computed property or observer?

So I'm new to Ember and trying to work out the best way to set a computed property that depends upon related model data. I'll include the models below FYI.


I want to set the computed property to an asynchronous result (desiredOutcome). My question is how do I this? Or is it more appropriate to use an observer, as in this question.



score: function() {
var self = this;
var allscores = this.get('model.scores');

//Find the scoreRecord that has the appropriate objective id (in this case just 1)
var scoreRecord = allscores.find(function(item){
var scoreID = item.get('id');

return self.store.find('score', scoreID).then(function(scoreRecord){
var objID = Number(scoreRecord.get('objective.id'));
if (objID === 1){return true;}
});
});

//Return the scoreRecord's score attribute
var scoreID = scoreRecord.get('id');
return this.store.find('score', scoreID).then(function(score){
var desiredOutcome = score.get('score');
console.log(desiredOutcome);
return desiredOutcome;
});
}.property('model.@each.scores', 'selectedObjective'),


Apologies for the poor choice of variable names etc...


My models:


student



scores: DS.hasMany('score', {async: true}),
name: DS.attr('string')


objective



name: DS.attr('string'),
scores: DS.hasMany('score', {async : true})


score



scoreResult: DS.attr('number'),
objective: DS.belongsTo('objective', {async: true}),
student: DS.belongsTo('student', {async: true})




LSAdapter with ember-rails

I am reading the book of Ember in action but trying to write the code with ember-rails.


In the first chapter I didn't arrange to use the LSAdapter. When I checked Network of Ember Inspector, it seem like it is calling the api (exactly to /notes). My code is like:



# routes/notes.js.coffee
Notes.NotesRoute = Ember.Route.extend
model: -> @store.find 'note'

# store.js.coffee
Notes.ApplicationStore = DS.Store.extend
adapter: DS.LSAdapter # specify to use Local Storage Adapter

# router.js.coffee
Notes.Router.map ()->
@resource 'notes', path: '/', ->
@route 'note', path: '/notes/:id'


Am I doing something wrong? Any suggestion will be appreciated. The error I see in the console is:


enter image description here





Simulating an actual page reload with Ember to enable Chrome password saving

When a user submits our signup form in Safari and Firefox, they are prompted for saving their username and password. However, in Chrome this does not happen. After some research I have found that Chrome only prompts after an actual page refresh/redirect after login which I achieve using document.location = "/". However, this causes an unnecessary page reload and flicker. Any suggestions on how I can work around this Chrome limitation for single page apps would be appreciated please.





framework - best framework to use for web application

I am building a web application that will help manage documents in any organization. Users will be able to upload files in pdf format and pass it to another user for evaluation etc. The receiver will get a notification that he has received a file etc.


I am unable to decide which framework to follow, so that it is easy to scale the application for many departments. For client side should I user Ember or Angular. Should I exchange data and update pages using ajax(using json) for better views or use just jsp for all the dynamic content.


I have done the basic coding and but now I have to scale the application for better user experience and more features. So I was thinking of using a framework.Is single page application type architecture good for this ?? Please help !!





how to create a separate copy of properties in ember js

After my latest update of ember-cli to 0.1.12 array.slice and jquery.extend is not creating a separate copy of arrays and objects.


Eg:



//Arrays
{
arrayProp: [a,b,c],

someFunction: function () {
var localArrayProp = this.get('arrayProp').slice(0);
localArrayProp.push('d');
/*
Now both arrayProp and localArrayProp will be a,b,c,d

This was not the case before updating, before updating arrayProp was a,b,c and localArrayProp was a,b,c,d
*/
}
}

//objects
{
objectProp: {'key1':'val1', 'key2':'val2'},

someFunction: function () {
var localObjectProp = $.extend({},this.get('objectProp'));
localObjectProp.key3 = 'val3';
/*
Now both objectProp and localObjectProp will be {'key1':'val1', 'key2':'val2', 'key3':'val3'}

This was not the case before updating, before updating objectProp was {'key1':'val1', 'key2':'val2'} and localObjectProp was {'key1':'val1', 'key2':'val2', 'key3':'val3'}
*/


}
}


Also now how to obtain the above.A bit urgent please!





Ember js download from service stack

So I need to find way how to download CSV file from service stack service via ember js app. Unfortunetly I am new in client / server things and file transfering with http.


I have method that creates CSV httpResult 'thing'




public HttpResult Get(ClaimPrintRequest printRequest)
{
string csvBody;
using (var session = NHibernateFactory.OpenSession())
{
var testClaims = session.QueryOver<Claim>().Take(10).List();
var testClaimsMapped = testClaims.Select(Mapper.Map<ClaimGridDto>).ToList();
csvBody = ServiceStack.Text.CsvSerializer.SerializeToCsv(testClaimsMapped);
}
using (var streamOfCsvString = GenerateStreamFromString(csvBody))
{
return new HttpResult(
new MemoryStream(Encoding.UTF8.GetBytes(csvBody)), "application/CSV");
}



}


and i have my action (coffee & javascript):



actions:
printGrid: ->
self = @
claimPrintRequest =
tempVal:'abc'
$.ajax(
url:'/api/print/claim'
type:'GET'
dataType: "json"
data: claimPrintRequest
).then(httpResult) ->
console.log 'abc'

actions: {
printGrid: function() {
var claimPrintRequest, self;
console.log('i am here 1');
self = this;
claimPrintRequest = {
tempVal: 'abc'
};
return $.ajax({
url: '/api/print/claim',
type: 'GET',
dataType: "application/csv",
data: claimPrintRequest
}).then(function(httpResult) {
return console.log('abc');
});
}


} });


and my button:



<button class ="btn btn-primary" {{action 'printGrid' }}>Print</button>


I know i am doing whole process WRONG or maybe part of it, but if i look into network:



Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:ss-pid=PCbUzmx01zh4wo7Wjm9z; ss-id=neElkAxnCOFbSOCG87in
Host:localhost:17951
Referer:http://localhost:17951/App/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
tempVal:abc
Response Headersview source
Accept-Ranges:bytes
Cache-Control:private
Content-Length:7259
Content-Type:application/CSV
Date:Thu, 26 Feb 2015 10:50:15 GMT
Server:Microsoft-IIS/8.0
Vary:Accept
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-Powered-By:ServiceStack/4.036 Win32NT/.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNcQWRtaW5pc3RyYXRvclxEb2N1bWVudHNcd2ViLXFhaXNcV2ViUWFpc1xPQy5XZWJRYWlzLlNlcnZpY2VcYXBpXHByaW50XGNsYWlt?=


it seems there is something


Anyone know or could give me a tip how to do this?





determining location of deprecation warning on Ember.js

I upgraded to Ember 1.18 and I'm getting:



DEPRECATION: Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.
at Ember.LinkView.EmberComponent.extend.init (http://ift.tt/1BfMkow)
at apply (http://ift.tt/1LHxUP9)
at superWrapper [as init] (http://ift.tt/1BfMjAQ)
at apply (http://ift.tt/1LHxUP9)
at new Class (http://ift.tt/1LHxUPb)
at Function.Mixin.create.create (http://ift.tt/1BfMkEO)
at CoreView.extend.createChildView (http://ift.tt/1LHxUPd)
at Object.merge.appendChild (http://ift.tt/1BfMkEQ)
at CoreView.extend.appendChild (http://ift.tt/1LHxV5v)


None of the traceback is my code, and I'm mainly using {link-to-animated} (without currentWhen explicitly)


How can I figure out where is the preblematic code?





mercredi 25 février 2015

Chrome 'duplicate tab' and back button for angular/ember apps

Chrome's duplicate tab feature doesn't copy the data in text fields for tabs which have open a javascript single page app (SPA) written on a framework like angluar.js or ember.js. How can I make my javascript app compatible with Chrome's duplicate tab feature?


Demonstration: The TodoMVC app is an SPA implemented in many js frameworks for comparison of the frameworks.


For the jQuery (non-framework example) and backbone apps, duplicate tab works. Type something in the textbox (DO NOT hit the enter key) then right click the tab and click 'Duplicate' in Chrome. The text you typed will appear in the duplicated tab. http://ift.tt/1AMC1Gt http://ift.tt/1FY93rC


However, for these examples, duplicating the tab does not duplicate the text in the "What needs to be done?" textbox. http://ift.tt/1uFMIta http://ift.tt/1FY93rD




Back button - related concern: in the above apps, if you try typing in some text (without hitting the enter key) and then, navigate away from the page, and hit the back button in your browser, the text you typed in the form is lost for angular/ember apps. How does one easily make their app persist form fields while navigating?





Will using javascript framework for my website be an overkill?

I have a website that is similar along the lines of a blog/news website in a niche area. Presently, it has hundreds of articles and I would like to add more user interactive features such as a newsletter subscription, search box, community forum, quizzes, commenting system for the posts etc.


Also, since the website has so many articles, I want to start managing them better like implementing common header and footer, adding dynamic content etc. The website gets several thousand visitors a day and is poised to increase.


I built the website from scratch using HTML5, CSS3, Bootstrap and Javascript/Jquery. The website is deployed using google app engine and PHP. Since I am also a web developer, I am really keen on learning one of the javascript frameworks such as emberjs/angularjs etc. I am aware that several news websites use these frameworks to better manage their websites.


Will using frameworks be an overkill for my website? Is it okay to use any one of these frameworks only for specific features such as search box, newsletter etc.


Any help will be greatly appreciated.





How to write an Ember Async Test Helper?

I had a longish sequence of async testing steps that I was going to need to repeat, so I figured it was a good time to collect those behaviors in an Ember Async Test Helper, but once I had put them in a test helper and was injecting it, the async steps seem like they weren't being waited for!


The testing guide has a lot of conflicting information on this. Some async helpers return a wait() call, others return nothing at all. Some wrap their contents in an Ember.run() call, some do not.


This is not helped by the example test helper JSbin, which are themselves in an error state.


Can anyone point me in the right direction? What am I supposed to provide the registerAsyncTestHelper function to get all of its async contents to be run and resolved on the next andThen?





Coffescript, undefined is not a function in Ember.js controller when calling internal function

My controller looks like this:



App.ExaminationController = Ember.ObjectController.extend

amountErrors: null

actions:
saveChanges: ->
if @get('model.isDirty')
@get('model').save().then(
->
(errors) ->
@setAmountErrors errors
)

cancelChanges: ->
@get('model').rollback()

submitValue: ( ->
if @get('isDirty')
'Zapisz'
else
'OK'
).property('isDirty')

setAmountErrors: (errors) ->
if errors.errors.amount
@amountErrors = errors.errors.amount[0]a
console.log @amountErrors


When the line @setAmountErrors errors is executed i get TypeError: undefined is not a function And although i tried and validated my code i looks like it's syntax is ok to me. I tried to modify it in all the possible ways of which i could think of. And when I drop the function call and write function call instead the function call like this:



App.ExaminationController = Ember.ObjectController.extend

amountErrors: null

actions:
saveChanges: ->
if @get('model.isDirty')
@get('model').save().then(
->
(errors) ->
if errors.errors.amount
@amountErrors = errors.errors.amount[0]
console.log @amountErrors
)

cancelChanges: ->
@get('model').rollback()

submitValue: ( ->
if @get('isDirty')
'Zapisz'
else
'OK'
).property('isDirty')


It suddenly started to work like intended. But i want to call a function and not write away body of this function. How to do it? What am I missing? Does it has to do anything with my coffescript code, or am I missing something in the Ember controller itself?





How to compile project's CSS files into one file

By default ember-cli seems to be set up not to compile css files into one (as it does with the JS files).


What is the best way to configure ember-cli to merge all files in app/styles (and subdirectories) into one app.css file (and then fingerprint etc)? Is this possible via the Brocfile or do I need to override EmberApp.styles()?





Ember creating via accepts_nested_attributes duplicates children

I have a parent and children models which I'm saving via accepts_as_nested_attributes in Rails. I have this working fine after changes to my serializer in Ember like so:



App.FooSerializer = DS.ActiveModelSerializer.extend DS.EmbeddedRecordsMixin,
serialize: (record, options) ->
json = @_super(record, options)

# re-write the keys for accepts_nested_attributes_for
json.bars_attributes = json.bars
delete json.bars

json

attrs:
bars: {
serialize: 'records',
deserialize: 'ids'
}


However when I save a new record I end up with the bars for the new record being duplicated in Ember those new records with a null id and then the saved versions with their appropriate id.


I was trying to look at the serializer to figure out if I can do something there to properly modify the records in Ember rather than duplicating them with the ones from the response but started to get a bit lost after the payload is normalized.





How to create record with belongsTo association with ember.js front end and rails back end

I'm trying to create a record that has a belongs_to association. I have a rails back end with an ember front end.


I'm able to create users, but can't figure out how to create posts for users, i.e.,



# rails/db/seeds.rb

user.posts.create(title: "bonjour")


Rails


Here are the rails models



class Post < ActiveRecord::Base
belongs_to :user
end

class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end


Here is the posts controller:



class Api::PostsController < ApplicationController

...

def update
post = Post.find(params[:id])
post.title = params[:post]['title']
post.save!
render json: post
end

def create
user = User.find(params[:id])
post = user.posts.create(title: params[:title])
render json: post
end

end


Here are the serializers' files



# app/serializers/posts_serializer.rb
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :user_id
end

# app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
embed :ids, include: true

attributes :id, :name
has_many :posts
end


Ember


Here are the Ember models



// app/models/post.js

export default DS.Model.extend({
title: DS.attr('string'),
user: DS.belongsTo('user', { async: true})
});

// app/models/user.js

export default DS.Model.extend({
name: DS.attr('string'),
posts: DS.hasMany('post')
});


Here is the create.js file for posts



// app/routes/posts/create.js

export default Ember.Route.extend({

model: function () {
return this.store.createRecord('post', {
title: ''
});
},

actions: {
create: function () {
var my_model = this.controller.get('model');
my_model.save();
this.transitionTo('users.show', my_model);
}
}
});


Here is the create.hbs template



app/templates/posts/create.hbs

<h4 class="create-new-post">Create New Post</h4>

{{input value=title class='post-title'}}

<p><button type='submit' {{action 'create'}} class='commit-post-creation'>Submit</button></p>


And lastly, here is the app/router.js file



...

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

this.resource('posts', function () {
this.route('show', {path: ':post_id'});
this.route('edit', {path: ':post_id/edit'});
this.route('create', {path: 'create'});
});

});

...


When I try to create a post, I get the error:



POST http://localhost:4200/api/posts 404 (Not Found)


The post shows up at first, but there is no user associated with the post, and then it disappears when the page refreshes.


Thanks. Any help would be really appreciated. I'm just learning Ember, so sorry about the massive post.





Complete Ember Login Demo - Injection Issue

I'm trying to teach myself Ember. I've seen very little complete demos on how to create an Ember App that checks for login status on load, and then allows a user to login and log out. The App should also have some basic permissions control (allow for public and private routes etc).


So far I've got the basics of the App up and running (big thanks to this). But I'm struggling with the login functions. The demo I have built has mock RESTful API responses, and returns the current user always (once I have that working, I'll figure out how the login form will work).


Q: Currently when the the App loads, it should get the logged in user (server will have a cookie set), and inject it into the routes and controllers. I have that working, but can't get the firstName, lastName of the current user inside the routes (they all come back undefined).


Take a look here: http://ift.tt/1BdAvit


Mock API response here: http://ift.tt/1A7D5Bb


I have the source code here: http://ift.tt/1BdAxH7





Load Soundcloud SDK inside Ember CLI App

I've got an Ember CLI-application and would like to use the Soundcloud SDK to retrieve track data and stream music.


I tried loading it inside a controller like this:



import SC from "http://ift.tt/OJL5Z7";


but I get this error:



Uncaught Error: Could not find module http://ift.tt/18mqgNL


What am I doing wrong?





Define a root path in the router with Ember

I'd like to know if it's possible to set a specific folder to be my root path for my routes/views/templates/controllers?


For example, my project looks something like this:



/controllers
/base
/main
/index.js
/welcome
/index.js

/routes
/base
/main
/index.js
/welcome
/index.js

/templates
/main
/index.hbs
/welcome
/index.hbs

/views
/base
/main
/index.js
/welcome
/index.js


My main folder is my root folder for all my controllers, routes, templates and views.


Using the URL:



  • mywebsite.com would access the page in /main/index.js

  • http://ift.tt/1kWKOee would access the page in /main/welcome/index.js


Thanks





Drag and drop into div

I have been wondering if there is a way to drag and drop objects with different widths into div, so they will not impose on each other.


Let's say I have two divs and 5 objects. By div I mean something like timeline with one column for each 5 minutes. And objects are films, each film has his length, obviously. What I want is to drag these films and drop them into my timeline.


Sorry, English is not my native language. I made a picture, might help you understand my question.


Here it is: http://ift.tt/1A6Ve27


P.S. I'm using ember.js, so if it has her own plugins or ways to do it, I would like to know.


Thanks!





How to get access to global variable in template?

I want to create global object with settings which I need to get from REST API. I need to make one request to REST API and get settings and after that I want to get access to these settings from any controllers and from any templates. What can you advice, what is the best practice for that problem?





Ember-Cli vendor.js initial download - Showing a loading message

What is the ember-cli way of displaying a static message to indicate that the emper-app itself (vendor.js) is loading (being downloaded)?


Current situation



  • Index.html is blank pre vendor.js download


Goal



  • Display something to the user while vendor.js is downloading to avoid making them leave the page while its loading.


Solution idea (not yet tested, not yet known if it's a good solution)



  1. Create a named div in the index.html file

  2. Hide it on ember initialization





Ember properties with multiple dependencies dont update as expected

I have following issue concerning understanding ember properties:


If i have a propertyA:



propertyA: function() {
return this.get("propertyB.someObject.someValue");
}.property("propertyB")


and a propertyB:



propertyB: function() {
return this.get("propertyY.someObject");
}.property("propertyX", "propertyY", "propertyZ")


And i have a binding for propertyA in some template like:



{{propertyA}}


Then in 90% of the cases in my code it happens that propertyA does not get updated properly when i set i.e. propertyX.


If i understand it correctly, then propertyB should become dirty as soon as one of the dependent properties (like propertyX) changes. This should automatically make propertyA dirty and thus update it automatically since it has a binding.


What happens in my code is, that propertyA remains the old cached value even when i called it in the console, but when i call propertyB it revaluates and returns the updated code, since it was dirty.


The question is, why does propertyA not automatically become dirty when propertyB does? Is it because propertyB has no binding in a template? I thought it is not necessary if propertyA has the dependence.


I also figured out that this problem does not occur when propertyB just depends on propertyX, so the multi-dependency must somehow mess things up.


Sorry for this quite complicated explanation but i tried to abstract my actual code as simple as possible.





How do I specify a mapping from an Ember model to JSON?

I have an API that returns:



{id: 1, "other-property": 100}


My Ember Data object is defined:



MyApp.MyThing = DS.Model.extend({
extId: DS.attr('number'),
otherProperty: DS.attr('number')})


It looks like I can't use id as an attribute in an ember model, and using non-identifier field names will cause trouble. So the guide suggests I write a normalizeHash function.



App.MyThingSerializer = DS.RESTSerializer.extend({
normalizeHash: {
id: function(hash) {
hash.appId = hash.id;
delete hash.id;
return hash;
},
otherProperty: function(hash) {
hash.otherProperty = hash['other-property'];
delete hash['otherProperty'];
return hash;
}
}
});


It doesn't suggest how to re-serialize when sending back over an API. How do I do this?


Is there a declarative way to do this? It seems very cumbersome.





Creating login with ember using Parse.com Restful api

I'm trying to manage protected access to my ember app/ rote.


This todo tutorial works using the Parse js lib with backbone.


I am using a pure ember implementation using REST with: http://ift.tt/1pmBMLz


How can I achieve the same thing using pure ember + REST





Ember query api with multiple parameters

I was wondering if it was possible to query the API with multiple parameters in one go.


I know we can do



this.store.find("assetType",{category:"ancillary"});


which will do a query of http://ift.tt/1Bsd8n3


But what I want to do is a query of http://ift.tt/17X0oai


Is this possible to do this in Ember on one go. Or will I have to do a filter on the results of the first query instead?





Ember getting error 404 (Not OK) with no code changes

This morning I got to work tried to run my app and got GET http://localhost:60589/Index.html?prvdRetarg 404 (Not OK) on console with no changes to my code which didn't have any errors yesterday... any ideas on what may have caused this?