jeudi 30 juin 2016

Ember - Adding dynamic attributes to model inside serializer

How can we add dynamic attributes to model inside serializer.

I have created a model entity. I need this model for different type of entities. So for now I created an attribute type to identify which type of entity is that and the remaining attributes I need to create dynamically based on the response in serializer response handler. Is it possible?

entity.js

export default DS.Model.extend({
   type: DS.attr('string')
});

entity.js(Serialaizer)

export default DS.RESTSerializer.extend({
   normalizeFindAllResponse(store, primaryModelClass, payload) {
      var payloadData = {};
      payloadData.data = [];    
      payload.forEach(function(model) {
          // I will get the entity type and other attributes here
          // How can I define new attribute for model entity here
      }
   }




How to change default findAll endpoint

I'm doing a app that have several users, and each user hasMany mappings.

So, i'm not using JSONAPAdapter because i'm working with strongloop, so i'm using RESTAdapter with JSONSerializer.

All my mappings routes in the backend work like this:

GET        /users/{userId}/mappings
POST     /users/{userId}/mappings
PUT       /users/{userId}/mappings
DELETE /users/{userId}/mappings
GET        /users/{userId}/mappings/{mappingId}
.....

So, i want get all mappings from the logged user. How to do so? I'm trying like this:

this.store.query('mapping', {
   userId: userId
});

But doesn't work at all. Is trying to get the data from /mappings/{userId}

Is it possible to overwrite the default findAll url? How so?

Thanks!




Ember Cli Upgrades

Instructions provided here: http://ift.tt/1ysP6WQ lead me to believe that in order to upgrade Ember and/or Ember Data to a newer version, Ember-cli must also be upgraded. Is this true? The Ember-cli website doesn't mention versioning much, which always leaves me guessing whether or not to upgrade. Is there a one-to-one relationship between a version of Ember-cli and a version of Ember/Ember Data? Can someone please clarify?




Dynamic segments other than id in Ember.js

I'm trying to wrap my head around dynamic segments and I want to be able to use a slug or other property instead of the id. When I can get things working it feels like a fluke. (I'm using ember 2.7+)

I plan on using ember-data, but I want to ensure I'm in control - and so I don't want to use the :post_slug / underscore style that has some built in magic that I want to avoid.

Here is an ember-twiddle Here are step-by-step commits in a github repo



My thought process


1. Conceptually, lets say I need a list of cats - so I need to describe the model for what a 'cat' is.

models/cat.js

import Model from "ember-data/model";
import attr from "ember-data/attr";

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


2. define where the dynamic segment will be in the url. I'm going to use catId to prove a point instead of cat_id or :id like most of the tutorials I've seen. For this example, I'm also writing an actual app structure instead of the smallest router possible - to test the edges of this.

router.js

Router.map(function() {
  this.route('index', { path: '/' });
  this.route('cats', { path: '/cats' }, function() {
    this.route('index', { path: '/' }); // list of cats
    this.route('cat', { path: '/:catId' }); // cat spotlight
  });
});


3. pull in the catData into the store ~ in the /cats route

routes/cats.js

import Ember from 'ember';

const catData = [
  {
    id: 1,
    name: 'Dolly',
    slug: 'dolly'
  },
  {
    id: 2,
    name: 'kitty cat',
    slug: 'kitty-cat'
  },
  {
    id: 3,
    name: 'Cleopatra',
    slug: 'cleo'
  }
];

export default Ember.Route.extend({
  model() {
    return catData;
    // return this.get('store').findAll('cat'); // with mirage or live api
  }
});


4. create the templates... + set up the 'cat' route. The records are in the store... right? so I should be able to 'peek' at them based on id. The docs use params - but - "Ember will extract the value of the dynamic segment from the URL for you and pass them as a hash to the model hook as the first argument:" ~ and so the params can really be anything you want... and is just replaced with the dynamic segment - so to that point / I'm using 'passedInThing' just to assert control over the confusing conventions (many tutorials use param instead of params)

routes/cats/cat.js

model( passedInThing ) {
  return this.store.peekRecord('cat', passedInThing.catId );
}


5. At this point, I should be able to navigate to the url /cats/2 - and the 2 should get passed through the model hook - to the query. "Go get a 'cat' with an id of 2" --- right??? ((the twiddle example uses a hard-coded set of catData - but in my other attempts I'm using mirage: http://ift.tt/29eTvpR


6. Typing in the segment works - but for link-to helpers I need to pass in the explicit cat.id


  <span></span>



7. I can get all that working - but I don't want an ID in the URL. I want cats/cleo with the 'slug' ~ in theory I can just switch catId for catSlug and cat.id to cat.slug etc - but that is not the case. I've seen many tutorials outlining this but they are outdated. I've tried passing in { slug: params.slug } and every combo of find query and peek etc. Sometimes the url will work but the model wont render - or the opposite.


8. This seems like 101 stuff. Can anyone explain this to me? Oh wise emberinos - come to my aid!




Server side (or clientside??) solution to prevent multiple ajax requests across sessions?

I had a quick question. I have a login on my site (using Auth0 + Firebase). The site is using Ember JS. When you login, you have a dashboard, and when you click on the "Display" button, it shows a live feed pulling from Twitter's API and Instagram's API using AJAX requests. However, if you open the same page on multiple screens with the same user, it makes double the ajax requests, or triple depending on the amount of screens it's on. Is there any way to make this server side? Have it make the requests once on the server and then just fetch it from there live?

Ideally, I would like for people to login across multiple computers, click their "display button", and be projected the same stream. I figure this would need to be server side, i'm just at a loss of where to even start. I essentially just want to prevent 15 simultaneous ajax requests across sessions, and just have them fetch the 1. Is this even possible?

Thanks for the help is advance!




using Ember --proxy behind corporate firewall

I am developing an Emberjs Application behind corporate firewall (NTML Proxy). I have configured proxy settings (using Cntlm) to by pass all devtools.

Things working behind firewall through Cntlm (http://127.0.0.1:3128)

  • Git
  • Npm
  • Bower

But, when ever i proxy request to my cloud api (deployed on Azure) using
ember server --proxy http://ift.tt/2968Vxn --ssl

I am unable to do api request from the served website. If i connect the system to my phone (Wifi), remove proxy config. Every thing runs fine.

how can i forward all request from my website to my api throught my proxy (http://127.0.0.1)




Handlebars

I am using Ember js to render the main content in my web app. Ember uses Handlebars for templates. The main contest contains html tags and script tags. I have escaped the html tags in my handlebars variable using triple braces. This ensures that html tag in the content is parsed by the browser after the template is rendered. My doubt is that why is the script tag not executed by Javascript parser after the template is rendered. When I inspect via Chrome Inspector, the script tag is present in the content, but not parsed by Javascript. Is there any specific reason for this behavior.




Ember 1.13.15 acceptance test, pass and fail randomly or app.reset() does not clean up

I ran into this problem recently:

One of my acceptance test fail in one time and pass in next time and so on - it keepflipping the testing indicator flag. The failed error is

expect 4 tests but 0 were run.

That means it does not hit the andThen after click three times.

It always pass if I filter and run the test alone.

The scenario is when use click on one button if will fire a service call to backend if server receive three times it will pass 429 response. The 429 response will update array1 and array2 object and computed property disableTemplate will return true or false based on that.

Here is my code:

Template.hb


    //some template code    


Template/component controller.js

disableTemplate: Ember.Computed('array1, array2', function(){
    //some logic to return boolean.
})

Acceptance tests.js

test('button locked after clicking three times', function(assert) {
    assert.expect(4);
    andThen(()=> {
      click('.resend-btn');
    });
    andThen(()=> {
      click('.resend-btn');
    });
    andThen(()=> {
      click('.resend-btn');
    });

    andThen(()=> {
        assertSomething('.body', '5067');
        click('.cancel-btn');
    });

    andThen(()=> {
        click('button.show');

    andThen(()=> {
        assertSomething('.body', '5067');
    });
  });
});




EmberJS trigger computed property

Suppose I have the following computed property;

someCP: function() {

}.property(obj.innerObj.attr)

My question is will this get triggered even if obj.innerObj does not have 'attr' defined ?

How does this CP work?




Ember unit test computed property with then

I have the following model: partner.js

  invoices: hasMany('invoice'),
  resolvedInvoices: computed('invoices', {
    get(){
      let value = null;
      let _this = this;
      this.get('invoices').then(invoices=>{
        _this.set('resolvedInvoices', invoices);
      });
      return value;
    },
    set(key,value) {
      return value;
    }
  }),

I try to unit test it: partner-test.js

test('test', function(assert) {

  let partner = this.subject();
  let store = this.store();
  // set a relationship
  run(() => {
    let invoice = store.createRecord('invoice', {

    });

    partner.get('invoices').pushObject(invoice);
    console.log(partner.get('resolvedInvoices'));
  });
  assert.ok(true);
});

But console.log always shows null. Is it possible to wait till the computed property's then runs, and the new value sets?




Ember.js bower AdminLTE dependencies

Im learning Ember.js and I want to create a simple Ember.js + AdminLTE app. I did following steps:

  1. $ ember new app
  2. $ cd app
  3. $ bower install admin-lte
  4. $ ember build --env production

My questions:

  1. Why there is no AdminLTE dependency in bower.json ?
  2. Why there is no AdminLTE CSS and JS in compiled assets ?
  3. Do I have to manually add some dependencies to "ember-cli-build.js" file ?



Uncaught Error: Assertion Failed: You may not set `id` as an attribute on your model --- want to duplicate id attribute

I have a model called group having multiple attributes, I also want to save my id information to some other attribute because of some reasons to pass the model info to somewhere else.


import DS from 'ember-data';

var group = DS.Model.extend({

groupId : DS.attr('string'),//want to duplicate id here
groupName: DS.attr('string'),
groupRegion: DS.attr('string'),
groupCountry: DS.attr('string'),
groupSegment: DS.attr('string'),
groupSubSegment: DS.attr('string'),
isSelected: DS.attr('boolean'),
isExpand: DS.attr('boolean')

});

export default group;




How to fetch the data

Please tell me how to fetch the data from firebase

app/template/gmap.hbs

  

  

 
 
 
 

 

app/controller/newcase.js

 import Ember from 'ember';
 export default Ember.Controller.extend({
 actions:{
 addCase: function() {
 var hname = this.get('hname');
 var location = this.get('location');
 var latitude = this.get ('latitude');
 var longitude = this.get('longitude');
 var newCase = this.store.createRecord('case', {
 hname : hname,
 location : location,
 latitude : latitude,
 longitude : longitude
});
 newCase.save();
 this.setProperties({
 hname: ' ',
 location: ' ',
 latitude: ' ',
 longitude: ' '
});
 }

} });

app/controller/gmap.js

  import  Ember from 'ember';
  export default Ember.Controller.extend ({
 });

app/model/case.js

import Model from 'ember-data/model';
import attr from 'ember-data/attr';
 export default Model.extend({
 hname : attr('string'),
 location: attr('string'),
 latitude: attr('number'),
 longitude: attr('number')
 });

app/route/newcase.js

import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.get('store').findAll('case');
 }

});

firebase data1

i want to display that location, lat and lng in map i am not getting how to display please tell me how to write code for that




mercredi 29 juin 2016

how to execute action methods of a component from a controller or router in ember

I need assistance in executing action methods defined in ember components from outside. (even though ember follows DATA Down and Actions Up approach). My usecase is as follows

Application Template

    <script type="text/x-handlebars-template" data-template-name="application">
       <h2> Dialog Component </h2>
       
    </script>

Index Template
    <script type="text/x-handlebars-template" data-template-name="index">
        <button >Open Dialog 1</button>
        <button >Open Dialog 2</button>
        
            Content of the Dialog ...
        

         Content of the dialog ... 
    </script>

Modal Dialog Template
    <script type="text/x-handlebars-template" data-template-name="components/modal-dialog">
        <div class="titlebar-title">
           <span>  </span>
           <a class="closeBtn" >X</a>
        </div>
        <div class="content">
         
        </div>
    </script>

Index Controller

App.IndexController = Ember.Controller.extend({
      openFirst : false,
      actions : {
         showDialog1 : function(){
            this.toggleProperty("openFirst");  // open and close the first dialog when clicking the button.
         },
         showDialog2 : function(){
            // want to trigger "open" action of modal-dialog component without using any conditionals(if-else) and without observing "auto-open" attribute
            ......

         },
         handleDialogOpen : function(dialogName){
            if(dialogName === "dlg1"){
               // do something.
            }else if(dialogName === "dlg2"){
               // do something
            }
         }
      }
});

Modal Dialog Component

App.ModalDialogComponent = Ember.Component.extend({
        tagName : 'div',
        classNames : ['ui-dialog'],
        attributeNames : ['title','name','auto-open'],
        didInsertElement : function(){
             if(this.get("auto-open")){
                this.send("open");
             }
        },
        actions : {
              open : function(){
                 $(this.element).show();
                 this.onOpen()
              },
              close : function(){
                  $(this.element).hide();
              }
        }
});

Css Style Definition

ui-dialog{
  display : none;
}

Is there any way to achieve this ? Kindly guide me.




Ember/Emberfire + Firebase 3 Acceptance Test

Prior to firebase 3 update our acceptance test have been running without any issues. We use the following in our beforeTest and afterTest

moduleForAcceptance('Acceptance | Dashboard | Items | Library | New', {
  beforeEach() {
    stubFirebase();
    var ref = createOfflineRef(basicDataRef, 'http://ift.tt/1Fn9FlZ');
    replaceAppRef(this.application, ref);
    stubValidSession(this.application, {uid: 'xxxx'});
  },
  afterEach() {
    unstubFirebase();
  }
});

basicDataRef is a fixture for the test. The above code allows my to mock session following the test-helper in torii library to allow my application to correctly obtain the data needed as my firebase hieararchy is as follows: / +--uid +--profile +--otherdata

I am not testing for permission rules, just interaction to save/edit data in the application, and this has worked OK prior to firebase 3 migration. After version 3 all my test returns the following:

    actual: >
        false
    expected: >
        true
    stack: >
            at http://localhost:7357/assets/test-support.js:4130:12
            at exports.default._emberTestingAdaptersAdapter.default.extend.exception (http://localhost:7357/assets/vendor.js:49473:7)
            at onerrorDefault (http://localhost:7357/assets/vendor.js:41461:24)
            at Object.exports.default.trigger (http://localhost:7357/assets/vendor.js:62212:11)
            at http://localhost:7357/assets/vendor.js:63463:40
            at Queue.invoke (http://localhost:7357/assets/vendor.js:10415:16)
    message: >
        Error: permission_denied at /xxxx/profile: Client doesn't have permission to access the desired data.

I always thought the createOfflineRef in emberfire allows us to bypass rules checking. the fact that it keeps returning permission_denied is quite perplexing. Maybe i need to re-engineer the test? Or I approach this wrongly all this time? Any input is greatly appreciated




Ember js - how to create a shared uitility

I am writing code to detect breakpoints via js using match media. In plain js, I know how to create a separate utility for this and consume it, but in Ember, how do I go about it, would I need to create a helper or something else.

Plain JS code:

define('viewportDimension', function() {
    var viewportSize ={
        mqMaxTablet : '959px',
        isTablet: function(){
            if(matchMedia){
                var mq = window.matchMedia("(max-width:" + this.mqMaxTablet+ ")");
                mq.addListener(this.viewportChanged);
                this.viewportChanged(mq);
            }
        },
        viewportChanged: function(mq){
            if(mq.matches){
                return true;
            }
        }
    };
    return viewportSize;
});

Ember Controller:

isTablet: function (){
 viewportDimension.isTablet();
}.property('')

I understand the above code will not work. I dont know how to make it more Ember'ish type. The "isTablet" property should be set to true, as soon as the media query match is done.

Started converting my plain js to emberish (as below), but dont know how to proceed.

define('viewportDimension',function(){
    var viewportSize = Ember.Object.extend({
        isTablet: function(){
            alert("1");

        }.property('')
    });
    return viewportSize;


});

Ember.Application.initializer({
    name: 'viewport-dimension',
    initialize: function(container,app){
        require('viewportDimension',function(object){
            app.ViewportDimension = object
        })
    }
})




Changing body background color based on authentication

I am building an Ember application. On my homepage page my body background color is our website's blue, but when a user logs in, I want the body background color to change to white. How can I set a dynamic body background color that changes after a user is authenticated?

Here is my body css:

body {
    background-color: $process-blue;
    font-family: 'Lato', sans-serif;
    @include container(80%);
}




Using isn't rendering an image in ember.js 2

I am using Ember.js andI am having an issue getting this piece of code to render out a logo.

<span data-src="/images/logo.png"></span>

Does Ember.js not allow the use of data-src? I have gone through the docs and I havent seen anything that alludes to this.

Sort of a beginner so bare with me.

Thanks! Derek




EmberJS 1.13 Templating - script elements from htmlSafe string not executing JS

I have observed that, while writing JS in script tags into the template will run the script, inserting them into the template using a Handlebars expression will prevent it from running.

I have tried writing this into my component:

test: Ember.String.htmlSafe("<script>console.log('Hello World')</script>")

And in my template:

This will insert it into the DOM, but will not run the code. I thought it was because HTMLBars did not allow script tags in the template, but just writing

<script>console.log('Hello World')</script>

into the template itself will run the JS within.

Can somebody tell me if there is a way to achieve this, or provide an explanation as to why this happens? Thanks in advance.




Ember build not picking up changes to environment.js

I have a working configuration in my environment.js, but want to add a variable. I placed the pageSize variable like so: var ENV = { contentSecurityPolicy: { 'style-src': "'self' 'unsafe-inline'" }, modulePrefix: 'fdms-admin', environment: environment, ROOT_URL: process.env.ROOT_URL, BASE_URL: process.env.BASE_URL, pageSize: 100, baseURL: '/admin/', locationType: 'auto', EmberENV: { ...

When I run ember build and place the assets folder inside of my Java project, the changes to the config are not being picked up. The pageSize variabale is undefined on the ENV object. Any ideas?




fastboot usage example explained?

Can some one please explain in more detail how the example posted in the "Fastboot" readme file would work, as to where in an existing Ember application this would be integrated? Thanks.

This is a copy of the code I don't understand:

// Usage
const FastBoot = require('fastboot');
 
let app = new FastBoot({
  distPath: 'path/to/dist'
});
 
app.visit('/photos')
  .then(result => result.html())
  .then(html => res.send(html));



Ember.js - Can I nest a component into another before it's added to the Handlebars template?

I'm developing an application with Ember CLI version 2.6.1 and I'm using a UI library called Webix.

Webix generates html through JavaScript like this:

var accordion = webix.ui({
    view:"accordion",
    type:"wide",
    cols:[
        { header:"col 1", body:"content 1", width:150 },
        { header:"col 2", body:"content 2", width:150 },
        { header:"col 3", body:"content 3", width:150 },
        { header:"col 4", body:"content 4", width:150 },
        { header:"col 5", body:"content 5", width:150 }
    ]
});

Webix is imported into my Ember app and I can generate a component with this syntax by creating an instance within the JS file of the component instead of the Handlebars file (where it would live if I were using html).

Like this:

    import Ember from 'ember';

    export default Ember.Component.extend({
        didRender: function() {

            webix.ui({ 
                container: this.container,
                height: 585,
                view:"accordion",
                    type: "line",
                    rows:[ 
                    { 
                        header:"Panel 1",
                        body: {
                            padding: 10,
                            rows: [
                                { 
                                   view:"textarea", 

                                   labelAlign:"right", 
                                   //height:150, 
                                   value: "type here"  
                                },
                                { 
                                   view:"textarea", 

                                   labelAlign:"right", 
                                   //height:150, 
                                   value: "type here"  
                                }

                            ]

                        }
                    }
                ]
            });

        }
    });
}

This works fine, but as the application grows in complexity I will have one GIANT component that is going to be impossible to maintain.

I would like to extract the nested Webix views into their own components that are instantiated as they are needed.

Like this:

enter image description here

My parent component is created in Handlebars, but since the Webix component has its own nesting methodology, I can't just drop in a new component:

enter image description here

Since component structure is usually composed through Handlebars with properties passed in there, how could I nest a component into another before its parent is loaded into Handlebars?




Can we mix KnockoutJs and EmberJs in our application?

I have couple of pages written in KnockoutJs and I want to add these 4 pages to the application which is written in Emberjs+HandlebarsJs. Can we do this? KnockoutJs is based on MVVM pattern, EmberJs is based on MVC. So is my idea right? Can we do this at all? It will be great if I can get answer with explanation.




Intellij with ember error: "you have to be inside an ember-cli project in order to use build command"

I have created a project which is configured to use ember-cli on the webapp folder before launching the resulting code, however I get that error when the ember compiler is called.

Here are some pictures: picture1 picture2

Is it something related to ember or is it something related to my run configuration?




Ember: Integrating Google Recaptcha with ember-cp-validations

I have a simple contact form, with validation done using ember-cp-validations http://ift.tt/1NRGKRu and I now need to integrate the new Google Recaptcha into that.

For the rendering of the recaptcha, I am using this code - http://ift.tt/294G2Pc - which works perfectly.

However, I don't know how to deal with the verification process to allow the form to be submitted/prevented if the challenge is correct/incorrect or not provided

Here is a truncated version of my contact-form component

import Ember from 'ember';
import Validations from './cp-validations/contact-form';
import config from '../config/environment';

export default Ember.Component.extend(Validations,{
    data:{},
    nameMessage:null,
    init() {
      this._super(...arguments);
      this.set('data',{});
     },
     actions:{
        submitForm() {

           this.validate().then(({model,validations}) => {
               if (validations.get('isValid')) {
                   // submit form
               }
               else {
                   if(model.get('validations.attrs.data.name.isInvalid')){
                this.set('nameMessage',model.get('validations.attrs.data.name.messages'));

                 }
               }
           })
        }

     }
});

Here is the template for the component, which includes the rendering of the recpatcha using the gist above

<form >
<div class="row">
<div class="medium-6 columns">

<div class="error-message">

</div>
</div>
</div>

<div class="row">
<div class="medium-12 columns">

</div>
</div>
<button class="button primary" type="submit">Submit</button>
</form>

The Validations import looks like this

import { validator, buildValidations } from 'ember-cp-validations';
export default buildValidations({
 'data.name': {
    validators: [
      validator('presence',{
        presence:true,
        message:'Please enter your name'
      })
    ]
  },
});

Many thanks for any help!




Intellij Idea run configuration with ember.js on ubuntu

I am having a problem with the run configuration of ember on intellij idea on ubuntu 14.

I have installed ember using npm and I have followed a tutorial on my teacher's site on how to correctly configure intellij to use both maven and ember. I had no problem configuring the first part (maven), however at the second part, which was basically the same, I couldn't find the file he was refering to. Here is the picture: tutorial

And here is the error: error

Error: No ember-cli-build.js found. Please see the transition guide: http://ift.tt/292ONso.
at CoreObject.module.exports.Task.extend.setupBroccoliBuilder (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/lib/models/builder.js:56:13)
at CoreObject.module.exports.Task.extend.init (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/lib/models/builder.js:89:10)
at CoreObject.superWrapper [as init] (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/node_modules/core-object/lib/assign-properties.js:32:18)
at CoreObject.Class (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/node_modules/core-object/core-object.js:32:33)
at CoreObject.module.exports.Task.extend.run (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/lib/tasks/build.js:15:19)
at /home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/lib/commands/build.js:32:24
at lib$rsvp$$internal$$tryCatch (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1036:16)
at lib$rsvp$$internal$$invokeCallback (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1048:17)
at /home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:331:11
at lib$rsvp$asap$$flush (/home/user/.nvm/versions/node/v5.0.0/lib/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1198:9)

Could you please help me find the file he was referring to in the tutorial (since "usr/bin" doesn't have any "ember" files)?




mardi 28 juin 2016

Heroku pipeline config vars

I've been having this issue many times. When I promote my staging app to production its config vars are not loaded properly. Right now my production app is using my staging's config vars. How can I fix this?




Add a Favicon to AWS/S3 - Ember.js

I've uploaded the favicon in my route bucket for S3. I've linked the favicon in the html file of the project:

<link rel="icon" href="images/favicon.ico"> 

Where images is a public folder.

The problem is when I locally host the web app it displays the Favicon,

but it only displays the Favicon on Production when I inspect the source of the page. I don't know if this is a bug that I should report, or if I'm doing something wrong.

Any suggestions will be helpful. Thanks.




Can't update template from controller

I need to update template from action. But I use two controllers.

In my template I show a text:



My controller:

export default Ember.Controller.extend({
   myText: 'Hi',
   actions: {
    reload: function() {
        this.set('myText', 'Bye');
    }
   }
   ...

I change it from another controller from someFun:

export default Ember.Controller.extend({
    needs: ['another'],
    someFun: function() {
        this.get('controllers.another').send('reload');
    }
});

It calls reload action (I tested). But it doesn't change template. It still shows Hi but should change to Bye.




Ember multidimensional arrays, best practice with model data

Typically in Ember, you setup your model:

export default Model.extend({
    "name": attr('string'),
    "address": attr('string'),
    "sports": attr()
})

You then create a form:





From there you can get the value of the input or set the value:

var name_val = this.get('name');
var address_val = this.get('address');
var sports_val = this.get('sports');

or set a value:

this.set('address','123 Main Street');

How would one create dynamic multidimensional arrays and store them? For example, you want to list out several sports:

 
 


From there perhaps you want to know given a sport checked, does the user watch that sport, or play that sport? This could be done using a dropdown or more checkboxes. Ultimately, the end result would be this json:

{
    'name':  'Matt',
    'address': '123 Main Street',
    'sports': {
        'baseball': 'watch',
        'hockey': 'play'
    }

}

It seems Ember is easy to setup items one level deep, but what about multi, dynamic values and levels?




Call one controller from another without reloading it

I need to call one controller from another.

export default Ember.Controller.extend({
  needs   : ['another'],
  ....
  callAnother: function() {
    this.get('controllers.another').reloadIt();
  }
})

Another controller:

export default Ember.Controller.extend({
  init: function() {
     calling API
  }
  reloadIt: function() {
    calling API
  }
})

When I call this.get('controllers.another').reloadIt(). It calls init and reloadIt.

Is it possible to call it without init because it's already loaded.

Thanks.




Closing an emberfire/torii session and logging out throws permission_denied errors

I am using EmberFire with the Torii for sessions. I am getting an odd issue when I log a user out, and the following errors are thrown in the console:

firebase.js:186 Error: permission_denied at /folders/-KKvrk3K_JOHxQWgR1km: Client doesn't have permission to access the desired data.(…)(anonymous function) @ firebase.js:186(anonymous function) @ firebase.js:380Tb @ firebase.js:276uc @ firebase.js:263vc @ firebase.js:262(anonymous function) @ firebase.js:449vh @ firebase.js:434g.wd @ firebase.js:425Ye.wd @ firebase.js:328(anonymous function) @ firebase.js:326vd @ firebase.js:279La.onmessage @ firebase.js:278
firebase.js:186 Error: permission_denied at /folders/-KLFp3zh5QUB7KvMF0HZ: Client doesn't have permission to access the desired data.(…)(anonymous function) @ firebase.js:186(anonymous function) @ firebase.js:380Tb @ firebase.js:276uc @ firebase.js:263vc @ firebase.js:262(anonymous function) @ firebase.js:449vh @ firebase.js:434g.wd @ firebase.js:425Ye.wd @ firebase.js:328(anonymous function) @ firebase.js:326vd @ firebase.js:279La.onmessage @ firebase.js:278
firebase.js:186 Error: permission_denied at /externalApps/-KLF_wKXtzm38EHtuQ_C: Client doesn't have permission to access the desired data.(…)(anonymous function) @ firebase.js:186(anonymous function) @ firebase.js:380Tb @ firebase.js:276uc @ firebase.js:263vc @ firebase.js:262(anonymous function) @ firebase.js:449vh @ firebase.js:434g.wd @ firebase.js:425Ye.wd @ firebase.js:328(anonymous function) @ firebase.js:326vd @ firebase.js:279La.onmessage @ firebase.js:278
firebase.js:186 Error: permission_denied at /users/-KLKUOZRBCIeCj44WMe7: Client doesn't have permission to access the desired data.(…)(anonymous function) @ firebase.js:186(anonymous function) @ firebase.js:380Tb @ firebase.js:276uc @ firebase.js:263vc @ firebase.js:262(anonymous function) @ firebase.js:449vh @ firebase.js:434g.wd @ firebase.js:425Ye.wd @ firebase.js:328(anonymous function) @ firebase.js:326vd @ firebase.js:279La.onmessage @ firebase.js:278
firebase.js:186 Error: permission_denied at /externalApps/-KLIyXUwTSrkCIL4rz7U: Client doesn't have permission to access the desired data.

This only seems to happen when I log the user in immediately after registering them. Here is the code that registers and logs in the user:

register(data) {
  return this.get('firebaseApp')
    .auth()
    .createUserWithEmailAndPassword(data.email, data.password)
    .then((registeredUser) => {
      const newUser = this.store.createRecord('user', {
        uid: registeredUser.uid,
        firstName: data.firstName,
        lastName: data.lastName,
        email: registeredUser.email
      })
      return newUser.save();
    })
    .then((savedUser) => {
      return this.get('session').fetch().then(() => {
        return savedUser;
      });
    })
    .then((savedUser) => {
      this.replaceWith('dashboard');
    });
}

And here is the action that logs the user out:

logout() {
  this.get('session').close().then(() => {
    this.store.unloadAll();
    this.replaceWith('index');
  });
}




ember client liquid fire transitions

I have gotten my transitions.js working. Am using the 'fly-to' effect.

However, in tablet mode (so when my browser is smaller/shrunk) I'd like the animation/transition to be the slide one.

This is because the shape, size and position of my div changes in desktop and tablet mode. Using 'fly-to' in my tablet mode results in a clunky animation. But if I change it too 'slide-to' the animation is smooth in tablet mode. ...but then this means in desktop mode, the animation is also 'slide-to'. I need to to be 'fly-to'

Hope that makes sense!

Is there an equivalent of and if/else condition statement I can add to transitions.js ?

See snippet from my transitions.js below:

  let duration = 200;
  this.transition(
    // this.debug(),

    this.use('explode', {
      matchBy: 'data-icon',
      use: ['fly-to', { duration }]
    }, {
      use: ['toDown', { duration }]
    }),
    this.reverse('explode', {
      matchBy: 'data-icon',
      use: ['fly-to', { duration }]
    }, {
      use: ['toUp', { duration }]
    }),
  );




Private variables in Ember-data DS.Model

I want to store a private variable on each DS.Model. Its purpose is to store a pending callback (in case I want to cancel it).

I have tried this (and it works):

DS.Model.reopen({
  init() {
    let _pending; // my private var

    this._getPending = () => _pending;                   // get private var
    this._setPending = callback => _pending = callback;  // set private var

    this._super(...arguments);
  }
});

I have placed this in an initializer, and it works as I expect it to.

My questions are: Is this a good practise? ...and, is there a better way?

Personally, I'm happy with the way it works.. but I'm not sure if its the "Ember" way. This is going to go into an Ember-cli addon, so I would like it to be the most "best practise" as possible. (the _getPending/_setPending method are only to be used internally within the addon.)




Relationships: Ember data & MySQL

Hei guys,

I would like to understand how to connect MySQL and Ember data relationships.

For example, i have a user model:

// app/models/user.js

export default({
  collections: hasMany('collection')
});


// app/models/collection.js:

export default({
  user: belongsTo('user')
});

This part is very simple, i get it.

Now, the problem: How should i express the relationship in the MySQL? Using the same names (columns) to add foreign keys?

Thanks in advance1




How to filter a model by belongsTo relationship property in EmberJS

I'm trying to filter a findAll query to get only the elements without relationship.

My model is created by two classes:

Element

export default Model.extend({
    position: attr('number'),
    name: attr('string'),
    shared: attr('boolean', { defaultValue: false }),
    stack: belongsTo('stack')
});

 Stack

export default Model.extend({
  position: attr('number'),
  name: attr('string'),
  shared: attr('boolean', { defaultValue: false }),
  element: hasMany('element')
});

I have tried to filter by property stack filterBy('stack', null) and filterBy('stack.content', null) but they didn't run.

Any idea and help of how to filter by relationships?




lundi 27 juin 2016

Set the scroll top in ember perfect scroll components

I am working on ember js project now.
I used http://ift.tt/28ZhuGm
when the container's height is resized, the scroll position has to be at the top. I need your help.




Displaying Errors on Unsuccessful Save with Ember

I have a route for new-thing and it's template is a form. When this form submits, I call a createThing action in the route, passing in this.

export default Ember.Route.extend({
  model() {
    return {};
  },

  actions: {
    createThing(thing) {
      let thingToSave = this.store.createRecord('thing', {
        name: thing.name,
        description: thing.description
      });

      thingToSave.save().then(function() {
         // happy path
      }).catch(function(reason) {
        // unhappy path
      });
    }
  }
});

In my template, I have the following:


  <div class="error">
    
  </div>


But something isn't quite wired up right. I'm unclear on how the route's model ends up being the thing I'm trying to save so that the errors will render when the bad path triggers.




Handling Errors with RESTSerializer

Using ember and ember-data 2.6 versions, I'm trying to get error handling working but running into issues. I'm using the RESTSerializer and I'm sending the following payload to my server:

{
    "brand": {
        "name": null,
        "description": null,
    }
}]

Since name cannot be null, this is what I'm sending back as my response:

{
    "errors": [{
        "code": null,
        "detail": "may not be null",
        "status": null,
        "title": null,
        "source": {
            "pointer": "brand/name",
            "parameter": null
        }
    }]
}

In my route, I am doing the following in the save promise on failure:

console.log(savedBrand.get('isValid')); // logs false
console.log(savedBrand.get('errors').toArray()); // logs [ ]

There doesn't seem to be a lot of detailed documentation on how this all works so I'm using this article as a starting point. I'm unsure as to why toArray() returns an empty array instead of my error that I'm returning in the JSON.




Trouble transitioning to current user after signing in with Emberfire

I am using Emberfire for my authentication and database and I am able to sign in, but it does not redirect me to my current users page after that. It also throws an error at me saying that no user exists at the custom url but my firebase console shows the user with the correct id that I am redirecting to.

Here is my login controller:

import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    return this.get('session').fetch().catch(function() {});
  },
  actions: {
    signIn: function() {
      var controller = this.get('controller');
      var email = controller.get('email');
      var password = controller.get('password');
      this.get('session').open('firebase', { provider: 'password', 'email': email, 'password': password}).then(function(data) {
        console.log(data.currentUser);
      });
      let uid = this.get('session').get('uid');
      this.store.findRecord('user', uid).then(user => {
      console.log(user.get('firstName'));
      this.transitionTo('user', uid);
});
    },
    signOut: function() {
      this.get('session').close();
    }
  }
});

Here is my router:

Router.map(function() {
  this.route('signup');
  this.route('home', { path: '/' });
  this.route('login');
  this.route('user', { path: '/user/:user_id' });
});




Ember unit test rendering handlebars returns null or undefined

I am trying to write unit tests for rendering a handlebar component. When the test gets ran the object is empty and no HTML is generated. I have followed this same layout using other components and they render properly. I am confused why the returned object is null/undefined

here is my ember test code:

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('csv-upload', 'Integration | Component | csv upload', {
     integration: true
});

test('it renders', function(assert) {
assert.expect(2);


this.render(hbs``);

assert.equal(this.$().text().trim(), '');

// Template block usage:
this.render(hbs`
  
   template block text
  
`);

assert.equal(this.$().text().trim(), '');
});

the output from the test is:

ok 32 PhantomJS 2.1 - JSHint - integration/pods/components/csv-upload/component-test.js: should pass jshint
not ok 33 PhantomJS 2.1 - Integration | Component | device actions: it renders
---
    actual: >
        null

another thing from output:

undefined is not an object (evaluating 'this.get('selected').isAny')




Controller not recognizing Ember Validations mixin

I am creating a sign up form with ember-validations and EmberFire. My server starts up fine, but my console displays this error:

Uncaught Error: Could not find module `app/mixins/validations/signup` imported from `processapp/controllers/signup`

Here is the code for my signup validation mixin:

import Ember from 'ember';
import EmberValidations from 'ember-validations';

export default Ember.Mixin.create(EmberValidations, {
  validations: {
    "model.firstName": {
      presence: true
    },
    "model.lastName": {
      presence: true
    },
    "model.email": {
        format: { with: /^.+@.+\..+$/, message: 'Please enter a valid email address.' }
    },
    "model.password": {
        length: {minimum: 6, maximum: 30},
        presence: true,
        confirmation: true
    }
  },
});

Here is the code for my signup controller:

import Ember from 'ember';
import SignupValidations from 'app/mixins/validations/signup';

export default Ember.Controller.extend(SignupValidations, {
actions: {
    createUser(){
      //...
      this.validate().then(()=>{
        var newUser = this.store.createRecord('user', {
            firstName: this.get('firstName'),
            lastName: this.get('lastName'),
            email: this.get('email'),
            password: this.get('password')
        });
        newUser.save().then(()=>{
          this.transitionToRoute('user', newUser);
        });
      }).catch(()=>{
        console.log(this.get("errors"));
      });
    }
  }
});

The file structure seems to match the structure included in the import SignupValidations line in my controller so I am a bit confused as to why I am getting this error. Any ideas?




Refactoring mock response in ember cli mirage 0.2.x

I'm using ember cli mirage to write some acceptance tests for my Ember app. I succeeded to mock server response for login but I'm not happy how I did it. Ember cli mirage have shorthands for route handlers and I would like to use them but everything I try throws me an error(except this solution). Can someone help me to refactor this response?

this.post('/login', ({ users, resources })=> {
  let user = users.first();

  if(!Ember.isEmpty(resources.first())){
    return {
      data: {
        type: 'user',
        id: user.id,
        attributes: user,
        relationships: {
          resources: {
            data: [
              { id: resources.first().id, type:  'resource' }
            ]
          }
        }
      },
    };
  } else {
    return {
      data: {
        type: 'user',
        id: user.id,
        attributes: user
      }
    };
  }
});

I have both user and resource model and factory defined, with relationships between them in user and resource model(it's many to many relationship). Here's how I create user in tests

test('User can login', function(assert){
  let resources = server.createList('resource', 2),
      user      = server.create('user', {resources: resources});

  loginUser(user.email);
  andThen(()=>{
    assert.ok(find('a:contains("Logout")'));
    assert.equal('resource.content', currentPath());
  }); 
});




How effective is AngularJS 2.0? What all (facts) can we expect?

(PLEASE DON'T QUOTE OPINIONS. JUST FACTS AS ACCEPTED BY THE WHOLE COMMUNITY.) (Opinion-based quotes are not legal on this site.)

Now that Angular 2 is in Release Candidate 1 (RC1);

I want to start a thread on what all claims were made, & how much has been deliverd/will be delivered. What all was aimed & what has been done/will be hopefully done.

I am asking from a programmer's or engineer's perspective. It is a question related to programming.

Please only quote the most authoritative, & verifiable facts. Specially relevant to engineering, programming, new web standards, & tech.

I want this to be an authoritative thread. Request only the most, most experienced people to speak. Requesting an Angular-God's zone.




How can I make a GET request in Ember with a '/' in the path?

I want to make a GET request to my backend application with Ember.js. The problem I'm having is that I have a '/' in the URL for the GET request. The URL I need to make a GET request to looks like this:

http://localhost:9000/alertsettings/settingId

But when I pass in the settingId as a parameter, like this:

this.store.find('alertsettings', {'settingId': settingId})

The resulting URL it tries to make the GET request to looks like this:

http://localhost:9000/alertsettings?settingId=12345

Does anyone know how to make a GET request to my backend application with the URL as described in the first codeblock (so '?settingId=12345' is replaced with '/12345')?




Ember js: TypeError: this.store.adapterFor is not a function inside component

So I have different host url for production and development

I am trying to make a ajax post call inside a component, I have this to get the host from the store:

var host = this.store.adapterFor('application').get('host');

I have injected the dependency with this:

import Ember from 'ember';

export default Ember.Component.extend({
   store: Ember.inject.service(),

but I get this error

TypeError: this.store.adapterFor is not a function

Any help will be appreciated.

also here is my adapters/application.js

import DS from 'ember-data';
import ENV from "../config/environment";

export default DS.JSONAPIAdapter.extend({
    host: ENV.APP.API_HOST,
});




Ember.js Multiple Selection in a Table

I'm newbie in Ember.js framework, and I have a problem, I need a multiple selection of rows in a table.
I'm using jQuery Datatables, with Ember-Data, and I need to have an ID of the selected rows, something like push to the array and I have no clue how to do this.




dimanche 26 juin 2016

Ember input helper placeholder not working for password and email type

I am trying to create sign up and log in forms for my Ember app. I am using the input helpers, but when I set the field for email and password the placeholder text comes in the format of the respective types and also shows the "value" as the placeholder text instead of the defined "placeholder" text. The first name and last name fields show the correct placeholder text and in the correct format. Here is the code from my sign up template:


    
    
    
    

Here is what the form looks like as a result: form

Any ideas how to fix this?




Dynamic Facebook Share/Comments in Ember

After trying a few different packages to help with updating meta and og tags unsuccessfully, I am exploring other options to integrate Facebook sharing or commenting onto my Ember site. But I seem to be unable to dynamically generate the data-href value in my HBS templates.

<div class="fb-comments" data-href="http://ift.tt/28WSjEt}}" data-width="510px" data-numposts="10"></div>

Whenever you access the first review, the comments load fine. But once you go to another, even though the href is updated the comment plugin no longer loads. Is there a way to incorporate this with dynamic URLs?




Different serverTokenEndpoint for login and registration

I'm using ember-simple-auth for logging in a user which is working fine. For logging a user in, I've to ping this endpoint: /auth/sign_in.

However, for registering a new user, I've to ping a different endpoint: /auth.

If I'm trying to use the ember-simple-auth for also registering (as instructed in this blog: http://ift.tt/290uXll), I'm facing the issue that Ember is pinging the same endpoint (as specified in the serverTokenEndpoint).

How can I register a new user using ember-simple-auth?




how does the ember server pass the ember app a url

I have an ember app. With a rails backend. I have the following in my rails routes file.

get '*path' => redirect('/')

This catch all will send everything that is not defined in the route to / where my ember app is located and my application route is executed.

If I have a route in ember that looks like /posts my rails app goes to / and again it executes my application route but not my post route, which makes sense since there was nothing passed to tell it to execute the ember posts route.

So then I went down the long journey of googling until I got to ember-cli-deploy. And while this is incredible, I thought it a bit over kill for what I wanted to do (I might be wrong as maybe I do not really know how hard what I am trying to do is).

So I figured I can set a cookie from rails that would expire in a few seconds. That cookie would have the initial url the user visited before the redirect to /. Before the cookie expires, I can have ember read that cookie and get the url. Then in the ember application route (in the setupController function), before I set session info, ect...; I can this.transitionTo('posts'). (I could not figure out another way to pass the url to the client.)

This is where my question came up. Is there a way I can pass the initial url to ember before getting to the application route. I figure there is a way to do this since, the ember server is doing it. When I run ember server, I am able to navigate to /posts and the application route as well as the posts route are executed.




Loading data on dropdown change in Emberjs

I have a component that is a dropdown (listing "periods") and when this selection change, should populate the form below it with a form so one can edit the data for that period.

The main template render the component just fine (I hope the code explain itself?)



and the component render with a dropdown populated with the periods

<select style="width:100%"  onchange=>
    <option>Select a period</option>
    
        <option value=></option>
    
</select>

Here's where I'm starting to loose it (very new to Ember) because model have a periods property where period have a "balance" property. So the form being show will be something like model.periods[1].balance(if you think in terms of c# code which I'm used to)

Anyhow, my problem for now is this promise thing, seems my api get hit AFTER the alert in the following code, which should only happen when the data have been returned (the alert is [object,object] anyhow...uuurgh)

 actions: {
    periodChange(period) {
        var store = this.get('store'); 
        store.findRecord('dealperiod',  period.value).then(function(data) {
          var assetBalance = data.assetBalance;
          alert(assetBalance);
          this.set('assetBalance', assetBalance);
        }); 

If someone could just point me in the right direction, not expecting to be spoonfed.

Guess my questions comes down to : what's the right way to do something only after the data have been returned (promise?) and secondly, now to name form inputs if the inputs are for a child property of the model (like in this case I have a "deal" model, which have a collection of "periods" and I want to edit data for each period as they are being selected)




Emberjs data binding model to controller

New to EmberJS and trying to follow this tutorial here: http://ift.tt/28Y3fFe

This tutorial has a "Contact" page which lets user send a feedback using email and message box.

I have completed the exercise using Option 1 for Lesson 3 but I am not sure I am doing it right. It fulfils the requirements, I can submit message and I can see a list of messages in my Contact Messages page (not Contact page, notice 's').

My contact.js controller looks like this:

import Ember from 'ember';

export default Ember.Controller.extend({

  emailAddress: '',
  message: '',

  emailValid: Ember.computed.match('emailAddress', /^.+@.+\..+$/),
  hasMessage: Ember.computed.gte('message.length', 5),
  formValid: Ember.computed.and('emailValid', 'hasMessage'),
  isDisabled: Ember.computed.not('formValid'),

  actions: {
    sendFeedback() {
      // alert(`Submitting your feedback\n\nFrom: ${this.get('emailAddress')}\n\nMessage: ${this.get('message')}`);

      let newContact = this.store.createRecord('contact');
      newContact.email = this.get('emailAddress');
      newContact.message = this.get('message');
      newContact.save();

      this.set('responseMessage', 'Feedback sent!');
    }
  },

  willTransition() {
    this.get('model').rollbackAttributes();
  }
});

If I do it like this, this is me just telling Ember to get the value from the HTML form manually using this.get('emailAddress'); and this.get('message');, constructing a new Contact instance, set its respective values and then call save() method.

My question is, what happened all to the data bindings ?

Is the way I'm doing it even right ?

Lesson 3 was about creating Library model, and its routes index and new. The model is data bound to the UI. Updating the UI also update the model associated with the UI, without me needing to manually tell it to get the value from UI and set it into the model.

I was expecting something similar for my Contact page but the way I am doing it doesn't feel right...I am manually setting the value for the model...




samedi 25 juin 2016

Ember how to refresh model after promise resolved?

I was trying to implement the following functionality: When user clicked a button, it triggers 'createEvent' which sends the data to backend server (a Python server) to insert a record into DB. After that, I'd like to refresh my model to show the latest data.

Howerver, Ember refreshes the model before it was resolved. If I run the following code, it always prints "refreshed." first and then "promise resolved.". Is there a way I could trigger the 'refresh' function after the model is resolved? I don't think it's a good idea to call 'refresh' inside the 'model' function as 'refresh' will fire 'beforeModle', 'model' and 'afterModel' functions.

Thanks!

    
export default Ember.Component.extend({
      title: null,
      actions: {
        createEvent() {
          var data = {
            title: this.get('title')
          }
          let self = this;
          $.ajax({
              type: 'POST',
              url: ENV.host + '/create_event',
              data: data,
              success: function(response) {
                // calls 'addEvent' to refresh model.
                // but it doesn't work!
                self.sendAction('addEvent', response);
              }
          });
        }
      }
    });

    export default Ember.Route.extend({
      model() {
        return this.store.findAll('event').then(function(events) {
          console.log("promise resolved.");
          return events.sortBy('date').reverse();
        });
      },
      actions: {
        reload: function() {
          this.refresh();
          console.log("refreshed.");
        }
      }
    });

    export default Ember.Controller.extend({
      actions: {
        addEvent: function(response) {
            self.send('reload');
        }
      }
    });
DEBUG: Ember      : 2.5.1
DEBUG: Ember Data : 2.6.0
DEBUG: jQuery     : 2.2.4




Overwrite a node package in ember

How do I overwrite a package in node within ember? For example, a particular component is located here:

node_modules/module/app/templates/components/module_code.hbs

If I edit that file directly, it of course will be overwritten with an upgrade. Can I put the same file:

module_code.hbs

somewhere in my Ember App structure to make adjustments?




Redirect to child route from parent route in Emberjs

How can I redirect to a child route from a parent route in Ember?

Currently, my router.js is:

Router.map(function() {
  this.route('landing-page', { path: '/' });
  this.route('users', function() {
    this.route('user', {path: ':id'});
    this.route('all');
  });
});

I want to redirect to users/all route from the users route.

I've tried using this.route('users', { path: 'all'}, function() {... but it doesn't work and shows UnrecognizedURLError: /users/.




Ember + Mirage and relationships

i'm working with Ember 2.6 and currently using Mirage for a client hosted static database.

I started using fixtures du provide the sample data, but I cannot make the relationships work.

I have 2 entities : island and spot, with a Many to One relationship

//mirage/models/spot.js
import { Model, belongsTo } from 'ember-cli-mirage';   
export default Model.extend({
  island: belongsTo()
});

and

//mirage/models/island.js
import { Model, hasMany } from 'ember-cli-mirage';
export default Model.extend({
  spots: hasMany()
});

and my fixture data

//mirage/fixture/spots.js
export default [
  {id: '1', name: 'test spot', island_id: [1]},
}

and

//mirage/fixture/islands.js
export default [
  {id: '1', name: 'Island 1 Name', permit: null, spot_ids: [1]},
}

my config.js is just a simple getAll

  this.get('/islands', function(schema, request){
    return schema.islands.all();
  });

But when I call it, I got my islands, but the relationships are missing.

Using the default json api adapter.

How to make Mirage return json data with the given relationships ? I tried to set the relation in both sides and 2 at the same time and neither provides the child entity.

Here is a link of my project on github : http://ift.tt/290uv5j




Emberfire and localhost setup

I've encounter problem with EmberFire. I'm using 2.6 Ember, 3.0 EmberFire, and Torii for Auth and turning Ember with SSL on. I did everything from Quick Start guide.

I'm getting the given error in Chrome:

Uncaught SecurityError: Blocked a frame with origin "http://ift.tt/28WLTIC" from accessing a frame with origin "https://localhost:4200". Protocols, domains, and ports must match.

Any idea what is missing in my localhost configuration?

# public/crossdomain.xml
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://ift.tt/1d1B8yI">
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="all"/>
  <allow-access-from domain="*" to-ports="*" secure="true"/>
  <allow-http-request-headers-from domain="*" headers="*" secure="true"/>
</cross-domain-policy>

# config/environemnt.js
Env.contentSecurityPolicy: {
      'script-src': '\'self\' \'unsafe-eval\' apis.google.com',
      'style-src': '\'self\' \'unsafe-inline\' fonts.googleapis.com',
      'font-src': '\'self\' fonts.gstatic.com',
      'frame-src': '\'self\' http://ift.tt/28WLVjK',
      'img-src': '\'self\' *.gravatar.com s3.amazonaws.com',
      'connect-src': '\'self\' http://ift.tt/1Us4oBa http://ift.tt/1ymbsZQ'
    },

Thanks in advance for any help.




Ember - Pass html element as parameter from ember template to component on click action

How can we pass element object in handlebar onclick action. I tried passing "this" but that doesn't worked.

<a href="javascript:void(0)" onclick= >Menu Item</a>

Component.js

Ember.Component.extend({
  actions: {
    menuClickEvent :function(element) {          
    // need element <a> to do jquery operation
    }
  }
});




Ember error on refresh or direct URL

I was unable to find any current answers for this question.

I am building my latest project in Ember and while I am able to access the different routes directly and with refreshes locally, as soon as I build for production and host the site, this no longer works. I believe the slug portions of my routers are correct so not sure what I need to update.

Note: I am using Ember CLI.

Router.js

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

Router.map(function() {
  this.route('reviews', function() {
    this.route('index', {path: '/'});
    this.route('review', {path: '/:review_id'});
  });
  this.route('movies');
  this.route('about');
  this.route("error", { path: "*path"});
});

Review Model

export default Ember.Route.extend({
    model(params) {
        const id = parseInt(params.review_id);
        const movies = this.get('movies');
        return movies.getMovieById(id);
    },
    movies: Ember.inject.service()
});

If I try to directly access or refresh /about, /reviews, /movies, or /reviews/:review_id I am given a 404. Even though the about route doesn't have a model to retrieve any data. It's simply loading a template. The only route I can refresh on is the very index page of the site.




Emberjs "eq" in component

Got a component that works just fine as follows (selectedId is definitely set):

export default Ember.Component.extend({
    store: Ember.inject.service(),
    items: [],
    selectedId: 0,
    result: '',
    init () {
        this._super(...arguments);
        var store = this.get('store'); 
        let items =  store.findAll('dealtype');
        this.set('items', items);
    },
    didInsertElement: function() {
       // this.$().select2();
     }
});

This render my component fine, but the part it never goes to true for the if statement (installed ember-truth-helpers for that)

<select style="width:100%">
    <option value=""></option>
    
        
            <option selected="selected" value=""> YEAH</option>
        
            <option  value="">  </option>
        
    
</select>

Don't want to mix problems, but as you see i commented out the select2 init call. When doing that it make my select a select2 list, but the items are gone (thought still in the markup)




user as |user| not working in Ember

When I'm doing it works but when I'm doing , it doesn't show anything.

I need users since it will be in a nested route.

This works:


  
  

    Sorry, nobody is here.


But this doesn't:


  
  

    Sorry, nobody is here.


I want to pass a Users helper. So, I need .

Any help will be highly solicited.




how to include specific js file in ember.js

I added a .js file into my bower_components folder in my ember app. The file is included in my ember-cli-build.js like app.import('bower_components/script.js'). The app is working correctly on localhost but when i try to upload my app to heroku i got the error message no such file or directory script.

My question is where shall i put the script.js file? Shall i import it somewhere in my app?




Ember - Attempting to register an unknown factory

I have my route structure like this:

abc (route)
    |-- index
    |       |-- route.js (extends base.js)
    |       |-- template.hbs
    |
    |-- edit
    |       |-- route.js (extends base.js)
    |       |-- template.hbs
    |
    |-- base.js (extends Ember.Route)

Now when I am trying to write the unit test for my base.js I am getting the following exception:

Promise rejected before it exists: Attempting to register an unknown factory: route:abc/base

What's wrong I have done that it isn't able to register my base class as route.?

If I change my base.js to route.js then it starts working, but what happen is that the afterModel inside base.js get executed twice when I make transition to abc/index(this is expected behavior). My base class contains code that is required by both of the index and edit route.

Is there any better way to deal with this.?




vendredi 24 juin 2016

Ember.js: How to assert event unbound in component test?

In component code like:

didInsertElement() {
  this.$('.something').on(//...);
},
willDestroyElement() {
  this.$('.something').off(//...);
}

You have the method of querying for events $._data(this.$('.something')[0], 'events'), but when destroyed, the element is gone. Is there a way to assert in test that the event was actually unbound before destroyed?




Dynamic Outlet for Nested Route in Ember JS

I want to create an interface in Ember that resembles something like Netflix's wherein upon clicking on a movie title the content reveals itself below the poster image. My think is the create a nested route w/

Router.map(function() {
  this.route('movies', {path: '/' }, function() {
    this.route('movie', { path: '/:id'});
  });
});

The problem is that I don't know how I can have a inside of each movie component and tell the nested route to render within the corresponding one. Has anyone created something similar to this w/ nested routes?

enter image description here




Set component property to data from store

Seems it's a bad practice to retrieve data from your component, but this is kind of an experiment (hope the code explains itself)

import Ember from 'ember';

export default Ember.Component.extend({
    store: Ember.inject.service(),
    items: [],
    init () {
        this._super(...arguments);
        var store = this.get('store'); 
        let items =  store.findAll('dealtype');
    }
});

While I can see my api is being hit (debug) and data returned (ember inspector) when looping over "items" in my component template, it's always empty.

Curious what I'm doing wrong (learning still)




How do I force Ember to wait for third party scripts to load during integration tests?

I'm trying to write integration tests for a component in Ember that uses a third-party javascript library to enable part of its functionality. The issue I'm running into however is that all of the tests run and finish before the javascript is fully loaded in the browser running the suite.

Is there a way to force Ember to wait for the library to load before running its suite?




Installing Ember Error -- BABEL failed

I've reinstalled ember-cli and I keep getting the following error when launching the server:

File: modules/ember-inflector/index.js
The Broccoli Plugin: [Babel] failed with:
ReferenceError: [BABEL] modules/ember-inflector/index.js: Unknown option: /Users/.babelrc.presets

Has anyone encountered this issue?




Proper way to compose an application in Ember 2 using custom addons and blueprints

I'm migrating a collection of tools and apps from Ember 0.10 to Ember 2. We have a 'core' application + plugins + multiple apps that are composed using the'core' app and plugins.

A high level summary:

  • core-application ('core')
    • contains basic logic for templates + shared business logic across All apps, including routes
  • plugins
    • shared templates and logic that can be reused across apps (but not needed by all)
  • application
    • is composed of elements from core-application, plugins, + any app specific code. a note that routes should be able to be 'pulled in' from 'core'

In the current Ember 0.10 app structure, this has worked by modifying grunt tasks to build the apps in a quick, fairly fool-proof way.

Now, in Ember 2, it appears that this sort of pathway for app development is provided by using addons and blueprints. I suspect my 'core' app should become a 'blueprint' and plugins could be either an 'addon' OR 'blueprint' based on what is required by them. I'm writing proof of concept code now, but I have the following questions:

  1. what does the --blueprint flag for the ember addon command do? I see that it essentially generates an app structure, but I don't see any realy documentation regarding where to go from there. This appears to to be what I want to use for my 'core' app, but the documentation is lacking here.
  2. If the above --blueprint flag isn't what I want for this kind of set up, is there a better approach I should be considering?
  3. Any other info regarding the above that folk with greater Ember 2 + ember-cli experience than I have can share on this would be hugely helpful.

Thanks in advance for any all feedback.




Show loading template in Ember

I have been doing a lot of tinkering with this and can't seem to get it working. I am looking to show my loading template while waiting for my model promise to return.

My understanding is, by default, if I have app/templates/loading.hbs, this template will be rendered across all routes. However, even with that template in place whenever I switch between routes the old route remains displayed until the model returns, at which point my liquid fire transition occurs and you're taken to the next route.

I have tried various version of creating nested loading templates for each route, tried creating subroutes for each route for the loading template, and have even messed with the beforeModel/afterModel methods that are available but I am making no progress. This is the last hurdle I want to cross before launching and am perplexed as to why I can't get it working. Here is a bunch of my code I feel is relevant.

Note: I am using Ember CLI and Liquid Fire. My data is also being returned to the model from am Ember Service for the time being.

Router

Router.map(function() {
  this.route('reviews', function() {
    this.route('index', {path: '/'});
    this.route('review', {path: '/:review_id'});
  });
  this.route('movies');
  this.route('about');
});

app/template/loading.hbs

<div class="content-container">
    <h1>Ish be loading</h1>
</div>

Slowest Model Route

export default Ember.Route.extend({
    activate() {
        this._super();
        $("html,body").animate({scrollTop:0},"fast");
        $("body").addClass('movies');
    },
    deactivate() {
        $("body").removeClass('movies');
    },
    model() {
        const movies = this.get('movies');
        return movies.getMoviesInAlphOrder();
    },
    afterModel: function() {
        $(document).attr('title', 'Slasher Obscura - Movie Database');
    },
    movies: Ember.inject.service()
});

app.js

App = Ember.Application.extend({
    modulePrefix: config.modulePrefix,
    podModulePrefix: config.podModulePrefix,
    Resolver,
    ...
});
loadInitializers(App, config.modulePrefix);

I have read the docs on Ember's site along with various other Google resources and can't seem to figure out why my loading template isn't rendering at all. Any help would be awesome! Thanks!




Ember: dealing with key up event, mobile Firefox on Android

I have a key Up event in my component which is not firing in mobile Firefox on Android. All is well on Chrome. I've read that that the key up event isn't supported on mobile FF, and have read about some solutions if you're using jQuery eg Key event doesnt trigger in Firefox on Android when word suggestion is on but I don't know how to fix this when using a component in Ember..

So in my component I have

keyUp(event) {
  // eg this.set('disabled',false)
},

I'm using the event for both a contact form and an autocomplete search. I can live with it on the contact form but not sure what do if the search doesn't work on mobile FF!

Does anyone know of a solution?

Many thanks in advance.




Display Location

I want enter the location in a form which contain location and click on submit button that location should be display in google map. the google map should be display in the next page and i want to display near by hospitals with icon.

I tried it but i am not getting.

app/template/newcase.hbs

<form class="form-horizontal">

          <div class="form-group">
            <label class="col-md-4 control-label"     for="textInput2">Location</label>
            <div class="col-md-8">
              
            </div>
          </div>

          <div class="form-group">
 <label class="col-md-4 control-label" for="textInput2"></label>
   <div class="col-md-8">
  <button  type="button" class="btn btn-primary">Submit</button>
  <button type="button" class="btn btn-default">Cancel</button>
</div>

app/route/newcase.js

import Ember from 'ember';
export default Ember.Route.extend({
 model: function() {
 return this.get('store').findAll('case');
    }
 });

app/controller/newcase.js

 import Ember from 'ember';
 export default Ember.Controller.extend({
    actions:{
           addCase: function() {
                 var location = this.get('location');
           var newCase = this.store.createRecord('case', {
              location : location
            });
  newCase.save();
  this.setProperties({
 location: ' ',
  });
  }
 }
});

app/model/case.js

 import Model from 'ember-data/model';
 import attr from 'ember-data/attr';
 export default Model.extend({
   location: attr('string')
 });

app/template/component/new-case.js

import Ember from 'ember';
export default Ember.Component.extend({
  actions: {
        submit() {
        if (Ember.isPresent(this.get('case.location'))) { 
        this.set('mapIsShown', true);
            }
  },
 } 
});

I changed app/template/newcase.hbs to app/template/component/new-case.hbs

app/template/index.hbs

please tell me how to display location and near by hospitals and how to add lat,lang of each hospitals




Run only acceptance test in Mocha

Is there a way to run just a given acceptance test? We have a bunch of integration tests and I just want to see how my acceptance test runs. From the command line, I'm using ember test --serve, but I'd like to run just this specific test. All my tests are in one file and I only want to run those. Thanks




Ember - Custom adapter and serializer for multiple models

I am using RESTAdapter and RESTSerializer for integrating rest service in my ember project. I am able to do the rest service operation with the default ApplicationAdapter(Extend RESTAdapter) and I am able to create custom adapter for specific models.

I want to create a custom adapter which can be used for some specific set of models.

example,

//Application adapter extends RESTAdapter

var LookupAdapter = ApplicationAdapter.extend({
   host: Properties.LookupServiceHost,
   namespace : Properties.LookupServiceNamespace,
});

export default LookupAdapter;

I have some models like country, language etc. For fetching and populating data in data store, now I am using separate adapter, serializer(for handling request, response) for each model. I want those specific models to be worked with LookupAdapter. Can we assign this adapter to model anyway so that these models will use the LookupAdapter/LookupSerializer?




ember js - value returned from computed property looks cached

I am having this weird issue while returning an array from a computed property. I got to know the problem exactly (as below), but not sure about solution. Have created a twiddle for demo purpose to explain.

Case 1: http://ift.tt/28SmCgT

Steps:

a) Check the first checkbox and if we see the value of "arr" in console, the "newprop" property will be added to each object in "arr"

b) Un check the same checkbox, see the console, the same "arr" is returned with that "newprop" still there. But I was assuming, it wouldn't have been there, as there is a check for that in if condition.

So, after little troubleshooting, I came up with this identical next twiddle.

Case 2: http://ift.tt/28UPlEG

perform the same steps and we see that this time the "arr" doesn't have "newprop" when the checkbox is unchecked

The only difference between twiddle is that the array (having data/model) in the first one is defined in "getData" itself and in second, its taking it from another computed property "what".

What I am looking for: I need to have case 1 twiddle working, but when the checkbox is unchecked, the "arr" should return the actual original "arr" without the "newprop". Also, need to understand why its happening. The only thing changed is that fetching the data directly inside fn or via another computed property.




Bootstrap components (model, tab, dropdown) are not working when switching the routes in EmberJs

Bootstrap components (model, tab, dropdown) are not working when switching the routes in EmberJs

I have two in my application.hbs, one for login and other for all other pages.


    <div class="main"><div>

    <div class="login"></div>
 

Initially the bootstrap components are working fine, If i transition to login and come back to other routes then the components in other routes are not working.

The tabs worked before are not clickable. The dropdown menu are not clickable. The model is not showing up on clicking on button.

If i use same outlet for both routes then it works fine.




jeudi 23 juin 2016

Ember.js: native input type="number" binding broke when constraining value

Using the new one-way binding of native inputs, I'm trying to stop the data at "999". It appears to constrain it once and reset it back to "999", but then the binding is lost and it continues unbounded.

<input type="number" value= oninput= />

js:

actions: {
  update(value) {
    if (value > 999) {
      this.set('count', 999);
    } else { 
      this.set('count', value);
    }
  }
}

twiddle that demonstrates issue: http://ift.tt/291dkyg

Am I doing something wrong?

linking github issue: http://ift.tt/28QylNH




Application Initializer vs Application Instance Initializer

I can't seem to figure out the difference between the two. The only difference I could see from the example is if somehow two instances of the application were running? How is that even possible?

Would someone be able to explain the difference between the two, and maybe with an example? I can't seem to wrap my head around the documentation: http://ift.tt/28SUEnf




EmberJS Table Component

Hey guys does anyone know any table component that works with EmberJS 2.6? My requirements are next:

Fixed header
Resizable columns
Sortable by column(s)

I know about these one but it does not work with current EmberJS version and it looks like it wont in near future...I tried two forks that looks decent but no luck, so im looking for replacement. Also i dont mind using some heavy library's i dont need since its for node webkit app.




How can I get the session stored in a Ember-Simple-Auth session?

I'm using ember-simple-auth to manage my app authentication.

I have implemented my own authenticator, authorizer and adapter.

Source code

 Authenticator

import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';

export default Base.extend({

  tokenEndpoint: 'http://localhost:9000/0/auth/',

  restore: function(data) {
    console.log("restore");
    console.log(data);
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate: function(options) {
    return new Ember.RSVP.Promise((resolve, reject) => {
      Ember.$.ajax({
        url: this.tokenEndpoint + options.method,
        type: 'POST',
        data: JSON.stringify(options.data),
        contentType: 'application/json',
        dataType: 'json'
      }).then(function(response) {
        console.log("OK!");
        console.log(response);
        Ember.run(function() {
          console.log("resolve: "+response.data.encodedToken);
          resolve({
            token: response.data.encodedToken
          });
        });

      }, function(xhr, status, error) {
        var response = xhr.responseText;
        console.log("ERROR");
        console.log(response);
        Ember.run(function() {
          reject(response);
        });
      });
    });
  },

  invalidate: function() {
    console.log('invalidate...');
    //return Ember.RSVP.resolve();

    Ember.$.ajax({
        type: 'POST',
        url: this.tokenEndpoint + 'logout',
      }).then(() => {
        resolve(true);
      }, () => {
        reject();
      });
  }
});

Authorizer

import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';

export default Base.extend({
  authorize: function(jqXHR, requestOptions) {
          console.log(requestOptions);
          console.log("---- Authorize ----");
          var accessToken = this.get('session.content.secure.token');
          console.log(this.get('session'));
          if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
              jqXHR.setRequestHeader('Authorization', accessToken);
          }
      }
});

 Adapter

import Ember from 'ember';

import JSONAPIAdapter from 'ember-data/adapters/json-api';

import singularize from 'ember-inflector';

export default JSONAPIAdapter.extend({
  namespace: '0',
  host: 'http://localhost:9000',
  session: Ember.inject.service('session'),
  headers: Ember.computed('session.token', function() {
    console.log("Sending header...");
    return {
      'Authorization': 'MYTOKEN'
    };
  }),

  pathForType: function(type) {
    return Ember.String.underscore(type);
    //return singularize(type);
  },

});

Questions

I would like to know how to get the stored token in the authentication process, inside the adapter to inject the encoded token in the header Authorization.

And another question, when is it called the authorizer?




Ember js - Filter list with nested arrays in JSON/Model

I have been trying to filter a list using the below code.

controller.js

return this.get('model').filter(function(item, index, enumerable){
    for(var i=0;i<item.options.length;i++){
      return item.options[i].key == "one"
    }
  });

I have a nested JSON and want to filter on basis of some nested properties. Below is my JSON and also a blob link to it.

JSON - http://ift.tt/28Qk7tZ

enter image description here

So, the need is to filter this object which has 5 child objects, on the basis of "key" property, as shown in screenshot. I have no idea if that is actually achievable using the above filter or not.

The above code will return true as soon as it finds first "one". But i want to loop through all objects in "options" array and filter based on key, as there might be more matching "key" and hence want to return true for all those matching one's.




Checking value of mixin property in Ember integration test

I'm writing an integration test for an Ember component that uses a mixin. Based on user interaction with the component, a property on the mixin's controller is toggled (boolean). How can I check that the value has been set? Should I inject the mixin's controller into the test? If so, what is the syntax? I can't find it googling. Thanks




Error calling custom API with EmberJS Adapters

I'm using JSONAPIAdapter with some customization to call my own API (developed in PlayFramework) but I get these errors:

vendor.js:9486 OPTIONS https://localhost:9000/0/calendar net::ERR_SSL_PROTOCOL_ERROR

vendor.js:38661 Error while processing route: calendars.index Ember Data Request GET https://localhost:9000/0/calendar returned a 0
Payload (Empty Content-Type)
 Error: Ember Data Request GET https://localhost:9000/0/calendar returned a 0
Payload (Empty Content-Type)

    at new Error (native)
    at Error.EmberError (http://localhost:4200/assets/vendor.js:26707:21)
    at Error.AdapterError (http://localhost:4200/assets/vendor.js:146849:16)
    at Class.handleResponse (http://localhost:4200/assets/vendor.js:148098:14)
    at Class.hash.error (http://localhost:4200/assets/vendor.js:148187:29)
    at fire (http://localhost:4200/assets/vendor.js:3498:31)
    at Object.fireWith [as rejectWith] (http://localhost:4200/assets/vendor.js:3628:7)
    at done (http://localhost:4200/assets/vendor.js:9070:14)
    at XMLHttpRequest.<anonymous> (http://localhost:4200/assets/vendor.js:9426:10)logError @ vendor.js:38661error @ vendor.js:38604triggerEvent @ vendor.js:38720trigger @ vendor.js:63599trigger @ vendor.js:63413(anonymous function) @ vendor.js:63233tryCatch @ vendor.js:63932invokeCallback @ vendor.js:63947publish @ vendor.js:63915publishRejection @ vendor.js:63850(anonymous function) @ vendor.js:42180invoke @ vendor.js:10459flush @ vendor.js:10523flush @ vendor.js:10331end @ vendor.js:10686run @ vendor.js:10808join @ vendor.js:10828run.join @ vendor.js:31307hash.error @ vendor.js:148190fire @ vendor.js:3498fireWith @ vendor.js:3628done @ vendor.js:9070(anonymous function) @ vendor.js:9426
vendor.js:42222 Error: Ember Data Request GET https://localhost:9000/0/calendar returned a 0
Payload (Empty Content-Type)

    at new Error (native)
    at Error.EmberError (http://localhost:4200/assets/vendor.js:26707:21)
    at Error.AdapterError (http://localhost:4200/assets/vendor.js:146849:16)
    at Class.handleResponse (http://localhost:4200/assets/vendor.js:148098:14)
    at Class.hash.error (http://localhost:4200/assets/vendor.js:148187:29)
    at fire (http://localhost:4200/assets/vendor.js:3498:31)
    at Object.fireWith [as rejectWith] (http://localhost:4200/assets/vendor.js:3628:7)
    at done (http://localhost:4200/assets/vendor.js:9070:14)
    at XMLHttpRequest.<anonymous> (http://localhost:4200/assets/vendor.js:9426:10)

When I enable mirage, I don't get any error.




Add together all data for each date

Ember 2.5

I have a model called journey with many journeys as JSON data. Most of the journeys have the same date as another journey other.

// journey JSON example
{
    id: 1,
    date: "2016-02-01",
    emissions: 2,
},
{
    id: 2,
    date: "2016-02-01",
    emissions: 3,
},

I want to display this data on a line graph with date on the x axes and the total emissions for that data on the y.

How can I gather this information so that there is one of each date with the total emissions. This array will need to be created as the route the chart is display in in loaded as the data will change a lot.

Also, using ember-cli-chart, how can I display this data on a graph?




Show parent template with next one

I have navigation bar and after clicking that bar disapears, but if I go straight to necessary url the bar appears.

Router:

  Router.map(function () {
  this.route('apis', function () {
    this.route('show', {
      path: '/:api_id'
    });
  });
});

Router apis/index:

import Ember from 'ember';
export default Ember.Route.extend({
  model() {
    return this.store.findAll('api');
  }
});

Router apis/show:

import Ember from 'ember';
export default Ember.Route.extend({
  model() {
    return this.store.findAll('api');
  }
});

Template apis/index and apis/show (same):

 <div class="panel-body">
       
               
                    
               
       
 </div>

So if I go to /apis or /apis/1 the bar is showing, but if I go from /apis to /apis/1 by clicking on link, the bar is not showing.




mercredi 22 juin 2016

Ember find average of key elements

I'm trying to this computed property to work by selecting individual scores of a movie, and finding the average. It's been a bit tricky, but this is what I have so far...

testing: Ember.computed('movie.title', 'movie.rating', function() {
return this.get('movie.title') + ', ' + this.get('movie.rating');
}),
averageScore: Ember.computed('review.@each.score', function() { //Used to determite each score of review
return this.get('review').(function(sum, review) {
  return sum += review.get('score');
}, 0) / this.get('reviews').get('length');

}),

I know I'm missing something, any suggestions?




Ember JS: Customizing adapter to include multiple parameters

I currently have a database with 2 objects:

  1. Role
  2. Permission

ONE Role can have MANY permissions. I currently have my Role adapter setup as:

export default DS.RESTAdapter.extend(DataAdapterMixin, {
  namespace: 'v1',
  host: ENV.APP.API_HOST,
  authorizer: 'authorizer:application',
  pathForType: function(type) {
    return 'staff/roles';
  }
});

By default, when a Permission is added to a Role, it generates this request:

Request:

PUT /v1/staff/roles/1

Body:

{
  "name": "name_of_role"
  "permissions": [
    {
      "id": "3", 
      "name": "name_of_permission"
    },
    ...
  ]
}

I'd like to customize my adapter to produce a request that looks like this instead:

Request:

PUT /v1/staff/roles/1/permissions/3

Body:

<None>

Can someone please tell me how I can go about doing this? Updating the server api to accommodate Ember JS is unfortunately not an option.




Fetching HasMany Ember Relationship data asynchronously form Mirage

I have model which has a hasMany async relationship,

export default Model.extend({
    name: attr(),
    description: attr(),
    metricNamespaces: hasMany('metric-namespace', {
        async: true
    })
});

Here is a sample jSONAPI doc of a model instance

{
  "data": {
    "type": "context",
    "id": "1",
    "attributes": {
      "name": "O'Reilly Inc",
      "description": "Aut mollitia mollitia esse inventore est consequatur mollitia ex dolores. Deserunt est dicta temporibus eius. Id dicta molestiae nostrum odio."
    },
    "relationships": {
      "metricNamespaces": {
        "data": [
          {
            "type": "metric-namespace",
            "id": "8"
          }
        ]
      }
    }
  }
}

I have an afterModel hook in a route which tries to fetch the relationships

model.get('metricNamespaces').then((success) => {
    console.log("Success", success);
}, (error) => {
    console.log("Error", error);
});

I expect this to trigger a get request to Mirage. But this never triggers a get request (Which should fail since I don't have a mirage route for the metric-namespace get)

Can someone help me figure out what I am missing?




Ember Loading Template with Liquid Fire

I have searched previous questions but have yet to have any luck with this issue. I am trying to display my loading template in between routes as the model is loaded. I am using Ember CLI and Liquid Fire as well. My understanding from what I've been reading is by default, if I have app/templates/loading.hbs this should automatically be inserted into my application template outlet in between routes. However, that is not the case in my instance and I'm not finding the what I need to know in the Docs. And since I am not looking for route-specific loading, I am under the impression I can push this to the application level and display the same loading template for all routes.

Here is what I currently have.

Router

Router.map(function() {
  this.route('reviews', function() {
    this.route('index', {path: '/'});
    this.route('review', {path: '/:review_id'});
  });
  this.route('movies');
  this.route('about');
});

templates/loading.hbs

<div class="loading-pane">
    <div class="loading-message">
        Loading stuff, please have a cold beer.
        <div class="spinner"></div>
    </div>
</div>

Example Route (movies.js - the longest load time)

export default Ember.Route.extend({
    activate() {
        this._super();
        window.scrollTo(0, 0);
        $("body").addClass('movies');
    },
    deactivate() {
        $("body").removeClass('movies');
    },
    model() {
        const movies = this.get('movies');
        return movies.getMoviesInAlphOrder();
    },
    movies: Ember.inject.service()
});

Any help with not only solving this issue but helping me understand the loading states would be greatly appreciated. Thank you!




Ember: "Map" mismatching api objects (asp.net web api) to ember models

From what I’ve learned so far I know I have to do something in the serializer to solve the following, but a bit lost…

My api, return an object named PortfolioSummaryDto, and my Ember model is named “portfoliolistitem”.

This gives me the following error (which make sense) Encountered "portfolio_summary_dtos" in payload, but no model was found for model name "portfolio-summary-dto" (resolved model name using dealview1@serializer:-rest:.modelNameFromPayloadKey("portfolio_summary_dtos"))

Going forward I’d like to call any API call, where the returned object/s and its names (and property names) are totally different from my Ember models.

Can someone point me to some reading how one “map” api objects to ember models?