mardi 31 mars 2015

"TransitionTo" affects page refresh in Ember

My ember application contains a parent route with two nested routes. After fetching the parent route's model I'll transition to one of the nested routes by default.


The router is as follows



this.resource('parent', {path: '/parent'}, function() {
this.route('route1', {path: '/route1'});
this.route('route2', {path: '/route2'});
});


In the parent route



redirect: function()
{
this.transitionTo('parent.route1');
}


Now this works perfectly fine. But the problem arises when I refresh the page while being on the route "#/parent/route2".


Actually I should get the contents of "route2" but the transitionTo makes the route to render "route1". How can I handle this ?





Deploy Ember-cli heroku Unexpected token punc «:», expected punc «,»

Build failed. Unexpected token punc «:», expected punc «,»


Error at new JS_Parse_Error (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:196:18) at js_error (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:204:11) at croak (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:678:41) at token_error (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:682:9) at expect_token (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:695:9) at expect (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:698:36) at /Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:1224:44 at /Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:721:24 at expr_atom (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:1181:35) at maybe_unary (/Users/MNinaut/Documents/Project/PremierCapital/system/front-end/node_modules/ember-cli-uglify/node_modules/broccoli-uglify-sourcemap/node_modules/uglify-js/lib/parse.js:1357:19)





How to define a large number of resources that use the same logic without creating boilerplate modules in ember-cli?

I have a large number of resources that use exactly the same logic for their routes, controllers, and templates. Each resource has a <resource> route and a <resource>.show route. I've defined BaseRoute, BaseShowRoute, BaseController, BaseShowController and corresponding templates to capture this common logic. I set the appropriate controller/templates on the route objects:



// routes/base.js
import Ember from 'ember';

export default Ember.Route.extend({
controllerName: 'base',
templateName: 'base'
});

// routes/base/show.js
import Ember from 'ember';

export default Ember.Route.extend({
controllerName: 'baseShow',
templateName: 'baseShow'
});


But in order to use these route classes with my resources, I find I have to have two files for each resource:



// routes/<resource>.js
import BaseRoute from './base';

export default BaseRoute.extend({
});


// routes/<resource>/show.js
import BaseShowRoute from './base/show'

export default BaseShowRoute.extend({
});


This seems silly. I would like to somehow specify that all of these resources should use BaseRoute and BaseShowRoute without needing to create identical separate modules for each one. It would seem logical to be able to do this in Router.map. Something like this:



Router.map(function(){
this.resource('articles', { extends: BaseRoute }, function() {
this.route('show', { path: ':article_id', extends: BaseShowRoute })
});
});


But to my knowledge there is nothing like the extends option I'm using above.


The only documentation I can find for the route and resource methods invoked in Router.map is in the Routing Guide. The only option that you can pass to these methods seems to be path. The ember-cli user guide does say that you can override the base class for all generated routes if you define routes/basic.js, but this is not enough for me-- I need multiple base classes.


How can I get rid of my boilerplate route modules?





Dynamically output the expression within each loop in handlebar emberjs

Suppose I have the following controller



App.SomeController = Ember.Controller.extend({
container: Ember.A(['one','two','three']),
attrOne: 'Attribute One',
attrTwo: 'Attribute Two',
attrThree: 'Attribute Three'
});


In my handlebars, I can loop each of the value in the container array, but how I can dynamically populate each attr within the each loop



{{#each data in container}}
{{data}} // one, two, three
{{???}} // {{attrOne}} {{attrTwo}} {{attrThree}} ??? How ???
{{/each}}




Ember js cloning record with relations

What I try to achieve: user goes to post/3/edit. Here the form is bound to the model, so it already filled out. And on the top



You are editing the post {{model.title}}


If the user changes the title it changes dynamic. I don't want this behavior. I want to apply the changes to the record, if user already hit the "Save" button (and everything went right on server side).


my idea:



  1. clone the record

  2. bind cloned record to the form

  3. after hit "Save" the properties of the cloned (and edited) record are applied to the original record.


Questions



  • Is this the right way to do this?

  • Is there something like record.clone(), which deep copy the record with it's relations?

  • Is there a way to apply the changes, like originalRecord.apply(clonedRecord)?





How to test if page loads?

How can I write test that checks if page loads without errors/exceptions? I tried visit, but this will pass. I know I could check if some root element exists but that will not catch errors generated after the root element is made.



test("pageloads", function (assert) {
assert.expect(0);
visit('/nonexistingpage').then(function () {
return true;
});
});




upgrade ember addon on ember-cli 0.2.2

I started developing an addon in on ember-cli 0.2.1 and when I generated my files using the generator, they placed the files in ~/app/ and not ~/addon.


What do I need to do put the files in the right place?


The project contains services, mixins and utils with tests covering them.





Emberjs + ember-data find with param

I'm trying to find a model based on a param like this :



this.store.find('slide', {slideCategory: category});


But it return :



TypeError: Cannot read property 'length' of undefined


I'm running this code from an action in my SlideRoute.


Here is what my Slide model looks like



App.Slide = DS.Model.extend({
title: DS.attr('string'),
note: DS.attr('string'),
slideCategory: DS.belongsTo('slideCategory')
});


And my SlideCategory model



App.SlideCategory = DS.Model.extend({
title: DS.attr('string'),
slides: DS.hasMany('slide', {async:true})
});


It's running with fixtures and here is one record :



{
id: 1,
slideCategory: 1,
title: 'Slide 1',
note: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eget hendrerit lacus. Donec venenatis sagittis turpis a aliquet. Ut nec ipsum ac sem lobortis ultrices id eu ante. Aenean ut vehicula odio, non imperdiet risus. Aenean mattis diam nec nulla tincidunt, vitae vehicula dui vehicula.',
}


What I'm trying to do is to query all slide from a specific category and then add them to another model, but without this I'm stuck going backward and querying the category and then finding the slides in this category, although this doesn't work neither, I can't seem to be able to get the hasMany items from the category model.


This is what I currently do, but slideCategory.get('slides') doesn't give me the slides like it would work on another regular static property of the model :



this.store.find('slideCategory', category).then(function(slideCategory){
slideCategory.get('slides').then(function(slides){
$.each(slides, function(k,slide){

});
});
}


I'm using ember 1.11 and ember-data 1.0.0-beta.16


Thank you!





Ember changedAttributes() not show boolean change

I've been trying to store a list of changes to a model into another model before saving it, so that I can recall the changes to undo previous changes. This is the code that I'm using:



var changes = item.changedAttributes();
var newUndo = this.store.createRecord('undo', {
item_id: item.get('id'),
changes: changes
});


And my checkbox is a typical one:



{{input type="checkbox" checked=checked class="checkbox"}}


I have a component for the checkbox that sends a save action when checked changes, and the controller's save method is calling the code above when before saving the record:



import Ember from 'ember';
export default Ember.Component.extend({
checked: false,
model: null,
watchChecked: function () {
this.sendAction('save', this.get('model'))
}.observes('checked')
});


This works well for string attributes, but with boolean checkboxes, it's not acting as expected. This is what I'm seeing:


Page load, unchecked item is checked:



changes: {}


Then unchecked:



changes: {print_copy_sent: true,true}


Then checked again:



changes: {print_copy_sent: false,false}




Drop-down menu which changes the content on an other drop-down menu

I'd like to create a drop-down menu from a hasMany relation which filters the values of an other drop-down menu. I have ships which belongsTo companies and which haveMany cruises. The user of the webpage should be able to select nothing (the table displays all ships) or a company (the table displays just the ships of that company) or a specific ship (the table just displays one ship). If the user selected a specific company only ships of that company should be displayed in the ship drop-down menu. The table of ships should be updated too.


Screenshot of the ships index table.


How can I create a set of two drop-down menus (above or below the table) which behave like this example and filter the content of the table?


Screenshot of an drop down example.


I know this question is a tall order. I tried to break it down as much as possible. Thank you for your time and effort.


The code of my example application



ember new travel_agency
cd travel_agency
ember install:addon ember-cli-scaffold
ember g scaffold ship name:string
ember g scaffold company name:string
ember g scaffold cruise starts_at:date
ember generate adapter application
ember g http-mock ships
ember g http-mock companies
ember g http-mock cruises
ember install:addon ember-moment


app/adapters/application.js



import DS from 'ember-data';

export default DS.RESTAdapter.extend({
'namespace': 'api'
});


app/models/company.js



import DS from 'ember-data';

export default DS.Model.extend({
name: DS.attr('string'),
ships: DS.hasMany('ship', { async: true })
});


app/models/ship.js



import DS from 'ember-data';

export default DS.Model.extend({
name: DS.attr('string'),
company: DS.belongsTo('company', { async: true }),
cruises: DS.hasMany('cruise', { async: true })
});


app/models/cruise.js



import DS from 'ember-data';

export default DS.Model.extend({
startsAt: DS.attr('date'),
ship: DS.belongsTo('ship', { async: true })
});


server/mocks/ships.js



[...]
var shipList = [
{"id":1,"name":"Carnival Fantasy","company":1,"cruises":[1,2]},
{"id":2,"name":"Carnival Triumph","company":1,"cruises":[3,4]},
{"id":3,"name":"Queen Mary 2","company":2,"cruises":[5]},
{"id":4,"name":"Queen Elizabeth","company":2,"cruises":[6]},
{"id":5,"name":"Norwegian Jewel","company":3,"cruises":[7,8]}
]
[...]


server/mocks/companies.js



[...]
var companyList = [
{"id":1,"name":"Carnival"},
{"id":2,"name":"Cunard"},
{"id":3,"name":"Norwegian Cruise Line"}
]
[...]


server/mocks/cruises.js



[...]
var cruiseList = [
{"id":1,"startsAt":"2014-10-01","ship":1},
{"id":2,"startsAt":"2014-10-15","ship":1},
{"id":3,"startsAt":"2014-10-30","ship":2},
{"id":4,"startsAt":"2014-11-10","ship":2},
{"id":5,"startsAt":"2014-11-20","ship":3},
{"id":6,"startsAt":"2014-11-20","ship":4},
{"id":7,"startsAt":"2014-10-20","ship":5},
{"id":8,"startsAt":"2014-11-20","ship":5}
]
[...]


app/templates/ships/index.hbs



[...]
<tbody>
{{#each ship in model}}
<tr>
<td>
{{ship.name}}
</td>
<td>
{{ship.company.name}}
</td>
<td>
{{#each cruise in ship.cruises}}
{{moment date "L" cruise.startsAt}},
{{/each}}
</td>
<td>
{{link-to "Edit" "ships.edit" ship}}
</td>
<td>
{{link-to "Show" "ships.show" ship}}
</td>
<td>
<a href="#" {{action "remove" ship}}>Remove</a>
</td>
</tr>
{{/each}}
</tbody>
[...]




Ember CLI Simple Auth - Cannot read property 'on' of undefined

I've got two Ember 1.11 project that is using Simple-Auth via Ember cli simple auth. The simpler of the two (the basic hello world app) works just fine...in fact it works great (simple auth is pretty awesome). However, the other one (a recently upgraded app) has some sort of initialization error.


My error is: Error while processing route: receiving.index Cannot read property 'on' of undefined TypeError: Cannot read property 'on' of undefined


And it breaks in ApplicationRouteMixin in the beforeModel function on this line: _this.get(Configuration.sessionPropertyName).on(event, function(error) { Array.prototype.unshift.call(arguments, event); var target = routeEntryComplete ? _this : transition; target.send.apply(target, arguments); });


The Configuration.sessionPropertyName is "session" and it obviously can't find it. I haven't been able to recreate it outside of this one project, so any help is appreciated.


Sam





how to change upstream route, preserving subroutes in ember?

Say you have a router like so:



@resource 'products', ->
@resource 'product', { path: /product/:product_id } ->
@route 'description'


and you're currently in the


http://ift.tt/19xYOwL URL.


From this location, if you click a link to a different product, how do you modify that link so that the resulting page is not


root.com/products/37


but rather


http://ift.tt/1I13JVv?


I want to preserve the subroutes, as you can see. Or is there a better way to do this, for example, using an application controller property that gets passed around to every descendant route/controller?





Dynamic bound property for an HTMLBars Helper in Ember

I have a list of attribute names attrs that I would like to iterate over, creating an input with a binding to that attribute on the model for each for each. The below expresses the functionality I'm after:



{{#each attr in attrs}}
{{input value=model.get(attr) }}
{{/each}}


Of course this does not actually work, because you can't make method calls in a helper. I found this question, but the solution doesn't work in my version of Ember (1.11.0)-- I gather because this is undefined in a helper definition as of version 1.11.0 (see ).


How can I make this work?





How to render italic/bold text using handlebars?

So here is the thing, I am using Handlebars to render the template on the page.


Now in the context js object, I have a paragraph, which should have few italic words,


For e.g:



var context = {
"event":"This is event name <i>XYZ</i>"
}


And the paragraph is rendered as,



This is event name <i>XYZ</i>


Is there any way I can make/escape the font italic/bold in Handlebarsjs/Mustachejs ??


Here is the fiddle


Thanks!





laggy typing when binding a text input to compute a filtered list in Ember

I have an Ember application in which I have an input bound to property query. There is a computed property filteredRecords that uses query to filter the model to build an array of records display. The model contains a large number of records so there is some lag in the filtering process. This lag is OK, but I find that the typing into the search bar is also laggy. It seems that the rerendering of the list is getting in the way of text being rendered into the search bar. Is there a way to give the search bar "priority" such that typing into it is always smooth, even if the list takes a second or two to update?





Using export command to alter PATH from shell script file

I am setting up a vagrant box (VM) to mimic a server. The idea is that you initialize the VM by running one command and it provisions itself using a single bash script file, "bootstrap.sh".


I am trying to run ember on my VM.


So in the script file, I install node, nvm, npm, and all other kinds of dependencies and stuff. Just for reference, this is what the file looks like:



echo "installing node version manager"
curl http://ift.tt/1DlTrMZ | bash
source ~/.nvm/nvm.sh

# EMBER CLI & DEPENDENCIES ...

# Install node.js
echo "Installing node.js"
nvm install stable
nvm use stable

# Symlink node to node.js
echo "node symlink"
ln -s /usr/bin/nodejs /usr/bin/node

# Install npm
echo "Installing node package manager"
apt-get install -y npm

# Install Ember CLI
echo "Installing Ember CLI"
npm install -g ember-cli

# Install Bower
echo "Installing bower"
sudo npm install -g bower

# Install watchman from source
apt-get install -y autoconf automake
git clone http://ift.tt/1NDIdGH
cd watchman
./autogen.sh
./configure
make
make install
cd

# Install Phantom.js
echo "Installing Phantom.js"
sudo npm install -g phantomjs

# Do some weird path thing that makes npm find Ember (?)
echo "Creating path for node modules"
export PATH=node_modules/.bin:$PATH


But when i run ember s it says "ember: command not found".


If i rerun this line in the VM:



export PATH=node_modules/.bin:$PATH


then it works.


So it seems that export PATH=node_modules/.bin:$PATH does not work form the shell script file, but it does work if you run it from the command-line (on the VM via ssh)


Why is this happening and how can I make this command run the same from the script file, as if it were run from command-line?





Ember Checkbox getting name of element in callback

If I define a checkbox as follows:



{{input type="checkbox" name="email" checked=controller.isEmailChecked}} Email


In the callback controller.isEmailedChecked, defined as:



isEmailChecked: function(key, value) {
...
}


How do I get the value of name ("email")?


My controller is responsible for displaying multiple checkboxes so I do not want to have to write lines like this:



{{input type="checkbox" name="x" checked=controller.isXChecked}} X
{{input type="checkbox" name="y" checked=controller.isYChecked}} Y


Only to be doing:



ixXChecked: function(key, value) {
// Set or Get
this.set('x', value);
this.get('x');
}
ixYChecked: function(key, value) {
// Set or Get
this.set('y', value);
this.get('y');
}


Can someone point me to the docs please.


Edit: Same applies to actions on Buttons:



<button {{action 'toggleSetting'}}>
</button>


How would I get the name of the element in the toggleSetting callback?


Thanks a lot,





Ember history location HaProxy config

I'm unable to configure HAProxy to enable history location url.



App.Router.map(function() {


this.resource('user', { path: '/user/:user_id' }); });



App.Router.reopen({


location: 'history' , rootURL:'/' });


HAProxy config backend home_srvs mode http option httpclose option httplog reqrep ^GET\ /user/[0-9]+\ HTTP/1.1 GET\ /\ HTTP/1.1 balance roundrobin server web1 localhost:8080 check


when I browse to http://localhost/user/1, I see the following in haproxy log


Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42907 [31/Mar/2015:16:03:52.332] frontend home_srvs/web1 1/0/0/6/9 304 153 - - ---- 5/5/0/0/0 0/0 "GET /user/1 HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42908 [31/Mar/2015:16:03:52.332] frontend home_srvs/web1 22/0/0/28/53 404 361 - - ---- 6/6/5/5/0 0/0 "GET /user/css/bootstrap.css HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42911 [31/Mar/2015:16:03:52.332] frontend home_srvs/web1 24/0/0/34/76 404 353 - - ---- 5/5/5/5/0 0/0 "GET /user/js/app.js HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42910 [31/Mar/2015:16:03:52.332] frontend home_srvs/web1 24/0/0/53/79 404 360 - - ---- 4/4/4/4/0 0/0 "GET /user/js/libs/ember.js HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42909 [31/Mar/2015:16:03:52.332] frontend home_srvs/web1 24/0/0/51/84 404 368 - - CD-- 3/3/3/3/0 0/0 "GET /user/js/libs/jquery-1.10.2.js HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42912 [31/Mar/2015:16:03:52.333] frontend home_srvs/web1 23/0/1/48/85 404 361 - - CD-- 2/2/2/2/0 0/0 "GET /user/css/normalize.css HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42921 [31/Mar/2015:16:03:52.385] frontend home_srvs/web1 6/0/0/24/34 404 372 - - ---- 1/1/1/1/0 0/0 "GET /user/js/libs/handlebars-v1.3.0.js HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42915 [31/Mar/2015:16:03:52.355] frontend home_srvs/web1 1/0/0/64/66 404 357 - - ---- 0/0/0/0/0 0/0 "GET /user/css/style.css HTTP/1.1" Mar 31 16:03:52 localhost haproxy[6761]: 127.0.0.1:42923 [31/Mar/2015:16:03:52.452] frontend home_srvs/web1 0/0/0/6/6 304 153 - - ---- 0/0/0/0/0 0/0 "GET /favicon.ico HTTP/1.1"


What am I doing wrong? I've tried multiple things already. Thanks





Ember: When child controllers are observing same property of Parent controller firing request simultaneously

I have created an application with two child object controller and a parent array controller. The route is also described in the same way.





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

App.Router.extend(function() {
this.resource('parent', function() {
this.route('child1', {
path: '/'
});
this.route('child2');
});
});

var ParenteRoute = Ember.Route.extend({
model: function() {
//Got my model from here.
};
});

var Child1Route = Ember.Route.extend({
model: function(){
return Ember.$.ajax('dummyUrl.com');
},
action:{
refreshData: function(){
var controller = this.controllerFor('parent.child1');
return Ember.$.ajax('dummyUrl.com').then(function(response){
return controller.send('updateModel' response);
});
}
}
});

var ParentController = Ember.ArrayController.extend({
getFirstName: function() {
return this.get('model').get('firstName');
},
getLastName: function() {
return this.get('model').get('lastName');
}
});

var Child1Controller = Ember.ObjectController.extend({
needs: ['ParentController'],
getName: function() {
return this.get('controllers.ParentController.getFirstName')
},
updateName: function() {
this.send('refreshData');
}.observes('controllers.ParentController.getLastName'),
actions: {
updateModel: function(response) {
this.set('getName', response);
}
}
});

var Child2Controller = Ember.ObjectController.extend({
needs: ['ParentController'],
getFirstName: Ember.computed.alias('controllers.ParentController.getFirstName')
});



<!--Parent Template--!>
<div>
<input type='text' {{bind-attr value=getFirstName}}>
<input type='text' {{bind-attr value=getLastName}}>
</div>
{{#link-to 'parent.child1'}}child1{{/link-to}}
{{#link-to 'parent.child2'}}child2{{/link-to}}
{{outlet}}

<!--child1 template--!>

<div>
{{getName}}
</div>

<!--child2 template--!>

<div>
{{getFirstName}}
</div>



So the problem with the above code is that when I am in the index of parent controller then on change of getLastName property every time child1's function updateName() is called and is executed properly. But after doing some changes while keeping child1 route active if a move to child2's route by clicking on the link to, then when I change the property getLastName, though I am in child2, child1's updateName() function is also getting triggered because of the observes function and throwing the error:



Uncaught Error: Nothing handled the action 'refreshData'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.


I need help in understanding how I can tackle this problem. And is this method of reloading the model in a child up on a change in the parent controller's property is a good way, if not then please suggest the right way of doing it.





import openlayers3 in ember.js

I am starting up an ember.js app aimed at drawing and displaying maps.


I am using ember.js v1.11.0 and ol3 v3.4.0


I managed to install ol3 via bower and import it using Brocfile.js:



app.import('bower_components/ol3/build/ol.js');
app.import('bower_components/ol3/css/ol.css');


I can use it as well without problem in my views, etc. What I would like if possible is to get rid of the server errors:



views/map.js: line 6, col 22, 'ol' is not defined.
views/map.js: line 7, col 19, 'ol' is not defined.
views/map.js: line 10, col 21, 'ol' is not defined.
views/map.js: line 11, col 19, 'ol' is not defined.
views/map.js: line 14, col 19, 'ol' is not defined.
views/map.js: line 17, col 17, 'ol' is not defined.


And if possible get autocompletion in my Intellij IDEA (make it recognise the ol library)


If somebody could give me a hand, that owuld be much apreciated.





Unknown template object: function Precompile templates Emberjs and Gulpjs

I'm working with ember and gulpjs to precompilate the templates but I always I get the same mistake:



Error: Unknown template object: function
...e","number","stack"];return e.prototype=new Error,t=e}(),r=function(e,t){"use st...


This is the process with gulpjs



...
var handlebars = require('gulp-handlebars');
...
gulp.task('templates', function() {
// Load templates from the source/templates/ folder relative to where gulp was executed
gulp.src('./app/templates/**/*.hbs')
// Compile each Handlebars template source file to a template function using Ember's Handlebars
.pipe(handlebars({
handlebars: require('ember-handlebars')
}))
// Wrap each template function in a call to Ember.Handlebars.template
.pipe(wrap('Ember.Handlebars.template(<%= contents %>)'))
// Declare template functions with Ember.TEMPLATES according to their path and filename
.pipe(declare({
namespace: 'Ember.TEMPLATES',
noRedeclare: true, // Avoid duplicate declarations
processName: function(filePath) {
// Allow nesting based on path using gulp-declare's processNameByPath()
// You can remove this option completely if you aren't using nested folders
// Drop the source/templates/ folder from the namespace path by removing it from the filePath
return declare.processNameByPath(filePath.replace( './app/templates/', ''));
}
}))
// Concatenate down to a single file
.pipe(concat('templates.js'))
// Write the output into the templates folder
.pipe(gulp.dest('www/js/'));
});


The version with I precompile the templates are acording my package.json



"gulp-ember-handlebars": "^0.7.0",
"gulp-handlebars": "^3.0.0",
"handlebars": "^3.0.0",


And the versions of the templates interpreters according with my bower.json



"ember": "1.9.1",
"handlebars": "3.0.0"


In the index.html I loaded the templates



<html>
<head>
<meta charset="utf-8" />
<!-- load jquery,emberjs,handlerbars an more -->
<script src="js/vendors.js"></script>
</head>
<body>
<script src="js/main.js"></script> <!-- controllers from ember...-->
<script src="js/templates.js"></script>

</body>
</html>


And the compiled templates generate it (templates.js):



this["Ember"] = this["Ember"] || {};
this["Ember"]["TEMPLATES"] = this["Ember"]["TEMPLATES"] || {};
this["Ember"]["TEMPLATES"]["app"] = this["Ember"]["TEMPLATES"]["app"] || {};
this["Ember"]["TEMPLATES"]["app"]["templates"] = this["Ember"]["TEMPLATES"]["app"]["templates"] || {};
this["Ember"]["TEMPLATES"]["app"]["templates"]["index"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};

data.buffer.push("Hello world :D \n");

});


So I'm wondering what am I doing wrong?





lundi 30 mars 2015

How to get the prototype for a given key using container.lookupFactory

I have a simple key like "model:person" that I'm using to lookup like so



var factory = this.container.lookupFactory("model:person");


...and although this does allow me to "create" I need a quick/easy way to get the prototype for the given object so I can use it like so.


example:



App.Person.prototype.hasOwnProperty("...");




Conditional positioning with Sass of relative div, based on absolute psoition

I have the equivalent of a dropdown menu that is attached to a button. The button can be moved around the page. I currently have it so that you can specify if the dropdown flows left or right from wherever the button is



Right:

BUTTON
_/\______
|Dropdown|

Left:
BUTTON
______/\_
|Dropdown|


That's all fine except for when it gets too close to the right of left edge of the containing div, in which case it gets cut off (overflow:hidden).


What is the best approach to having it default to Left or right, but switch or adjust / offset its final position were to be too close to the edge?


The dropdown can also vary in width depending on the content.


My inital idea of how to approach this problem would be:



  1. Calculate the width of the dropdown

  2. Find the initial x position dropdown based on its parent's position

  3. Calculate final edge locations based on x + width

  4. Adjust x with a simple min or max type of equation


I just not sure how to do 1,2, or 3 :)


Thanks for your help!





New model instance with hasMany relationship from form data

I have two models:



// models/licenses.js
export default DS.Model.extend({
name: DS.attr('string'),
active: DS.attr('boolean'),
territoryType: DS.attr('string'),
territories: DS.hasMany('masterTerritory', { async: true }),
cities: DS.hasMany('city', { async: true }),
});


and



// models/license-type.js
export default DS.Model.extend({
primaryCity: DS.attr('string'),
region: DS.attr('string'),
licenseType: DS.belongsTo('licenseType', { async: true }),
});


I'm trying to create a new instance of the 'license' model from form data, including a select box containing licenseType data:



{{!-- templates/index.hbs --}}
...
{{view 'select'
contentBinding='controller.ddLicenseTypes'
optionLabelPath='content.name'
optionValuePath='content.id'
class='form-control'
value=newLicenseType
action='createLicense'
prompt='Select a License Type'
}}
...

// controllers/index.js
...
ddLicenseTypes: function() {
var store = this.get('store');
return store.findAll('licenseType');
}.property('store'),
...
actions: {
createLicense: function() {
var store = this.get('store');
var primaryCity = this.get('newPrimaryCity');
var region = this.get('newRegion');
var licenseTypeId = this.get('newLicenseType');
if(!primaryCity.trim()) { return; }
if(!region.trim()) { return; }
if(!licenseTypeId) { return; }

var license = this.store.createRecord('license', {
primaryCity: primaryCity,
region: region,
licenseType: store.find('licenseType', licenseTypeId), // What do I do here?
});

this.set('newPrimaryCity', '');
this.set('newRegion', '');
this.set('newLicenseType', '');

license.save();
},
}


My problem (as noted by 'What do I do here?') is in converting the licenseTypeId I retrieve from the select input back into a licenseType model object. The code above leaves licenseType empty, so when I submit it to my server it inserts the record with a NULL licenseType.


I've tried using and several other permutations of that same theme, but I have not hit upon the correct answer.


Thank you for your help.





deprecation warning on ember data models

Just updated to ember v1.12.0-beta.1 and ember-data v1.0.0-beta.16. I'm getting the following deprecation warning on the fields in my models:



DEPRECATION: Using the same function as getter and setter is deprecated. See http://ift.tt/19s4HeN for more details.


The Ember inspector Deprecations view is pointing to all my models. So I basically get one deprecation error per line in my model. Here is an example model:



import DS from 'ember-data';

export default DS.Model.extend({
userid: DS.attr('number'),
unitid: DS.attr('number'),
log: DS.attr('string'),
name: DS.attr('string'),
start_date: DS.attr('date'),
end_date: DS.attr('date'),
duration_mins: DS.attr('number')
});




Ember - Routes / Nesting / Params/ HasMany

I'm still learning Ember and I'd like some help to solve this problem...


I have a simple library app with authors and books. I'd like to add an "add book" link to my author view template And I want this link to render a new book template, with the book.author defined. But I want it to be displayed in the main outlet


My Models:



App.Author = DS.Model.extend({
name: DS.attr('string'),
about: DS.attr('string'),
picture: DS.attr('string'),
books: DS.hasMany('book', {async: true})
});

App.Book = DS.Model.extend({
title: DS.attr('string'),
isbn: DS.attr('string'),
summary: DS.attr('string'),
isAvailable: DS.attr('boolean'),
featured: DS.attr('boolean'),
picture: DS.attr('string'),
author: DS.belongsTo('author', {async: true})
});


Here are my routes:



App.Router.map(function () {

this.resource('books', function () {
this.route('edit', {path: '/:book_id/edit'});
this.route('view', {path: '/:book_id'});
});

this.resource('authors', function () {
this.route('new');
this.route('edit', {path: '/:author_id/edit'});
this.route('view', {path: '/:author_id'}, function (){
this.resource('books', function(){
this.route('new');
});
});
});
});


URL will be like authors/4/books/new


With this nested routes, I can only display my books.new template inside the authors outlet. I can not display it in the main outlet.




The other way I thought was using thoses routes



App.Router.map(function () {

this.resource('books', function () {
this.route('new');
this.route('edit', {path: '/:book_id/edit'});
this.route('view', {path: '/:book_id'});
});

this.resource('authors', function () {
this.route('new');
this.route('edit', {path: '/:author_id/edit'});
this.route('view', {path: '/:author_id'});
});
});


and using QueryParams


URL will be like books/new?author_id=4


The template is displayed right, but I could not bind my new book record to its author.


What is the "ember right way" to make it works?, could you give me an working example?


Thanks.





EmberJS - Using a custom layout/template instead of applcation.hbs

as a Rails-Developer who started messing around with EmberJS one week ago, I want to know if it's possible to use custom layout instead of the provided applictaion.hbs? Like we do it in rails:



class MyController < ApplicationController
layout :resolve_layout

# ...


Thanks in advaced, Hendry I.





Ember rails Assertion Failed: template must be a function

I'm trying to set up a rails project with ember and i followed the steps on the ember-rails github page.


Gemfile:



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


I have now created a basic structure with a router and some hbs templates. When I check Ember.TEMPLATES the templates are there but when ember wants to render them I get this error:



Uncaught Error: Assertion Failed: template must be a function.
Did you mean to call Ember.Handlebars.compile("...") or specify templateName instead?


I've looked around and tried multiple possible solutions to no avail. Does anyone who knows how to get the templates to compile properly with ember-rails?





Handlebars helper not getting value of variable

I'm Trying to create a custom "if_eq" helper for a Handlebars / Ember application. The helper is called with the following syntax: {{#if_eq item.name 'bob'}}, but is receiving 2 string values to compare (literally 'item.name' and 'bob'), instead of the value of "item.name" in the context it was called. Wondering what I might be doing wrong. Thanks!


Relevant code snippets are listed below and also created a jsbin to illustrate the problem here


Helper Code



Handlebars.registerHelper('if_eq', function(a, b, opts) {
console.log( "Comparing ", a, b);
if(a == b)
return opts.fn(this);
else
return opts.inverse(this);
});


Template code



<ul>
{{#each item in model}}
{{#if_eq item.name 'bob'}}
<li>We have a bob here!</option>
{{else}}
<li>A non-bob</li>
{{/if_eq}}
{{/each}}
</ul>




Web app using Ember.js

I am making a web app for a photographer, as a http://ift.tt/Y0UwaS. I started from basic html+css+jquery. I have a front page with hidden menu and menu page. But, it seems like I need to make it with ember.js, since data will be loaded dynamically. Can you please help on how to proceed with ember. I went through tutorials, but kinda cant get it right(. I never used it before. Thank you!


Here is link of first page on codepen: http://ift.tt/19rEmgI



<html>


<head>
<title>Timur Uteshbekov Studio</title>
<link href='http://ift.tt/19rEoVW' rel='stylesheet' type='text/css'>
</head>


<body>
<header>
<h1>Timur Uteshbekov</h1>
<h2>Studio</h2>
</header>
<a id="nav-toggle" href="#"><span></span></a>

<div class="content">
<ul class="bmenu">
<li><a href="#">About</a></li>
<li><a href="#">Illustrations</a></li>
<li><a href="#">Photography</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">Contact</a></li>
</ul>

</div>
<script type="text/javascript" src="http://ift.tt/ruu4ao"></script>

</body>
</div>
</html>

$(document).ready (function() {
$('.bmenu').hide();
$('#nav-toggle').click(function() {
$('header').fadeOut('slow');
$('.bmenu').fadeIn('slow');
this.classList.toggle("active");
});
});




How to specify async belongsTo/hasMany relationships in emberfire/emder-data?

I am very new at Ember/ED/EmberFire so apologies if this is a trivial question. I am able to save records to Firebase but I am unable to specify relationships to those records in my controller. I am using



DEBUG: Ember : 1.10.0
DEBUG: Ember Data : 1.0.0-beta.12
DEBUG: Firebase : 2.2.3
DEBUG: EmberFire : 1.4.3
DEBUG: jQuery : 1.11.2


I have a model as such:



var Patient = DS.Model.extend({
lastName: DS.attr('string'),
firstName: DS.attr('string'),
encounters: DS.hasMany('encounter', {async: true})
});

var Encounter = DS.Model.extend({
dateOfEncounter: DS.attr('string'),
patient: DS.belongsTo('patient', {async: true})
});


I am simply trying to specify the patient that my newly created encounter object is associated with. This is my controller:



actions: {
registerEncounter: function() {
var newEncounter = this.store.createRecord('encounter', {
dateOfEncounter: this.get('dateOfEncounter'),
patient: this.store.find('patient', '-Jl8u8Tph_w4PMAXb9H_')
});

newEncounter.save();

this.setProperties({
dateOfEncounter: ''
});
}
}


I can successfully create the encounter record in Firebase, but there is no associated patient property. All I get is


http://ift.tt/1ORmrkk





How to refresh a model after a request to API


enter code here
actions:{
deleteWorklog: function( worklogId ){
var model = this.get('model.logs');
var data = { auth_token: this.get('local_data').user_token };
Ember.$.ajax({
method: "DELETE",
url: this.get('url') + "/" + worklogId,
headers: { 'X-Api-Token': data.auth_token }
}).then(function(data){
//how do i do it?
})
}
}


I'm blocked after the request, i need to refresh my model but i've to do cmd + R to see the change, is there a method re-call the model or something like that?


Thank you for your time!





Get Current URL in ember JS

I'm trying to get the current url in emberJS but I cannot. I am doing this:



App.Route = Ember.Route.extend(Em.I18n.TranslateableProperties, {
actions: {
didTransition: function (transition) {
this._super();
console.log(window.location.href);
console.log(this.get('router.url'));
}
}
});


I used to use didTransition because I need to know the current URL when all elements are load. For example: If I am in home(/home) page and navigate to contact page(/contact-page), I want to know the url '/contact-page'.


If I use window.location.href works, but not always. I thought that didTransition was called when everything else is finished, but not.


Why?


Thanks in advance





Display belongsTo category for a product

I render a product table at http://localhost:4200/products which should include the category of each product but doesn't.


Screenshot of the product table.


The template code:


app/templates/products/index.hbs



[...]
<tbody>
{{#each product in model}}
<tr>
<td>
{{product.name}}
</td>
<td>
{{product.category.name}}
</td>
[...]


Why doesn't {{product.category.name}} display the product.name? How can I fix it?


The Application



ember new shop
cd shop
ember install:addon ember-cli-scaffold
ember g scaffold product name:string
ember g scaffold category name:string
ember g adapter application
ember g http-mock products
ember g http-mock categories


app/adapters/application.js



import DS from 'ember-data';

export default DS.RESTAdapter.extend({
'namespace': 'api'
});


app/models/product.js



import DS from 'ember-data';

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


app/models/category.js



import DS from 'ember-data';

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


server/mocks/products.js



module.exports = function(app) {
var express = require('express');
var productsRouter = express.Router();

productsRouter.get('/', function(req, res) {
res.send({
'products': [
{"id":1,"name":"Orange"},
{"id":2,"name":"Banana"},
{"id":3,"name":"Potato"}
]
});
});
[...]


server/mocks/categories.js



module.exports = function(app) {
var express = require('express');
var categoriesRouter = express.Router();

categoriesRouter.get('/', function(req, res) {
res.send({
'categories': [
{"id":1,"name":"Fruits","products:":[1,2]},
{"id":2,"name":"Vegetables","products:":[3]}
]
});
});
[...]




Ember.js: Related model empty when using multiple models in a route

Really stumped on this one..hopefully I can explain the issue clearly.


I'm loading multiple models in the EditRoute and displaying data from the artist model perfectly. Artist Genres is a related model and also displays fine in the template.


Model:



var attr = DS.attr,
belongsTo = DS.belongsTo,
hasMany = DS.hasMany;

App.Artist = DS.Model.extend({
description: attr(),
groupname: attr(),
artist_genre: hasMany('artistGenre', { embedded: 'always' }),
});

App.ArtistGenre = DS.Model.extend({
name: attr(),
});

App.Genre = DS.Model.extend({
name: attr(),
displayorder: attr(),
})


Route:



App.EditRoute = Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
artist: this.store.find('artist',App.CurrentProfile.id),
genre: this.store.find('genre'),
});
},
setupController: function(controller, model) {
controller.set('artist', model.artist);
}
});


Controller:



App.EditBasicInfoController = Ember.ObjectController.extend(App.ArtistEdit,{
artist: null,
genre: null,
});


Template:



List OF Artist Genre (Related model):
{{#each genre in artist.artist_genre}}
- {{genre.name}} </br >
{{/each}}

<div class="row">
{{input value=artist.groupname placeholder="Enter Artist name"}}
</div>


The issue appears when I set the controller "genres" property that I loaded in the route model().



App.EditRoute = Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
artist: this.store.find('artist',App.CurrentProfile.id),
genre: this.store.find('genre'),
});
},
setupController: function(controller, model) {
controller.set('artist', model.artist);
controller.set('genre', model.genre);
}
});


The artist data (artist.groupname) still works properly but the artist genre (related model artist.artist_genre) data is now empty in the template. Why would setting an additional controller property make the related model empty in the template? I still see the actual data in ember inspector.





sort elements out on click (Ember.js)

I have a component that display a bunch of data with different status.Each data is wrap up on different div.I also have a menu bar that suppose to show ONLY the elements that are bind with that action. I want to be able to hide elements that are not associate with onclick action.


THANK YOU GUYS



<script type="text/x-handlebars" id="new">
<section>
<ul>
<li {{action 'showAllLeads'}} {{bind-attr class="allLeadsTabIsActive:activeMenuTab"}}>
<a href="#">
<i class="icon-menu"></i>ALL
</a>
</li>
<li {{action 'newLeads'}} {{bind-attr class="newLeadsTabIsActive:activeMenuTab"}}>
<a href="#">TWO</a>
</li>
<li {{action 'activeLeads'}} {{bind-attr class="activeLeadsTabIsActive:activeMenuTab"}}>
<a href="#">
<i class="icon-right-open"></i>ONE
</a>
</li>
</ul>
</section>
</script>


App.NewController = Ember.Controller.extend({
actions: {
showAllLeads: function(){
this.send('resetTabs');
this.set('allLeadsTabIsActive', true);
},

activeLeads: function(){
this.send('resetTabs');
this.set('activeLeadsTabIsActive', true);
},
newLeads: function(){
this.send('resetTabs');
this.set('newLeadsTabIsActive', true)
},
resetTabs: function(){
this.set('allLeadsTabIsActive', false);
this.set('newLeadsTabIsActive', false);
this.set('activeLeadsTabIsActive', false);
},
}
})




Ember - Route event for attempting transition to active route

I'm trying to make sure my side menu closes anytime someone attempts to transition to any route, even the same route the user is already on.


This doesn't fire on the attempt to the same route, just on all others:



var ApplicationRoute = Ember.Route.extend({
actions: {
willTransition: function(){
// Close menu always
//this.controllerFor('application').set('menuOpen', false);
console.log('willTransition fired!');
}
}
});


Any ideas?





Concatenation string with variable in emblem.js

I need in Emblem.js to transmit to i18n helper concatenated string constant with variable value, How can i do it?



each item in model.items
div
t "dict.{{item}}"


returns error



Missing translation for key "dict.{{item}}"




EmberData unloadAll doesn't work on IE8. Works on Chrome/FireFox

Thanks in advance for the help !


I am having a problem refreshing my model on IE8. (Works on Chrome Chrome and Firefox) I run this code to refresh my model with a request to the database using my adapter. Through this command I am unloading the data of the model and reloading it again to display it to the user:



var type = self.controller.get('model').type;

this.controller.get('model').get('store').unloadAll(type);
this.controller.get('model').get('store').fetchAll(type);


No Javascript errors. I have looked for a solution but not a clue about it. Any idea?


Thanks !





In an Ember handlebars template, ".active" styling does not stick

I am working on an Ember project and noticed some weird behavior. I am using {{link-to}} helpers to build all my in-app links, and when I am on the correct page the navigation links correctly have an active class assigned.


What I noticed, however, is that the styling only persists until I click on the page. When I click on anything else, the styling goes away, however the class seems to remain.


Is there anything that I am possibly missing? I am pretty new to Ember, and most of my work has been on web pages that have little AJAX content, so it is entirely possible I am missing something super simple.


Thank you,





Ember Documentation understanding - Model linked to Template or not?

I'm learning Ember right now and i'm beeing a bit confused because of the Docu of Ember and the getting started example. In the Documentation it says:



In Ember.js, templates get their properties from controllers, which decorate a model.



And



Templates are always connected to controllers, not models.



But after doing the getting started guide i'm not sure if this is correct.


I've uploaded the finished TodoMVC app here: http://ift.tt/19nWSqs


In the Index.html you'll find this template:



<script type="text/x-handlebars" data-template-name="todos/index">
<ul id="todo-list">
{{#each todo in model itemController="todo"}}
<li {{bind-attr class="todo.isCompleted:completed todo.isEditing:editing" }}>
{{#if todo.isEditing}}
{{edit-todo class="edit" value=todo.title focus-out="acceptChanges" insert-newline="acceptChanges"}}
{{else}}
{{input type="checkbox" checked=todo.isCompleted class="toggle"}}
<label {{action "editTodo" on="doubleClick"}}>{{todo.title}}</label>
<button {{action "removeTodo"}} class="destroy"></button>
{{/if}}
</li>
{{/each}}
</ul>
</script>


My question refers to the 3rd Line:



{{#each todo in model itemController="todo"}}


In my opinion there is the model directly connected with the template isn't it?


Or is there a default Controller like the docu mentioned here?



For convenience, Ember.js provides controllers that proxy properties from their models so that you can say {{name}} in your template rather than {{model.name}}.






Ember.js call function after template is rendered

I am building an app using Ember.js that will display a map. In order to display the map, I need to call some JS after the rendering of the map div.


structure layout:



- app/router.js
--> this.route('map')
- app/controllers/map.js
--> build function
- app/templates/map.hbs
--> <div id="map"/>


In jquery I would use the document ready to launch my JS code:



$( handler )



I'm newbie in ember so I would apreciate any help. I went through the documentation yesterday but I did not quite get all the plumbing yet.





How to save several similar models in the hasMany relationship?

jsbin example


Ember-data does not store models with the same id in a hasMany relation.


How to organize the work hasMany so that can save several similar models?





dimanche 29 mars 2015

Access-Control-Oigin within Slim Framework and Ember.js

After reading many questions/answers I decided to post. I think Slim Framework - jQuery $.ajax request - Method DELETE is not allowed by Access-Control-Allow-Methods sums up most of the information I've found and tried out.


I'm using MAMP with PHP 5.6 for development but the production environment will most probably be a shared host. I'm also using ember.js


When ember does a POST request I get the Access-Cross-Origin message:



XMLHttpRequest cannot load http://foo.bar/ . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.



I understand that settings the appropriate headers on the server would solve the issue but I do not know when to do it. What I currently do in the Slim framework is:



header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');

$app->options('/(:name+)', function() use($app) {
$response = $app->response();
$app->response()->status(200);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});


However, I've checked Ember.js requests and it is not requesting OPTIONS and thus the correct headers are not set.


If I set the headers in an individual route of Slim then it works correctly. But I do not want to set the headers on each route, one by one.


What can I do to set the headers for all routes?





Error when querying for records in ember.js

I'm trying to retrieve a value from a model from another page in the model() function of a route. This works fine when I look up the record by ID:



self.store.find('page', 1).then(function(page) {
self.controllerFor('edit').set('title', page.get('text'));
});


However, when I try to use a query to get this, I get a Error: Assertion Failed: Error: More context objects were passed than there are dynamic segments for the route: error message from line 14261 of ember.js.


Here's the code that causes the issue:



self.store.find('page', { section: params.section }).then(function(page) {
self.controllerFor('edit').set('title', page.objectAt(0).get('text'));
});


I've ensured that the model has the section property and that params.section is being set properly from the route. What would be causing the error?





How can I change query params without a controller in Ember?

I have a callback from a library which returns data that I need to use to update query params. The problem is that this callback has no reference to any Ember structure or data. Is there a way to get access to the current controller to do controller.set(param, value) or perhaps a way of doing Ember.transitionTo({param: value})?





How should I handle page refreshes in EmberJS?

As I understand from the EmberJS Guide to Routing, you should specify the model you want a route to load in the Route's model hook. The model hook may return a promise, and if it does, the route will pause until the promise resolves.


Therein lies my problem: this approach works fantastically under normal use cases (user triggers a transition from any other route into the route in question.) The problem arises if the user is currently at the route in question.


If the user triggers a page refresh (using the browser's refresh button, or ctrl+r or whatever other trigger there might be, the promise in the model hook causes the user to sit at a blank white page until that promise returns. In large dataset cases, this can be a handful of seconds, which does not make for a great user experience.


So, how do I resolve this issue?


The only solution I have developed is to trigger the data load in the route's activate hook, and manually set the controller's model when that promise returns. I don't like doing this, because I'm circumventing the entirety of Ember's model framework.


I would like the application template to render before the model hook hangs the page, at a bare minimum. Any guidance on how to resolve this would be greatly appreciated.


In case the context is necessary: as the tags imply, I am using Ember-Data. I'm utilizing the RESTAdapter almost entirely out-of-the-box, unmodified.





Ember js checkbox value

I'm new to Ember and this drives me crazy. I've read checkbox documentation several times but I still don't understand. I have form for adding employees and need to be able to choose employee's education level. I know that should be the select box but task says checkboxes. So, I have few checkboxes and I should be able to pass values from checked ones to action handler and to save them but i don't know how to assign value to checkbox(from docs I got that i should use checked instead value but don't know how).


Thanks in advance and sorry for noob question





How to proxy methods on the prototype using ObjectProxy in ember.js?

I've got a simple ObjectProxy that I'd like to make calling methods on easy(er). For example, the object I plan to "proxy" has a method named foo and bar - they will not be available directly causing me to do something like this.



this.get("model").get("content").foo();
this.get("model").get("content").bar();


Instead I'd much prefer if foo and bar acted like they were on the object



this.get("model").foo();
this.get("model").bar();


I can make this happen (long hand) by hard coding the foo and bar methods on the ObjectProxy itself - then pulling content and invoking the method manually w/ apply like so



return Ember.ObjectProxy.extend({
content: function() {
var filter_value = this.get("filter_value");
return this.get("source").filterBy("id", filter_value).objectAt(0);
}.property("source.[]"),
foo: function() {
var content = Ember.get(this, 'content');
return content["foo"].apply(content, arguments);
},
bar: function() {
var content = Ember.get(this, 'content');
return content["bar"].apply(content, arguments);
}
}).create({
filter_value: id,
source: store.find(type)
});


If instead I wanted to proxy each "method" like this - how can I set the prototype in a way that won't hurt the tree that ember has built up already?





Where to put simple functions in an Ember project

So... while I'm learning all of this Ember CLI world - things are going well. However, I can't seem to understand where all the normal ol javascript utility stuff I use on a normal project goes... for example --- this sticky footer thing... where do I put this? It's blowing my mind...





// dynamic weighted footer
var watchFooter = function() {

// define the height variable
var footerHeight;

// get the height of the footer and store it in 'footerHeight'
footerHeight = $('.container.footer').outerHeight();

// Share that info with the dependent elements
$('.footer-buffer').css('height', footerHeight);
$('.container.master').css('margin-bottom', -(footerHeight));

};

// run on window resize - and on load
$(window).resize(watchFooter).trigger('resize');




Creating multiple to-dos with Ember example

I'm trying to create multiple to-do lists using Ember example. I tried to extend it using this, but I'm having some trouble blending into the Ember to-do example.


I have TodosRoute and TodosIndexRoute making the to-do list work, and I'm creating model 'stack' to group individual todos.


Here's my router.js



Todos.Router.map(function() {

this.resource('todos', { path: '/todos' }, function () {
// additional child routes will go here later
this.route('active');
this.route('completed');
});
this.resource('stacks', {path: '/'}, function(){
this.route('stack', {path: '/stack/:stack_id'});
});
});




Todos.TodosRoute = Ember.Route.extend({
model: function() {
return this.store.find('todo');
}
});




Todos.TodosIndexRoute = Ember.Route.extend({
model: function() {
return this.modelFor('todos');
}
});




Todos.StacksRoute = Ember.Route.extend({
model: function() {
return this.store.find('stack');
}
});



Todos.StacksStackRoute = Ember.Route.extend({
model: function(params){
return this.store.find('stack', params.list_id);
}
});



Todos.TodosActiveRoute = Ember.Route.extend({
model: function(){
return this.store.filter('todo', function(todo) {
return !todo.get('isCompleted');
});
},
renderTemplate: function(controller) {
this.render('todos/index', {controller: controller});
}
});




Todos.TodosCompletedRoute = Ember.Route.extend({
model: function() {
return this.store.filter('todo', function(todo) {
return todo.get('isCompleted');
});
},
renderTemplate: function(controller) {
this.render('todos/index', {controller: controller});
}
});


And my stacks_controller.js



Todos.StacksController = Ember.ArrayController.extend({
actions: {
createNewStack: function() {
var stack = this.store.createRecord('stack');
var _id = stack.get('id');
stack.set('title', 'new stack ' + _id);
stack.save();
}
}
});


Model.js



Todos.Todo = DS.Model.extend({
title: DS.attr('string'),
isCompleted: DS.attr('boolean')
});



Todos.Stack = DS.Model.extend({
title: DS.attr('string'),
todos: DS.hasMany('todo')
});


And then some bits from template



<button {{action "createNewStack"}} class="btn btn-default navbar-btn navbar-left">+ stack</button></a>

<section id ="list">
{{#each}}
{{#link-to 'stack' this}}
<li>{{title}}</li>
{{/link-to}}
{{/each}}
</section>


It would be great if you could help me think about how I can structure the stack-todos relationship. I thought about making todos a child route of stack (and todo is already a child route of todos), then it would be a three layered relationship, which I don't know how to build.


Thanks a ton!





Is there a convention for brunch.io style 'skeletons' - for Ember / CLI?

I'm getting to a point with Ember CLI where I need to follow a long list of things at the beginning of every project.


add stylus, add this, add that -- copy and paste in the content security policy ---- partial out the head ... drag over some styles from bower...


I am thinking about a branch of a base install... with a git ignore or something... but I'm just wondering if there is a convention and I'm just missing it... like, instead of 'skeleton' it's called 'hampster-wheel' or something.


Any help to keep the refactoring down would be greatly appreciated. : )





Ember.js: Custom Slug URLs not working after refresh

I'm trying to setup custom slug URLs for my page models in Ember. They're working so far when I call the links from the index page. What's not working however, is that if I refresh the page with one of my custom URLs, the model is not found anymore and I'm being redirected to my "not found" page. So maybe it's a "timing" problem and I should load the models in a different way?


I followed the tutorial in the Ember guides and checked this question on StackOverflow but I still cannot get it to work.


Here's my source code snippet so far: http://ift.tt/1G50TN9


Thank you very much in advance - every help/comment is appreciated.





How to upgrade the Ember version in an Ember CLI application?

Assuming I created this Ember application last week:



ember new shop
cd shop
ember install:addon ember-cli-scaffold
ember g scaffold product name:string


The console tells me that this application uses Ember 1.10.0:


Screenshot of the JavaScript Console.


How can I upgrade this Ember application to Ember version 1.11.0?





Emberjs dropdown is not displaying text

My emberjs dropdown is not displyaing the text I want it to display rather than that its displaying enter image description here


But the value of each option is set correctly enter image description here


This view has a model created using json object as given below



App.CHART_CATEGORIES_JSON = [
{
"id":0,
"name": "Topics",
"desc": "Each topics analysis based on the previous course and current course. Will give you insight about difficulty level of chapters and etc.",
"subtype":[
{
"id":5,
"name":"Popular Topics",
"desc": "It will help to figure out what are the popular topics in this course. This if fully based on the data of previous course",
"filter":{
"name":"name",
"desc":"desc",
"callback":"callback"
}
},
{
"id":1,
"name":"Popular Topics2",
"desc": "It will help to figure out what are the popular topics in this course. This if fully based on the data of previous course",
"filter":{
"name":"name",
"desc":"desc",
"callback":"callback"
}
}

]
}]
App.AnalyticsRoute = Ember.Route.extend({
model : function() {
return App.CHART_CATEGORIES_JSON;
}
})


Code for the template is



{{#view App.AnalyticsMainView}}
{{#each}}
<div>
<div class="chartCategory">
<div class="chartCategoryDetails">
<div class="chartSubcategorySelect">
<label>Subcategories :
</label>
{{view Ember.Select
content=subtype
optionValuePath="content.id"
OptionLabelPath="content.name"
}}
<div class="filterCriteria">
</div>
</div>
</div>
<div class="chartCategoryGraph">
</div>
</div>
</div>
{{/each}}
{{/view}}




Ember: this.get from controller returns old data not the current data that is bound in a input

JsBin http://ift.tt/1G4z4Vf


I am having an issue where a value that is bound to input fields is not read in the same as it is currently set in the text fields.


I have a component I want to use as a modular edit all over my application. The only thing this component needs passed in is what ever the current business is. From there all the logic for the form is handled within the component, including passing it to the server.


I am trying to have a feature where the (save/reset) buttons only appear when the user has modified the business. When you pass in the currentBusiness all the fields are properly populated but if you edit one field then press Save, then from the save Action I do, this.get('currentBusiness.data') to get the updated fields and pass it as the data field of my ajax call. But this.get('currentBusiness.data') returns the values that were initially passed into the component and not the updated fields from the text boxes.


However currentBusinessO which observes all the editable fields triggers when ever a field is edited and that is also using this.get('currentBusiness')


Unfortunately Ember is the first framework I have used and it has quite the learning curve.


Ember: v1.9.0-beta.3


Ember-data: v1.0.0-beta.11


Open jsbin, click Set, edit one field, press save. I dump the contents of currentBusiness to console and it doesnt match the edited fields.


Thanks for the help.





samedi 28 mars 2015

How to link or transition to a dynamic segment route from another dynamic segment route in ember?

I can't seem to use transitionToRoute from the url .../product/1 to go to the url .../product/2. It works just fine from the "parent" products resource route, but only once when going from "sibling".


I'm using transitionToRoute in an observer that listens for a property to change upon clicking. This entity that is clicked is in the parent "products" route. So when I'm at a singular product route, and click the products clickable thing, it doesn't compute properly.


I'm also using fixtures for my data!


Why not just use link-to? Well I'm simplifying my situation for the sake of brevity, but I'm trying to make a fancier UI that is based on observing a property that is changed (that property is a computed property of other properties that get changed individually with each clickable div)


I've read about the model not being fired, how i need to use the setupController hook. And if I'm using a slug instead of an id, the serializer.


I've played around with it, but I can't seem to get things working properly. I imagnie an example solution would be simple and short, but I can provide code and context if needed.


What the hell, here is some boilerplate code: (ES6 code ommitted for brevity and readability)


router



Router.map ->
@resource 'products', ->
@resource 'product { path: '/:type' }, ->
@route 'description'


products route



ProductsRoute = Ember.Route.extend
setupController: (controller, model) ->
controller.set('model', DS.store.findAll('product'))


products controller



PersonalitiesController = Ember.ArrayController.extend
factorOne: 'q'
factorTwo: 'a'

actions:
toggleFactorOne: ->
if this.get('factorOne') == 'q'
this.set('factorOne', 'w')
else if this.get('factorOne') == 'w'
this.set('factorOne', 'q')

toggleFactorTwo: ->
if this.get('factorTwo') == 'a'
this.set('factorTwo', 's')
else if this.get('factorTwo') == 's'
this.set('factorTwo', 'a')

type: (->
this.get('factorOne') + this.get('factorTwo')
).property('factorOne', 'factorTwo')

typeChanged: (->
this.transitionToRoute('product', type)
).observe('type')


product model



Product = DS.Model.extend
type: DS.attr('string')
description: DS.attr('string')

Product.reopenClass
FIXTURES: [
{ type: 'qa', description: 'stuff'}
{ type: 'qs', description: 'stuff'}
{ type: 'wa', description: 'stuff'}
{ type: 'ws', description: 'stuff'}

]


Now for the singular product stuff


product route



ProductRoute = Ember.Route.extend
model: DS.store.query('product', params.type)

setupController: (controller, model) ->
modelCollection = DS.store.query('product', params.type)
controller.set('model', modelCollection.then (pers) ->
pers.get('firstObject'))

serialize: (product) ->
{ product: product.get('type') }


^ I think the product route is where the most problems lie.


product route


(nothing special here. empty)


Product adapter



ProductAdapter = DS.FixtureAdapter.extend()


I guess it wasn't that short. I feel I may be missing something with the model hooks, the code within the setupController hook, or serializing.


Thank you. Again, the symptoms are:


1) the url doesn't update when transitioning from a product route to another product route that has a different dynamic segment, only the first time.


2) the model is not set for the product route or from the product/description route.





Correct way to access current application configuration

I added some configurations to myapp/config/environment:



if (environment === 'development') {
ENV.APP.AuthURL = 'http://localhost:5000/';
}


Now, to access this configuration should I use some method or directly accessing window.Myapp?





ember-cli 0.2.1 - generated addon test cannot find mixin

I have recently upgraded ember-cli 0.2.0 to 0.2.1 and I ran the following command to generate a mixin:



ember g mixin listener


The generate file was place in addon/mixins/listener.js.


The generated test looks like this:



import Ember from 'ember';
import ListenerMixin from '../../../mixins/listener';
import { module, test } from 'qunit';

module('ListenerMixin');

// Replace this with your real tests.
test('it works', function(assert) {
var ListenerObject = Ember.Object.extend(ListenerMixin);
var subject = ListenerObject.create();
assert.ok(subject);
});


The test fails with the following error message:



Could not find module dummy/mixins/listener imported from dummy/tests/unit/mixins/listener-test



My mixins should be in /addons/ and not /app/


What do I need to change for the tests to find the module?


When I upgraded from 0.2.0 to 0.2.1 I followed the docs for upgrading and ran all the steps in the docs


but this line:



ember init


Returned this error which I assume is something to do with it:



Generating an addon in an existing ember-cli project is not supported.






Configure CSP in an Ember CLI application which uses http-mock

I'm using http-mock with Ember CLI as suggested on http://ift.tt/1Osat0p. I understand the basic concept of CSP but I don't understand the configuration of it within an Ember CLI application.


How can I configure my application to either accept requests to localhost:4200/api/ to avoid this during development:



Content Security Policy violation: {"csp-report":{"document-
uri":"http://localhost:4200/products","referrer":"","violated-
directive":"style-src 'self'","effective-directive":"style-
src","original-policy":"default-src 'none'; script-src 'self'
'unsafe-eval' localhost:35729 0.0.0.0:35729; font-src 'self';
connect-src 'self' ws://localhost:35729 ws://0.0.0.0:35729
http://ift.tt/1HbOW6Y; img-src 'self'; style-src
'self'; media-src 'self';
report-uri http://ift.tt/1HbOW6Y;","blocked-uri":"",
"source-file":
"chrome-extension://alelhddbbhepgpmgidjdcjakblofbmce",
"line-number":1,"column-number":20481,"status-code":200}}




How to change controller property from component?

I have a property in the controller. I want to use a component to update that controller property. The usual component parameter passing works when I'm using a text field like the guides say, but in my case, I'm changing the value in code, not input fields. The binding seems to be broken.


What method similar to propertyDidChange() or notifyPropertyChange() should I use to accomplish this? Can you also provide a simple example so I know WHERE to make that method call?





vendredi 27 mars 2015

Ember action syntax differences

I've read the documentation about the actions hash, but in every example I can find, people leave off the action: when observers are used.


like this one:


http://ift.tt/197C1aB


They favor the action name direction under the extend definition just like how properties are defined, and an anonymous function is defined wtihin that property.


My question is what are the differences between these two ways?


Does it not bubble up if you don't use actions:?


If you don't use actions:, does it not bubble up to routes?


And most importantly, what does this mean for using observers?


http://ift.tt/1CuAib5





Add Controller to needs with Mixin

I'm trying to create a mixin for my controllers that use a lot of the same functions, but I need to make sure all of the controllers have access to some basic controllers too. I do this currently by adding the to needs.



// mixins/item.js

import Ember from 'ember';

export default Ember.Mixin.create({
needs: ['application']
});


The issue is that many of the controllers have additional controllers that are included with needs. From what I've tested, the needs in the controllers overrides what's set in the mixin.


Is there anyway to merge the needs?





CSS for ember view tag

I would like to set the z-index for an ember view within the view class but ember keeps throwing the error:



DEPRECATION: Dynamic content in the `style` attribute is not escaped and may pose a security risk.


An abbreviated version of my class is this:



App.ModalComponent = Ember.Component.extend({
layoutName: 'components/modal',
classNames: ['modal', 'fade'],
attributeBindings: ['style'],
style: function() {
return 'z-index:131071';
}.property()
});


Do any more seasoned ember gurus know a more appropriate way to set custom style on an Ember View? Thanks!





using rails backend, best practice to develop ember frontend in rails or out?

I'm just about to start my first "real" ember.js project but I'm seriously lacking in best practices experience. One thing in particular I'm wondering about is, if I'm using a rails backend, is it better to develop within the rails distro using ember-cli-rails or just developing the front and back ends completely separately?


I first I thought it was a no-brainer, just stuck ember in rails and go. But I'm finding it a clunky experience compared to developing each separately. The automatic reloading isn't smooth (which I really enjoy when it works), server tail is a little chaotic having two players logging there, and I've only been at it a few minutes, I'm afraid of what I might find later, especially when testing.


I'm also wondering, that besides the clunkyness, the separation of concerns of back end and front end might have more benefits than sticking the two together.





Can't mock return from ember-data destroyRecord for testing

I'm trying to test deleting a user account using fauxjax and ember-data. I am getting this error back: Assertion Failed: Expected an object as 'data' in a call to 'push' @model:user: , but was undefined


I can't find what to do in this case with testing. Here is my test and code:


Test:



test('delete user account', function(assert) {
loginUser();
$.fauxjax.new({
request: {
type: 'GET',
url: ENV.apiDomain.concat('/users/1'),
dataType: 'json',
headers: {Authorization: 'abc123'}
},
response: {
content: {}
}
});

visit('/account/delete');

click('#yes');
andThen(function() {
assert.equal(currentPath(), 'index');
});
});


and my action:



confirmDelete: function() {
var controller = this;
this.store.find('user', localStorage.userId).then(function(user){
user.destroyRecord();
controller.send('logout');
});
},




How to import assets from a nested addon

How do I go about importing assets from a nested addon in a consuming application?


I currently have an addon, addonA, that has addonB as a dependency. When running the dummy app for addonA, addonB's CSS is imported correctly. However, when including addonA in an Ember app, only addonB's CSS is added to the vendor.css file.


Ember App package.json



{
"name": "my-app",
"version": "0.0.0",
"description": "My App.",
"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",
"connect-restreamer": "^1.0.1",
"ember-cli": "0.2.0",
"ember-cli-app-version": "0.3.2",
"ember-cli-babel": "^4.0.0",
"ember-cli-content-security-policy": "0.3.0",
"ember-cli-dependency-checker": "0.0.8",
"ember-cli-htmlbars": "0.7.4",
"ember-cli-ic-ajax": "0.1.1",
"ember-cli-inject-live-reload": "^1.3.0",
"ember-cli-qunit": "0.3.9",
"ember-cli-uglify": "1.0.1",
"ember-data": "1.0.0-beta.15",
"ember-export-application-global": "^1.0.2",
"express": "^4.12.3",
"glob": "^4.5.3",
"morgan": "^1.5.2",
"addonA": "some/location"
}
}


addonA index.js



/* jshint node: true */
'use strict';

module.exports = {
name: 'addon-a',

included: function (app) {
this._super.included(app);

app.import('vendor/addon-a/addon-a.css');
}
};


addonB index.js



/* jshint node: true */
'use strict';

module.exports = {
name: 'addon-b',

included: function (app) {
this._super.included(app);

app.import('vendor/addon-b/addon-b.css');
}
};