mercredi 28 février 2018

Can i use Emberjs + PHP + MySQL + Firebase > Emberjs

Our platform is a collaborative web design and marketing platform.

We are using Ember js on the frontend that speaks to our backend(laravel) via Jsonpatch.

Our DB is MySQL, so it is relational.

This solution works fine for us, but there is a new need to bring in the collaborative way of working in our app.

So real time updates are needed!

We also use Firebase for some event driven frontend data updates, but now we are thinking to migrate completely to firebase.

Again, our DB is relational but Firebase is non-relational. So what will be the best way to go with in our case?

Is there a way for our backend to still work for backend validations and permission checks for DB .read and .write operations for different user types and user groups.

So in this case we will have Emberjs - Laravel - Mysql - Firebase - Emberjs, so that our frontend will send save calls to our backend, which will normally update the mysql if the user has enough permissions, which will then let Firebase know about the changes and push that data back to Emberjs.

Do you think this is a good idea or do you have any other recommendation?

Thank you so much!

Gev




Firefox browser disconnect issue when running tests via testem

I am trying to run my ember tests in parallel using ember exam. However when I run the tests I am frequently getting browser disconnect issue, with following log:

[16:41:10][Step 6/6] not ok 561 Firefox - error
[16:41:10][Step 6/6]     ---
[16:41:10][Step 6/6]         message: >
[16:41:10][Step 6/6]             Error: Browser disconnected
[16:41:10][Step 6/6]             Stderr: 
[16:41:10][Step 6/6]              *** You are running in headless mode.
[16:41:10][Step 6/6]             [Parent 12706, Gecko_IOThread] WARNING: pipe error (45): Connection reset by peer: file /build/firefox-8HKHfQ/firefox-57.0+build4/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 353
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]             ###!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]             ###!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]             ###!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]             
[16:41:10][Step 6/6]         Log: |
[16:41:10][Step 6/6]             { type: 'error', text: 'Error: Browser disconnected' }
[16:41:10][Step 6/6]             { type: 'error',
[16:41:10][Step 6/6]               text: '*** You are running in headless mode.\n[Parent 12706, Gecko_IOThread] WARNING: pipe error (45): Connection reset by peer: file /build/firefox-8HKHfQ/firefox-57.0+build4/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 353\n\n###!!! [Parent][MessageChannel] Error: (msgtype=0x24001F,name=PContent::Msg_PreferenceUpdate) Channel error: cannot send/recv\n\n\n###!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv\n\n\n###!!! [Parent][MessageChannel] Error: (msgtype=0x150083,name=PBrowser::Msg_Destroy) Channel error: cannot send/recv\n\n' }
[16:41:10][Step 6/6]     ...

I am running firefox version 57, version 59 is better but even there I see this issue quite frequently, chrome however seems to fare well but on occasion it fails too. Initially I thought its because I am running in headless mode, but even in non-headless mode things do not get any better. And my testem.js file is:

let today = new Date();
const testWindowWidth = 1920;
const testWindowHeight = 1080;

/**
 * Exports configuration to run tests via testem.
 * There are issues with running the test in firefox in headless mode.
 * Chrome however works fine with the provided configuration.
 * @see : https://github.com/testem/testem/issues/1117
 * */
module.exports = {
    'framework': 'qunit',
    'test_page': [
        'tests/index.html?hidepassed&nojshint'
    ],
    'disable_watching': true,
    'parallel': -1,//sky is the limit
    'launch_in_ci': [
        'Firefox'
    ],
    'launch_in_dev': [
        'Chrome'
    ],
    'browser_args': {
        'Firefox': [
            `-headless`,//comment this line out for debugging purpose
            `-width ${testWindowWidth}`,
            `-height ${testWindowHeight}`
        ],
        'Chrome': [
            '--headless',//comment this line out for debugging purpose
            '--disable-gpu',
            '--remote-debugging-port=9222',
            '--remote-debugging-address=0.0.0.0',
            '--no-sandbox',
            '--user-data-dir=/tmp',
            `--window-size=${testWindowWidth},${testWindowHeight}`
        ]
    },
    'browser_start_timeout': 2 * 60,
    'report_file': `tests/logs/${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}/${today}.txt`,
    'browser_disconnect_timeout': 2 * 60
};

I don't know if the problem is with testem configuration or the browser itself! Your help/suggestions will be much appreciated, thanks.




How to focus on input after power-select-multiple is rendered?

I want to be able to search right after the webpage is rendered, instead of click on the search box then start typing. However when I trying to mimic focusInput in original source code, it doesn't work.

It could be reproduced by visit https://ember-power-select.com/docs/multiple-selection and run document.querySelector('.ember-power-select-trigger-multiple-input').focus() which is focus on an input tag.

I expected to see something like this screen shot 2018-02-28 at 1 44 06 pm

, but actually nothing happened.

I also tried to .click() on all parent html elements of that input, but nothing happened

Any help?




Not to get new data from server with Ember.js

I has a site based on Ember.js. This site has a textarea where models' field message is set. When user changes this field I make model.save(). Everything is ok but one thing: if I write something while save API request is not finished, text will be flushed to the version been saved to server. How to explain to Ember that I want to use client version of this field, not server version? Sorry for my english :(




Handlebars display object property dynamically by property name


<tr>
    <td>
        
    </td>
     // line 27
        <td>
            
             // what I tried
            
        </td>
    
</tr>


In the template I have a list of modelItems. In the table there are some certain columns displayed but there also might be optional ones in the selectedColumns list. As line 27 I am looping through selectedColumns to display them but no luck. How is it possible Handlebars to display object property dynamically by property name?


in JS it would something like

foreach (items in selectedColumns) {
    console.log(item.name);
    foreach (column in selectedColumns) {
        console.log(item['"'+column+'"']);
    }
}




mardi 27 février 2018

afterRender vs didInsertElement

Whats the difference between the following 2 things in ember.js?

Is there a rule of thumb for when one is preferred over the other ?

1) afterRender run loop

2) didInsertElement hook




How can I push JSONobject into Ember Array?

I tried it as below but it didn't work. Shows error in pushObject line. What is the correct way to make it work ?

   infantJsonArr: Ember.A(),
....//jsonObject is
var jsonObject = '{ "traveller_name":"Traveller Name"}'
............//later adding in infantJsonArr  
this.get('infantJsonArr').pushObject(JSON.parse(jsonObject));

`




Ember 3 conditional statement

Why while this code does render,


<ol>
  
    <li ></li>
  
</ol>

<ul>
  
    <li ></li>
  
</ul>


this does not?

}
  
    <li ></li>
  
}

The last snippet emits <ol></ol> before the list and no closing tag after the list:

<div id="ember260" class="ember-view"><h2>Ordered List Of Things</h2>
<ol></ol>
    <li data-ember-action="" data-ember-action-261="261">yarn</li>
    <li data-ember-action="" data-ember-action-262="262">feathers</li>
    <li data-ember-action="" data-ember-action-263="263">dinner plate</li>
    <li data-ember-action="" data-ember-action-264="264">sheep</li>
</div>

and why does this code not even compile?


<ol>

<ul>

  
    <li ></li>
  

</ol>

</ul>


Error:

Unclosed element ol (on line 2).




Ember concat two computed statements in one

Using computed "showField: Ember.computed.or() && Ember.computed.equal()" in order to wither to show a field or not. the value i get is not correct. How can concatenate the two and get the correct Boolean value ??

PS: i am using ember js 1.8




Component life-cycle

I'm trying to understand the issue in the ember-form-for (https://github.com/martndemus/ember-form-for/blob/master/addon/components/form-field.js#L64) but IMHO the code is not that important, it is just an ordinary component.

The component works perfectly when re-rendering does not occur. In the init() we will do set(this, 'name', 'value') and it works as expected. But after re-rendering, the init() is not called as expected (https://guides.emberjs.com/v3.0.0/components/the-component-lifecycle/), the object has same identifier as before rendering but the value that were set in the init() are lost. And I do not understand why.




Parsing data from RESTful api pokeapi.com

I'm new to Ember and I'm have another BIG(problem) question. I am trying to show the details of each pokemon based on the REST API https://pokeapi.co, the details of each pokemon are in https://pokeapi.co/api/v2/pokemon/pokemon_name/, (example: https://pokeapi.co/api/v2/pokemon/bulbasaur/)

This Twiddle have all my code

i dont know how to serialize it and show the data of each pokemon in monster-detail.hbs

The details example: https://pokeapi.co/api/v2/pokemon/bulbasaur

abilities<- Need this data
    0:
       slot: 3
       is_hidden: true
       ability:
        url: "https://pokeapi.co/api/v2/ability/34/"
        name: "chlorophyll" <- Need this data
    1:  
       slot: 1
       is_hidden: false
       ability: 
         url: "https://pokeapi.co/api/v2/ability/65/"
         name: "overgrow"  <- Need this data
stats: <- Need this data
    0:  
       stat:
        url: "https://pokeapi.co/api/v2/stat/6/"
        name: "speed" <- Need this data
        effort: 0
        base_stat: 45 <- Need this data
    1:  
       stat:    
        url: "https://pokeapi.co/api/v2/stat/5/"
        name: "special-defense" <- Need this data
        effort: 0
        base_stat: 65 <- Need this data
    2:  
       stat:
        url: "https://pokeapi.co/api/v2/stat/4/"
        name: "special-attack" <- Need this data
        effort: 1
        base_stat: 65 <- Need this data
    3:  
       stat:    
        url: "https://pokeapi.co/api/v2/stat/3/"
        name: "defense" <- Need this data
        effort: 0
        base_stat: 49 <- Need this data
    4:  
       stat:    
        url: "https://pokeapi.co/api/v2/stat/2/"
        name: "attack"<- Need this data
        effort: 0
        base_stat: 49 <- Need this data
    5:
       stat:
        url: "https://pokeapi.co/api/v2/stat/1/"
        name: "hp" <- Need this data
        effort: 0
        base_stat: 45 <- Need this data
name: "bulbasaur" <- Need this data
weight: 69 <- Need this data
height: 7 <- Need this data
id: 1 <-Don't need
base_experience: 64 <- Need this data




How to make a model automatically reload and fetch data when the data in the DB changes?

I am using ember-cli-mirage for the past few days. I have some doubts regarding it.

Question :

How to automatically reload the model after the data in ember-mirage has changed?

I mean: After performing a $.post() operation on ember mirage data, schema is changed. This has to be reflected in the template. But, since the model for the template is already run, the model hook is not run again!

Kindly help me regarding this.

Thank you.




Using a value from Component in Template hosting Component

I have a stacked bar chart component that on click, records the three values of the 'stack' and allows me to print them in the component template.

I would like to use these values in the parent template that is hosting the component but I am not sure how to send his data 'up'. I attempted to follow the proceedure in this question but I couldn't get it to work. I have also been unable to diagnose why this solution doesn't work as I receive no console or build errors.

My code is below:

Relevant Component Code:

.on('click', d => {
        let clickedLabel = d.data.label;
        let clickedCount1 = d.data.count1;
        let clickedCount2 = d.data.count2;
        let clickedCount3 = d.data.count3;

        if (this.get('on-click')) {
          this.get('on-click')(clickedLabel);
          this.set('selectedCount1', clickedCount1);
          this.set('selectedCount2', clickedCount2);
          this.set('selectedCount3', clickedCount3);

        } else {
          if (clickedLabel === this.get('selectedLabel')) {
            this.set('selectedLabel', '');
            this.set('selectedCount', '');
          } else {
            this.set('selectedLabel', clickedLabel);
            this.set('selectedCount1', clickedCount1);
            this.set('selectedCount2', clickedCount2);
            this.set('selectedCount3', clickedCount3);

          }

Component in template:



There is currently no relevant code in the controller for the parent template.




lundi 26 février 2018

Download files in ember: using Ember-cli-file-saver

It might be plain ignorance from my part but I have only managed to download a file generated by the api using the model method mention in the documentation. Using a component I am quite blind.

The specific question would be: where do I pass the mention arraybuffer:true to the application adapter or to a custom ajax request? Do you have a working example?

Here is a simple try using an ajax service:

import Component from '@ember/component';
import FileSaverMixin from 'ember-cli-file-saver/mixins/file-saver';
import { inject as service } from '@ember/service';

export default Component.extend(FileSaverMixin, {
  tagName: 'div',
  ajax: service(),
  store: service(),
  click() {
    this.get('ajax').request('/excel', {
      options: {
        arraybuffer: true
      }
      }
    ).then((content) => {
      console.log(content);
      this.saveFileAs(this.get('filename'), content, this.get('contentType'));
    }).catch((error) => {
      console.log(error);
    })
  }
});

And this is my adapter:

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
import AdapterArrayBufferMixin from 'ember-cli-file-saver/mixins/adapter-arraybuffer-mixin';
import ENV from 'efac-front/config/environment';

export default DS.JSONAPIAdapter.extend(
  DataAdapterMixin,
  AdapterArrayBufferMixin,
  {
    authorizer: 'authorizer:token',
    namespace: 'api',
    host: ENV.host
  }
);

I keep getting an error of SyntaxError: Unexpected token P in JSON at position 0... because it is trying to interpret an array buffer or binary response as json data.

I very much appreciate any light you can throw here




Ember 3.0 acceptance redirect test hangs forever

I have a simple acceptance test written in the modern RFC 268 format for Ember 3.0.

The test is for a page where, if the user is unauthenticated, the URL immediately redirects to /login.

...

module('Acceptance | index', function (hooks) {
  setupApplicationTest(hooks);

  test('visiting / logged out', async function(assert) {
    assert.expect(1);

    // Test hangs here forever.
    await visit('/');

    assert.equal(currentURL(), '/login');
  });
});

This test worked great using the older format with moduleForAcceptance.

Unfortunately, this test hangs forever in Ember 3.0. Am I missing something here? Is there a better way to test a redirect?

There are no errors in the console, and the addition of some console.log statements show that the await is where the test hangs.




Can I use ember-data with Glimmer?

Is it possible to use ember-data with Glimmer, or is the full ember install required? If so how much of Ember core is it possible to ignore (e.g. just use components, no router, etc)?

Also if it isn't possible is there a library that would provide a JSONAPI implementation compatible with Glimmer?




How can I use index while iterating over JSONArray in handlebar?

I am trying to show the details of the adultJsonArr in different and I want to get it saved on action without going into writing lengthy code.

I'm not getting idea of how to use the index while iterating, I tried as mentioned in line no 5 but didn't work( @index also couldn't do job for me).

Any suggestion on how to save the changes made to the input in the adultJsonArr

1.<form> 
2.   
3.    <div id="adult_form">
4.      Adult: 
5.      <input type="text" value="" required> 
6.      <input type="dob" value="">
7.      <input type="text" value="" required>
8.    </div>
9.   
10.  <div >
11.     
12.  </div>
13.</form>




Ember- return the response from a nested promise in a closure action

Using the pattern below I can return the result of a save operation in my route to a component, using closure actions. This works fine.

Route

actions: {
    submit: function(values) {
      var user = this.store.createRecord('user', values);
      return user.save();
    },
  }

Component

this.attrs.submit(values).then((response) => {
  //Handle success
}).catch(error => {
  //Handle error
});

In my submit action, I would like to first fetch the license object that the user belongs to and then set that on the user object before saving, as below.

The problem is that return user.save(); is now in the callback for query operation, and is not being returned from the submit action.

How can I restructure my code so that I can query the license record, and then return the result of user.save() to my component?

submit: function(values) {
  var user = this.store.createRecord('user', values);
  this.get('store').query('license', {
    filter: {
      code: values.licenseCode
    }
  }).then(function(licenses) {
    var license = licenses.get("firstObject");
    user.set('license', license);
    return user.save();
  });
},



dimanche 25 février 2018

How to save a record and its model relationships

In a blog application, a user writes a post and selects some tags for it. When the user clicks Publish, it executes the publish action which currenlty does the following but its obviously not right because, while the post saves, the tags do not. No error is thrown in the console though:

actions: {
  publishPost: function() {
    var post = this.store.createRecord('post', {
      title: this.get('title'),
      body:  this.get('body')
    });
    post.set('tags', this.get('newTags')); // array of tag model objects (post hasMany tags in the model file)
    post.save();
  }
}

I've also tried just directly adding tags: this.get('newTags') to the 'post' object:

actions: {
  publishPost: function() {
    var post = this.store.createRecord('post', {
      title: this.get('title'),
      body:  this.get('body'),
      tags:  this.get('newTags')
    });
    post.save();
  }
}

How is this usually handled in Ember?




ember.js list template keeps getting bigger on each visit

In an Emberjs 2.13.0 app I have a model that looks like this :

import DS from 'ember-data';

export default DS.Model.extend({
    cceIdentifierParent: DS.attr('string'),
    cchCceIdParent: DS.attr('string'),
    nodeType: DS.attr('number')
});

I have a route, 'diagcctreetoplevelonly', which looks like this :

import Ember from 'ember';

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

And a template that looks like this :



  <table>
    <thead>
      <tr>
        <th>
            cceIdentifierParent
        </th>
        <th>
            cchCceIdParent
        </th>
        <th>
            nodeType          
        </th>
      </tr>
    </thead>
    <tbody>
        
           <tr>
              <td>
                
              </td>
              <td>
                
              </td>
              <td>
                
              </td>
            </tr>
        
    </tbody>
  </table>

  <p id="blankslate">
    No Tree Nodes found
  </p>



That works fine the first time that 'diagcctreetoplevelonly' is visited - 12 rows are rendered - but on subsequent visits (without the underlying data having changed) the table rendered by the template has 12 extra rows .




vendredi 23 février 2018

lcov report is not getting generated

I am running my ember tests with embercliblanket, but my lcov reports are not getting generated

pfb my blanket-option.js file

var options = {
  modulePrefix: 'my-ember',
  filter: '//.*my-ember/.*/',
  antifilter: '//.*(tests|template|config).*/',
  loaderExclusions: [],
  enableCoverage: true,
  cliOptions: {
    jsonOptions: {
      outputFile: 'test-output.json'
    },
    lcovOptions: {
      outputFile: 'tmp/lcov.dat'
    },
    reporters: ['lcov'],
    autostart: true
  }
};
if (typeof exports === 'undefined') {
  blanket.options(options);
} else {
  module.exports = options;
}

pfb my testem.js

module.exports = {
  "framework": "qunit",
  "test_page": "tests/index.html?hidepassed",
  "disable_watching": true,
  "launch_in_ci": [
    "PhantomJS"
  ],
  "launch_in_dev": [
    "PhantomJS",
    "Chrome"
  ]
};

I am running tests in cmd as ember test --test-page='tests/index.html?coverage=true'

Tests are success, but the expected lcov.dat files are not getting generated. Cant see any errors as well while running in the browser.

Any clues ?




using Actions inside the input helper

Using the action helper works fine inside a DOM element:

<input value="123"

But then let's say you are using the input helper to generate your input field:

And you want to stick the very same action onto this input helper..

The docs say:

" To dispatch an action on specific events, such as enter or key-press, use the following

"

And yet..

This code does nothing:

I also tried this:

I'm slowly going insane. Can someone point me to the correct way of using actions inside the Ember input helper?

Thanks!




jeudi 22 février 2018

Sending a Query Param to a nested route via Ember

I am trying to send a query parameter via a . This has been achieved elsewhere in the application as follows:



This correcctly send s the user to the cusomterSearch.results nested route with the customerNumber, dateFrom and dateTo params in the URL.

In this part of my application I am trying to achieve the same result in a link-to that goes to a paramterised route. The original link:

  

This is succesfull and takes the user to route mtlcustomer/:id

When I try to add the Query Param as follows:

  

The user is still taken to the mtlcustomer/:id route but without the query param appended.

The route for mtlcustomer/:id mirrors the successfull implementation earlier in the app:

  model(params) {
    let unitNumber = this.paramsFor('results').unitNumber
    let hash = { unitNumber }

    return Ember.RSVP.hash({
      medid: this.get('store').query('mtlcustomer', params, hash),
      mtlhistory: this.get('store').query('mtlcusthistory', params, hash),

    });
  },

  setupController(controller, models) {
    this._super(controller, models);
    controller.set('mtlcustomer', models.mtlcustomer);
    controller.set('mtlcusthistory', models.mtlcusthistory);


  },

The route code probably still needs refining but in the URL bar after the is clicked there is no customerNumber param.




EmberJS parsing data from RESTful api

I'm new to Ember and I keep studying and learning every day. And as a challenge, I'm having great difficulty getting data from the RESTful API pokeapi.co I want to get the names and url of the results https://pokeapi.co/api/v2/pokemon/ to then pass the ID as a parameter and get all data in https://pokeapi.co/api/v2/pokemon/1/ /2 /3 etc.

I'm stuck, please help me.... My Code:

adapter/pokemon.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    host:'https://pokeapi.co',
    namespace: 'api/v2',

    pathForType(){
        return 'pokemon';
    }
});

model/pokemon.js

import DS from 'ember-data';

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

routes/pokemon.js

import Route from '@ember/routing/route';

export default Route.extend({
    model(){
        return this.store.findRecord('pokemon')
//    setupController(controller, model){
//    controller.set('pokemons',model);
    }
});

serializer/pokemon.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({

    normalizeResponse(store, primaryModelClass, payload, id, requestType){
        payload = {
            pokemon: payload
        },
        console.log(payload);
        return this._super(store, primaryModelClass, payload, id, requestType);
   }
});

templates/pokemon.hbs


      <div class="md-list-item-text">
         <h3>#: </h3>
        </div>





Using Universal Links in a Ember JS Cordova Project

I am working on a project that run on emberjs and uses corber to build the app using cordova on mobile devices. What I need to do now is enable deep links. I have come across this plugin and have installed it via corber. Now how do I use the universalLinks module to launch my app at a URL on which a user clicked?




mercredi 21 février 2018

Ember - create default record if model is empty

I have a simple User model, with two fields: name and user_id

When the app starts, I want to check if my User model contains at least one record - if not, I want to create a default "admin" user automatically.

I have the following code in my application route:

model() {

let user = this.store.findAll('user'); // find all users

let record = user.then(function(result) { 
    let first = result.get('firstObject'); // check if we at least one user
    if (first) { // if true, then we have at least one user
      let user_id = first.get('user_id'); // get the first user's id
      // do some more stuff here
    }
    else {
      console.log("no record found"); // no user found, let's create our default user
      let user = this.store.createRecord("user", { // <-- THIS DOESNT WORK - where can I create my record?
        user_id: 1,
        name: 'admin'
      });
    }
});

}

This code works, except that I can't call this.store inside my promise function, since this now belongs to the function.

Would it be better to create an action, and then call that action in my else statement? But then, how would I trigger that action from the model itself?

Any ideas would be helpful at this point. It feels like I'm misunderstanding some fundamental law of Ember (again).




Ember : Close/Cancel a form using 'Esacpe' Key

I have form and and I want to close my form with the escape key. I can't figure out how to implement it. I know I need some keyDown event or so! but where to implement and how do I make it trigger?

<form id = 'myform' >
<div class="usersgroups-headline-label admin-form-headline-label">
  EditAdd User :  () Group : 
</div>
.
.
.
.

<div class="action-buttons">
  
    
  
    
  
  
</div>




Ember abort - how to prevent from forward transition

I am looking a solution to prevent my forward transition from abort. I just want to prevent the back button ( previous page ) transition after mid of a page. how to do that?

here is my try :

willTransition:function( transition ){

            var target = transition.targetName;

            let previousTransition = this.controllerFor(this.routeName).get('previousTransition.targetName');

            console.log( target, 'previousTransition', previousTransition );

            if(this.get('modelProvider').get('cardTxnPage') === true &&  previousTransition ){
                transition.abort();
            }
        },

In above all are correct. But even I am not able to proceed to next page. means it abort prevents both forward/backward by condition.

any one show me the right approach?




mardi 20 février 2018

Emberjs 3.0 tests: how to select link by content

The following is a test that apparently works in Ember.js 2.15, but seem not to work in version 3.0: Failed to execute 'querySelector' on 'Element': 'a:contains('Contact')' is not a valid selector.

import { module, test } from 'qunit';
import { visit, currentURL, click } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';

module('Acceptance | list rentals', function(hooks) {
  setupApplicationTest(hooks);
    test('should show link to contact', async function(assert){
            await visit('/');
            await click("a:contains('Contact')");
            assert.equal(currentURL(),'/contact','should navigate to contact');
    });
});

How to do this in Ember.js 3.0?

I couldn't find it in the online Ember guides. The tutorials seem to refer thus to previous versions.

PS:The application's template file contains

 
    Contact
  




Packaging an ember addon in app.js instead of vendor.js

Is there a way to bundle an ember addon in app.js instead of vendor.js. Addons seem to get packaged into vendor.js by default with no hooks to customize this. In this case both the app and the addon is authored by the same person.




ember-pouch: acceptance test strategies

I am using ember-pouch as my adapter for an ember-cli app (v3.0.0).

For acceptance tests, I'd like to use the pouchDb adapter rather than mock everything. To implement this it seems the best strategy would be to:

1) create a new pouch-db instance at the start of each test and

2) destroy this instance at the end of each test

It seems like the best way to do it would be to use the beforeEach and afterEach hooks in the test. But I've been searching for two days and cannot find any useful documentation on how to implement this strategy.

Can somebody help me out with some pointers on how to implement this strategy on test setup?




Loading model on param route

I've successfully build out my app to have a proper child route and it works as it should when the user navigates through the site, but on load straight to the show route (exhibitions/slug) ember data seems to break; however, I'm still getting the proper response from the API. Here is my code, hope it makes sense..

routes/exhibitions

import Route from '@ember/routing/route';

const { set } = Ember;

export default Route.extend({
  model() {
    return this.store.findAll('exhibition');
  },
  setupController(controller, model) {
    set(controller, 'exhibitions', model);
  }
});

routes/exhibition

import Route from '@ember/routing/route';

const { set } = Ember;

export default Route.extend({
  model() {
    return this.store.findAll('exhibition');
  },
  setupController(controller, model) {
    set(controller, 'exhibitions', model);
  }
});

model for exhibition

import Contentful from 'ember-data-contentful/models/contentful';
import attr from 'ember-data/attr';
import { belongsTo, hasMany } from 'ember-data/relationships';

export default Contentful.extend({
  title: attr('string'),
  body: attr('string'),
  slug: attr('string')
});

router.js

import EmberRouter from '@ember/routing/router';
import config from './config/environment';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('homepage', { path: '/' });
  this.route('exhibitions');
  this.route('exhibition', { path: 'exhibitions/:exhibition_slug'});
});

export default Router;

The error I'm getting in the console is:

Error while processing route: exhibition Cannot read property 'Entry' of undefined TypeError: Cannot read property 'Entry' of undefined

Let me know if anything else is needed!! Thank you!




Update textarea model in Emberjs

I have a component which contains a switch and a yielded form. The switch changes the model used for the yielded form. In the said form, I have a textarea whose value comes from the model. When I update the model in the component, the textarea is bent to the correct model but the value inside it doesn't update. I can't figure out how to do it

Here is my component:

import Ember from 'ember';

const { computed } = Ember;

export default Ember.Component.extend({
  // Properties
  switchField: null,
  defaultModel: null,
  specificModel: null,

  activeModel: computed('switchField', 'defaultModel', 'specificModel', function() {
    if (this.get('switchField')) {
      return this.get('defaultModel');
    } else {
      return this.get('specificModel');
    }
  }),

  editDisabled: computed('switchField', function() {
    if (this.get('switchField')) {
      return true;
    } else {
      return false;
    }
  }),

  renderSwitch: function() {
    Ember.run.schedule('afterRender', this, function() {
      $('.toggle-switch').bootstrapToggle();
    });
  }.on('init'),

  actions: {
    reflectChange: function(value) {
      this.set('switchField', value);
      this.rerender();
    }
  }
});

The template:

<div class="col-xs-12">
  <input data-toggle="toggle" data-onstyle="success" data-offstyle="danger" class="toggle-switch" type="checkbox" checked= onchange= />
  <br>
  <br>
</div>



And how it is used:


  <div class="col-xs-12">
    
      <label class="control-label" for="carrierProcedure">Procédure coursier</label>
      
    
  </div>


I tried to rerender the component but it doesn't work. I don't understand why the value doesn't change since the textarea gets correctly enabled/disabled when I toggle the switch.

Thanks for your help.




What happens when we first boot our app using Ember JS?

I am new to ember and I have been through the Ember JS Documentation for a while and suddenly struck with two questions. I even surfed on the Internet for hours and barely could find a solution. So, here are they:

Question 1:

Quoting Ember Documentation,

The application is entered when your app first boots up. Just like any other route, it will load an application template by default.

application in the above quote represents the application route which according to the doc is loadedwhen app boots and renders the application.hbs. Where is the application route situated?

Question 2:

Where exactly in the control flow does the router.js file get loaded? Before application route or after application route?

Request:

Also I would be thankful if anyone could assist me with the complete flow of the Ember JS (starting when the user enters localhost:4200).

Thanks.




Ember addAddonsToProject() to dependencies instead of devDependencies

I made a Ember addon and I want to install one of it's dependencies to the target app, so I created a blueprint file which contains a afterInstall hook:

afterInstall() {
  return this.addAddonsToProject({
    packages: [{
      name: 'ember-svg-jar', target: '0.12.0'}
    ]
  });
}

This function adds ember-svg-jar to the devDependencies of my target project, but I would like to add it to the dependencies instead. The only documentation I've found don't write anything about such options, but I found something in the code that could help: extraArgs or bleuprintOptions:

/**
@method addAddonsToProject
@param {Object} options
@return {Promise}
*/
addAddonsToProject(options) {
  let taskOptions = {
    packages: [],
    extraArgs: options.extraArgs || [],
    blueprintOptions: options.blueprintOptions || {},
  };

  ...
}

Can anyone tell me how to solve this problem?




Ember.js: access the current component from helper

Looking for any solution (even dirty hacks) to access the current component from a custom helper.

import Ember from 'ember';

export default Ember.Helper.extend({
  compute() {
    ... who is computing me? ...
  }
});




lundi 19 février 2018

generate unique ID in Ember JS or CouchDB

I'm currently using CouchDB/PouchDB as a back-end for my Ember app.

The database automatically generates an unique UUID of 64 letters and numbers for each record, which is good for finding records and ensuring there are never any duplicates.

But my client wants each record to have a simple ID of 001, 002, 003, etc.

This doesn't have to be the actual ID for each record, this would be something like record_idand would only be used by my client internally, for his own convenience (so just a normal integer field, no index or key)

This is super-easy to do in MySQL, since all you have to do is add a primary key. But I'll admit that my knowledge of CouchDB is still pretty limited.

Basically, I'd like to generate simple, auto-incrementing and unique IDs using Ember.js - or CouchDB.

I can't find any way to do this easily, which is quite surprising. This seems like a very common requirement, but I can't find a good solution after about an hour of googling.

Has anyone ever done this before, or do you have any suggestions? I'm out of ideas.

Thanks in advance!




EmberJS - save with relation

If I have a product model and items model in Ember, one product has many items. How can I save this when creating a product? My items is in an array.




Updating page number from service

I am trying to add the page number. for that I have a service so, from there accordingly i can update the page number.

But I am not able to achieve this. any one help me to get it done for me?

service:

import Ember from 'ember';

export default Ember.Service.extend({
  pageIndex:1,
  totalPages:2 //setting total page
});

Route:

model(){ //calling controller
    this.controllerFor(this.routeName).send('pageHandler');
  }

here is my live demo




Not able to get auth-access-token from facebook using authorisation code

I want to create a Facebook enabled login for my ember app, In frontend i am using torii to get the authorisation code from facebook and then i'm posting it to rails enabled backend to get access-token(In the backend i am using omniauth-facebook+devisetokenauth).

But when i do post call from frontend to backend (localhost:3000/user/:provider ) i get following error

`Started GET "/omniauth/facebook?code=AQBy6c48CohDlPqI-fmfQeE9LN6NFFdtBZDuziflFkPjrFKACeT9OwHtfbIpUDufQbX3gXcArcJJRtPv9R9kXtHFWMDZ16k2r3Q6jJ0BdaNqkwwxwjUYmKUhZyllsDYP_GkS5KSq9brqvaSnjJqTI-KZR2s3AbNzYdbyy-Gdzh9zVhpeWTsD0yPBysjdgq2HU9Kj6dCwH37yNp2DnDfMHPWeCev2qjw_N8GU1R-3HOco9dV-MWNVNiQeKP8u88nioPmEL35FlSpycIy43lBL-hgN-iGFnHoVuxjWbH0Nhos_1QiZAbhYLlSjPE_RKu4sX-HT4ldQdsGMh6RoFCKoNTL0&provider=facebook&resource_class=User" for 127.0.0.1 at 2018-02-19 13:57:22 +0530 I, [2018-02-19T13:57:22.043998 #28320] INFO -- omniauth: (facebook) Request phase initiated.

ArgumentError (key must be 32 bytes): ` And is this the right approach.

Thanks




dimanche 18 février 2018

How do I access returned objects using Ember Data?

I have an Ember component that uses Ember Data. I'm just trying to get some data and simply console out one of the values I get back.

The JSON object being returned looks like this:

{
    success: true,
    sets: [
        {
            name: 'Some Name'
        },
        {
            name: 'Some Different Name'
        }
    ]
}

This is what my route looks like:

export default Ember.Route.extend({
    model() {
        this.get('store').findAll('set').then(function(data) {

            data.forEach(function(set, index) {
                console.log(set.name);
            });

            return data;
        });
    }
});

Instead of seeing Some Name and Some Different Name I see some kind of Ember objects:

{
    _dependentKeys: undefined
    _getter: function get()
    _meta: Object { type: "string", isAttribute: true, name: "name" }
    _readOnly: false
    _setter: function set()
    _suspended: undefined
    _volatile: false
    isDescriptor: true
}

How do I access the actual values of my objects?




samedi 17 février 2018

Where is the data coming from in Ember?

I am new to Ember, after I installed ember, I am seeing default welcome-page which is via application.hbs. Can someone please tell me where this data of welcome-page resides? Where is that being pulled from? I want to go through the code. Thanks.




ember js params is exists

So I need to do so that clicking on the store would stop the page with the goods of this store. When passing the store's id through the link URL changes but in the product's route model(params) the params is empty

  import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    address: DS.attr('string'),
    phone: DS.attr('string'),
    shops: DS.belongsTo('shop'),

});


import DS from 'ember-data';

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

});

    import EmberRouter from '@ember/routing/router';
import config from './config/environment';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('shops', function() {
  this.route('new');
  this.route('edit', { path: '/:shop_id/edit' });
});

  this.route('products',{ path: '/products/:shop_id' }, function() {
    this.route('new');
    this.route('edit',{ path: '/:product_id/edit' });
  });

});
export default Router;

import Route from '@ember/routing/route';

export default Route.extend({

  model(params) {
    console.log(params); // this show {}
    return this.store.findRecord('product', params.shop_id);
  },

  actions: {

    deleteProduct(product) {
      let confirmation = confirm('Are you sure?');

      if (confirmation) {
        product.destroyRecord();
      }
    }
  }

})


    <h2>List</h2>
<div class="row">
  

    <div class="col-md-4">
      
      <div class="panel panel-default library-item">
        <div class="panel-heading">
          <h3 class="panel-title"></h3>
        </div>
        <div class="panel-body">
          <p>Address: </p>
          <p>Phone: </p>
          <p>Phone: </p>
        </div>
        </div>
        
        <div class="panel-footer text-right">
          Edit
          <button class="btn btn-danger btn-xs" >Delete</button>
        </div>
    </div>
    
  <h1>  </h1>
   
  
</div>

Now I need to associate the store with the product, record and click on the link to find the goods of this store




How to test computed property that returns PromiseArray in Ember

I have a computed property that asks server for user data and then the other one that computes number of users. To propagate changes into the template, I'm using DS.PromiseArray wrapper. With this wrapper, I can't find an easy way to test this property.

  // model
  users: computed('name', function () {
    let name = get(this, 'name');
    return DS.PromiseArray.create({
      promise: this.store.query('user', { name })
    });
  }),

  numberOfUsers: computed('users', function () {
    return get(this, 'users.length') || 0;
  }),

  // ....

  test('numberOfUsers returns correct number', function (assert) {
    let model = this.subject({
      store: EmberObject.create({
        query() {
          return Promise.resolve([
            { name: 'Thomas' },
            { name: 'Thomas' },
            { name: 'Thomas' },
          ]);
        }
      }),
      name: 'Thomas',
    });

    assert.equal(model.get('numberOfUsers'), 3);
  });

This test fails with 0 !== 3. Any ideas?




vendredi 16 février 2018

Getting proper data in modal

I'm trying to access data two times in my template, once on a list view, and once in a modal view. Upon clicking on the image, the modal will display a lot of the same data, just blown up. I'm having issues. The modal seems to be taking the last set of data, even though it's nested in the each statement. Any ideas? Here's my code...

<div class="row">
  
    <div class="col-xs-12 col-sm-6 col-md-4">
      <div class="shopify-grid-wrapper">
        <div id="#image-wrapper" class="image-wrapper" >
        <div class="img-overlay">
          <p>
            Click for More Details
          </p>
        </div>
          
            <img src= />
          
        </div>
        <div class="description-wrapper">
          <span><p></p></span>
          <p>
            
          </p>
          <p>
            
          </p>
        </div>
      </div>
    </div>

    
      
      <div class="left-side">
        
      </div>
      <div class="right-side">
        
        <div class="Cart ">
          
        </div>
        <p >
          Close
        </p>
      </div>
      
    


  
</div>




rendering templates with #link-to and dynamic segments

I have a simple app to show a list of clients, and a detail page for each specific client.

So basically, two URLs:

/clients/
/clients/:slug/

I've been having some trouble rendering the results from my Client model into a template, specifically when using the #link-to helper with dynamic segments.

I've found two methods for doing so, and while I can get them both to work, I don't know which one is the best and why.

Here is some (simplified) code from my app to explain.

// app/models/client.js
export default DS.Model.extend({
  name: DS.attr('string'),
  slug: DS.attr('string')
});

(my actual model is larger, but these are the only relevant fields)

and here are my routes:

// app/router.js
Router.map(function() {
  this.route('clients');
  this.route('client', { path: 'clients/:slug' });
});

NOTE: I didn't nest the routes, because I didn't want to use the nested template feature.

Here is the route for Clients, where I retrieve my list of clients

// app/routes/clients.js
export default Route.extend({
  model: function() {
    return this.get('store').findAll('client'); // fetch all Clients
  }
});

Finally, here is the route to fetch info for a single Client:

// app/routes/client.js
export default Route.extend({
  model: function(params) {
    return this.store.query('client',  {
      filter: { slug: params.slug } // fetch one specific client, by slug
    });
  }
});

Everything works fine up to here, but my issue starts when displaying the model data in the templates.

There are two "ways", which one is correct??

OPTION A:

//app/templates/clients.hbs
// list all clients using #each

   // pass the "client" object to generate my dynamic routes
    
  


Clicking on any of the generated links will render the client detail template, client.hbs

//app/templates/client.hbs
<h1>Client - </h1>

In this example, I can use model.name to render my model object. That's fine, until I refresh the page! Then the info returned by model.name is obliterated. Same thing if I try to visit the URL directly. I have to go back to /clients and click on the link again to see my client's name.

I then looked for another way to display my data, where the model information would survive a page reload.

OPTION B:

After much reading I found a suggestion to use the specific client slug/id as param for #link-to

// app/templates/clients.hbs
// list all clients using #each

   // specifically use the actual slug/id, and not the object
    
  


But... by passing client.slug instead of client as parameter to #link-to, I can no longer use model.name to display my data. It simply returns nothing!

//app/templates/client.hbs
<h1>Client - </h1> <-- model.name now returns nothing D:

However, using a loop DOES work for some reason:

//app/templates/client.hbs

  <h1>Client - </h1> <-- using loop even though I only have one record :(


But this feels like a hack, why would I need to use a loop to iterate through a single record?

So option B works, and the information is displayed correctly after a page reload, or a direct visit from the URL.

option A feels like the correct way, but reloading the page obliterates the data.

option B actually works and returns the data, but I have to use a loop to iterate through a single record.

I'm extremely confused, any clarification would be greatly appreciated.

Thanks in advance!




jeudi 15 février 2018

ember.js - render() cannot find template specified by `into:` option

I would love some help on this as I've been trying to get this work for a few hours now. It seems like it should be something easy to do.

I'm trying to create a separate layout within my Ember app. For example sake, there's the public application.hbs layout, and a private admin.hbs layout.

On my route/admin.js, I have tried to use the renderTemplate() function to no avail.

route/admin-dashboard.js

import Route from '@ember/routing/route';

export default Route.extend({
  renderTemplate(){
    this.render('admin-dashboard', {
      into: 'admin'
    });
  }
});

templates/admin.hbs: ``` ````

When doing this, I get the following error in my console: Error: Assertion Failed: You attempted to render into 'admin' but it was not found.

The documentation seems to explain this simply, but it does not seem to match the actual behavior. For convenience, here's the example in the documentation. The key parts are the first parameter, and the into and outlet options.

import Route from '@ember/routing/route';

export default Route.extend({
  renderTemplate(controller, model){
    this.render('posts', {    // the template to render, referenced by name
      into: 'application',    // the template to render into, referenced by name
      outlet: 'anOutletName', // the outlet inside `options.into` to render into.
      controller: 'someControllerName', // the controller to use for this template, referenced by name
      model: model            // the model to set on `options.controller`.
    })
  }
});

https://emberjs.com/api/ember/2.17/classes/Route/methods/render?anchor=render

According to the documentation as well, if outlet is not passed, it will default to either using or , so there's no need to specify it explicitly from what I can tell. That said, I have tried specifying it explicitly and, again, to no avail.

Thanks in advance!




Trouble with ember model and computed properties

I have a book model that i use a mapBy() computed property on to retrieve all the prices in the model. allPrices: mapBy('books', 'price'); Then i use max() to get the highest value. maxPrice: max('allPrices'); That part works as expected. The problem i have is that i want to display the max price AND the title of the book associated with that price but i cant figure out how to do it.

<h2>Max book price:  </h2>
<h2>Which belongs to the book  </h2>

How can this be achieved? Any help would be appreciated.




Buttons that are links in Ember. js

Good I'm new at this and I was doing my own tests, but I still don't know enough about Ember. I wanted to make a button to click on the open a new tab of the browser with the page configured, I imagine it will be possible, someone can give me a hand? Thank you




Uncaught Error EmberJS and Polyfills

I cloned an Ember project and when running it throws me the following error:

loader.js:247 Uncaught Error: Could not find module `@ember/polyfills` imported from `radio/initializers/viewport-config`
    at missingModule (loader.js:247)
    at findModule (loader.js:258)
    at Module.findDeps (loader.js:168)
    at findModule (loader.js:262)
    at requireModule (loader.js:24)
    at index.js:18
    at Array.forEach (<anonymous>)
    at exports.default (index.js:15)
    at Module.callback (app.js:13)
    at Module.exports (loader.js:106)

Previously I had installed the ember client, phantomJS and I made both a bower install and npm install of the following files:

Package.json:

{
  "name": "radio",
  "version": "0.0.0",
  "description": "Small description for radio goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test",
    "deploy": "**",
    "deploy-prod": "**"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.2",
    "broccoli-sass": "^0.7.0",
    "ember-ajax": "^2.0.1",
    "ember-cli": "2.7.0",
    "ember-cli-app-version": "^1.0.0",
    "ember-cli-babel": "^5.1.6",
    "ember-cli-bourbon": "1.2.2",
    "ember-cli-dependency-checker": "^1.2.0",
    "ember-cli-google-analytics": "1.5.0",
    "ember-cli-htmlbars": "^1.0.3",
    "ember-cli-htmlbars-inline-precompile": "^0.3.1",
    "ember-cli-inject-live-reload": "^1.4.0",
    "ember-cli-jshint": "^1.0.0",
    "ember-cli-meta-tags": "3.0.1",
    "ember-cli-moment-shim": "2.2.1",
    "ember-cli-pace": "0.1.0",
    "ember-cli-qunit": "^2.0.0",
    "ember-cli-release": "^0.2.9",
    "ember-cli-slick": "1.0.14",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^1.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "^2.7.0",
    "ember-export-application-global": "1.1.1",
    "ember-lazy-image": "0.0.15",
    "ember-load-initializers": "^0.5.1",
    "ember-local-storage": "1.3.1",
    "ember-moment": "6.1.0",
    "ember-resize": "0.0.17",
    "ember-resolver": "^2.0.3",
    "ember-responsive": "1.2.7",
    "ember-social": "0.3.0",
    "ember-youtube": "0.8.2",
    "liquid-fire": "0.24.1",
    "loader.js": "^4.0.1"
  }
}

bower.json:

{
  "name": "radio",
  "dependencies": {
    "ember": "~2.7.0",
    "ember-cli-shims": "0.1.1",
    "ember-qunit-notifications": "0.1.0",
    "bourbon": "4.2.6",
    "slick-carousel": "^1.6.0",
    "pace": "^1.0.2",
    "blob-polyfill": "^1.0.20150320"
  }
}

I have been installing npm / bower several libraries to solve problems about polyfills but I did not find a solution, does anyone know how to solve this problem? Greetings.




Ember - Dynamic filterBy for an object that gets iterated?

I have a model request that has an attribute user_id. That user_id has a relationship to the id of the model user.

I want to display each user in a template, and below each user a list of all requests that have been assigned to that user. The model should hopefully be request, as I have other templates that iterate through request and it would be great to reuse that model if possible.

In hbs it would look like this:

#outside.hbs
<div class="row text-left">
  
    <div class="col-md-2">
      
    </div>
  
</div>

#requests-component.hbs
   <h4 class="request-heading"></h4>
   
      ...
   

Now, inside the component, how do I filter the requests to iterate over each specific user_id and create a new iteration if it's another user_id?

I've tried with the following in the component:

  request: Ember.computed('model.@each.userId', function () {
    return this.get('sortedRequests').filterBy('userId', this.get('userId'));
    //imagine this.get('userId') = [1, 2, 3, 4]
  })

How can I create a new request object that filtersBy each user_id, so that I have a list with lets say 10 Users on that template, where each is assigned the respective Requests, if user_id matches the user.id?

Thanks a lot!




model.reload not working in ember js

When i tried to reload the model using the model.reload this is not working

invoke: function () {
           var ctl = RSuite.Tab.currentTab.getController(),
               model = ctl.get('formModel');
              return model.reload();
       }

Please suggest me

Thanks in Advance




How to call a action from each loop while create a new element?

I require to add a class name according to the index. as well I do have much other conditional events to add with each of the element. for that reason I would like to add a call back on element create.

how can i call a function from each iterator. I tried like this:


    <li class="(action 'setting()')"></li> //trying to call


here is my controller:

actions:{
    setting:function(element, index){
        console.log(element, index); // i will add class name by condition
    }
  }

is it possible? or what is the correct way? especially i require to add different css classes according to the index value. ( for idea )

Live Example




mercredi 14 février 2018

Authenticating ember js using Azure AD and torii

I'm using torii to authenticate my front end using Azure AD and it's working fine. Now, my frontend needs to request a new token to access a backend that is also protected using Azure AD. I have a POC using Angular and Adal, and it fires the following request that I can't reproduce using Torii:

https://login.microsoftonline.com/myazuread.onmicrosoft.com/oauth2/authorize?response_type=token&client_id=6c49f322-11b4-42df-b064-96b9213c5754&resource=https%3A%2F%2Fmyazuread.onmicrosoft.com%2Fa6a6f6f0-7969-49e9-ad7e-cdf5299f8f59&redirect_uri=http%3A%2F%2Flocalhost%3A44342%2F&state=9db112a9-d644-4380-ba7d-c9e93bb2c756%7Chttps%3A%2F%2Fmyazuread.onmicrosoft.com%2Fa6a6f6f0-7969-49e9-ad7e-cdf5299f8f59&client-request-id=c83e62c3-bd86-4193-ac97-eefa8600916a&x-client-SKU=Js&x-client-Ver=1.0.12&prompt=none&login_hint=test%40myazuread.onmicrosoft.com&domain_hint=myazuread.onmicrosoft.com

PS: I just need the https://login.microsoftonline.com/myazuread.onmicrosoft.com/oauth2/authorize? the query parameters I can get them from Azure Portal.

Any help? Thanks in advance




Ember data discards irregular attributes

I have a model attribute with JSON key 'custom-device-label-1' that I would expect to find as 'customDeviceLabel1' but instead it is just not there and the model attribute is undefined even though the payload had data.




How to add Bootstrap Date Picker as Ember Component

One of the things I struggle the most with is taking existing libraries and adding them to my Ember project. I am currently trying to add the Bootstrap Date Picker as an Ember component but I can not get it to behave correctly.

I have added the Bootstrap JS files to my Vendor folder and added the following to ember-cli-build:

app.import('vendor/datepicker/bootstrap-datepicker.min.js');

Then I have created a component pod called date_picker. The template for the component is as follows:

<div class="input-group date" data-provide="datepicker" data-date-format="dd/mm/yyyy">
    <input type="text" class="form-control">
    <div class="input-group-addon">
        <span class="glyphicon glyphicon-th"></span>
    </div>
</div>

The JS file for the component is currently:

import Component from '@ember/component';

export default Component.extend({

addDate(){
  $('.datepicker').datepicker({
    format: 'dd/mm/yyyy',
    startDate: '-3d',
    autoclose: true
});
}
});

The component is called in the main template with . The above does render a date picker on the screen but one that does not behave correctly. It does not auto close for example and whilst the format is correct, it does not go cycle through months or always select the correct date on a button click.

Is there a step I have missed in integrating this into an Ember project?




What is the best strategy to upgrade a project in Ember CLI?

Ember CLI and Ember.js have some build time issues in older versions. One often mentioned solution is to upgrade stack to new versions. It means updating whole stack.

What is the best strategy to upgrade it to not destroy the whole project?




mardi 13 février 2018

how to enumerate all routes in an ember test

we need to get a list of all routes from router.js in a test. preferably a lower level test (unit/integration).

use case for context: we have metadata that is required for all routes. this test is to make sure that the appropriate metadata was added, and not forgotten, when a new route is added.

similar questions here and here have been asked, but attempts to adopt/modify those solutions within a test have not been fruitful.




What is the proper way to invoke a closure action inside a component?

I pass a closure action into my component like so:



How should I invoke this in my component?

actions:{
loadMoreDeployments(){
  // which one of the following three invocations is best?
  this.attrs.loadMoreDeployments();
  this.get('loadMoreDeployments')();
  this.loadMoreDeployments();
}

}




Mocking conditional computed property in Ember component test

I'm trying to simply mock the computed property return value before rendering a component. Trying this.set('isHome', true) does not work though because I can't pass it to the component.

Component [Logic]:

isHome: false

Component [Template]:


  <p id="maintext">Text</p>


Test:

test('Block is visible on the homepage', function(assert) {
  assert.expect(1);
  this.set('isHome', true); // Does nothing
  this.render(template);
  let maintext = this.$("#maintext")
  this.asyncWait(assert, () => {
    assert.ok(maintext);
  });
});

This is a very rough outline of the layout, with a computed property that then is used to show a block on the page or not. How would I override that computed property to true to force that block to show?




lundi 12 février 2018

Adding css/js structure from a template into an Ember project

I recently purchased a HTML based template. It came with a large number of CSS and PLugin files and I am struggling to use these as part of an Ember project. I'm not entirely sure where they are supposed to go or how they are supposed to be called.

Assuming the following structure from the template:

-assets
 -css
  -theme
   -a number of css files
 -js
  -a number of js files
 -less
  -bootstrap folder
   -less files
  -components
    -less files
  -other folders
  -less files
 -plugins
  -plugin folders
  -plugin js

I don't know how to best 'emberise' this structure, particularly the CSS and Less files. I am using the ember Less compiler and tried the following in the Ember application:

-styles
 -css
 -less
 -app.less

and attempted to import the files from the less folder with @import "less/style.less"; but this fails to load the requested resources.

I do not think they should be in the Public folder and called in as scripts (aside from the JS perhaps) but I am so far unable to successfully pull in these resources.

I appreciate answers to a question like this will be somewhat subjective but any pointers are appreciated




Ember-Simple-Auth customised Devise Authenticator serverTokenEndpoint defaulting to users/sign_in

Pretty much as described in the title. I have a basic Ember Simple Auth setup. With a Devise Authenticator I've setup a custom URL for the serverTokenEndpoint.

(Coffeescript)

devise = DeviseAuthenticator.extend

  serverTokenEndpoint: ENV.apiBaseURL + 'session'
  tokenAttributeName: 'authentication_token'
  resourceName: 'session'

export default devise

Authenticating and Invalidating are ok. But trying to navigate to certain pages I get requests for - https://apiBaseURL/users/sign_in. Which the endpoint doesn't exist.

Why is the configured URL not being used?

Or are there any other places this URL is set? Or used? It's currently causing the page to break and the user cannot continue.




dimanche 11 février 2018

ember and sails js authentication

I'm using Ember JS with Sails JS and i'm having a weird problem that drove me crazy for the last two days

Now as the setup i'm using sails-generate-ember-blueprints in sails js aside with jwt, bcrypt and express-jwt

On the Ember side i configured my adapters as follow

in the adapter folder "application.js"

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.RESTAdapter.extend(DataAdapterMixin, {
authorizer: 'authorizer:oauth2',
host: 'http://localhost:1338',
});

in the authenticators folder "oauth2.js"

import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';

export default OAuth2PasswordGrant.extend({
serverTokenEndpoint:'http://localhost:1338/auths/login'
});

and the authorizer folder "oauth2.js"

import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';

export default OAuth2Bearer.extend();

so far so good. now i created an authentication controller in the sails project "AuthController.js" and pasted this code which was taken from another project

 var jwt = require("jsonwebtoken");
 var bcrypt = require("bcrypt");

 module.exports = {
    login: function(req, res) {
        if (!req.body.username || !req.body.password) {
        res.badRequest({error:'missing info!'});
        return;
     }
    User.findByEmail(req.body.username).exec(function(err, user) {
            if (err) {
                    return res.badRequest({
                            error: err
                    });
            }
            if (!user || user.length < 1) {
                    return res.badRequest({
                            error: 'No such user'
                    });
            }

            bcrypt.compare(req.body.password, user[0].password, 
  function(err, result) {
                    if (err || !result) {
                            return res.badRequest({
                                    error: 'invalid Password'
                            });
                    } else {
                            issueTokens(user, res);
                    }
            });
    });
},

logout: function(req, res) {
        req.logout();
        res.send({
                success: true,
                message: 'logout Successful'
        });
    }
};

function issueTokens(user, res) {
var token = jwt.sign(user[0], sails.config.jwt.secret, {
        expiresIn: sails.config.jwt.expiration_time_in_minutes
});

res.send({
        user: user[0],
        access_token: token
});

};

i have a model in the Ember Application "user.js" which have an email and password attributes both set as DS.attr('string')

i registered my first user using postman and when i tried to login it gives me an error from the bcrypt.compare function i thought it might be because bcrypt is trying to compare a password that isn't encrypted in the first place so i tried to register a user simply by

signUp(email, password){
  this.store.createRecord('user', {
    email : email,
    password : password
    }).save();
 }

it did register new user and bcrypted the password, but when i try to login using the same user i created it i get an error

POST : localhost:1338/auths/login/ net::ERR_EMPTY_RESPONSE

and in the terminal from the sails side i get this error

/Users/Haboosh/Desktop/pulse/pulse-server/node_modules/jsonwebtoken/sign.js:97 throw err; ^

Error: Expected "payload" to be a plain object. at validate (/Users/Haboosh/Desktop/pulse/pulse-server/node_modules/jsonwebtoken/sign.js:34:11) at validatePayload (/Users/Haboosh/Desktop/pulse/pulse-server/node_modules/jsonwebtoken/sign.js:56:10) at Object.module.exports [as sign] (/Users/Haboosh/Desktop/pulse/pulse-server/node_modules/jsonwebtoken/sign.js:108:7) at issueTokens (/Users/Haboosh/Desktop/pulse/pulse-server/api/controllers/AuthController.js:53:18) at /Users/Haboosh/Desktop/pulse/pulse-server/api/controllers/AuthController.js:36:9

what am i doing wrong people ?

my login function is like this

login(email, password){
    this.get('session').authenticate('authenticator:oauth2', email, password).then(() => {
    this.transitionToRoute('index')
    })
 };




Emberjs: How to get to a route parameter passed in via url in controller

Consider routes:

this.resource('things', {path: '/things/:id'}, function () {
  this.route('edit');
});

Inside controller of the edit, how do I access the :id?




Ember direction dont work

I have a function

movePacMan: function (direction, amount) {
    this.incrementProperty(direction, amount);
    this.clearScreen();
    this.drawCircle();
},

But when i need to use it, it doesn't work

`keyboardShortcuts: {
    up: function() {this.movePacMan('y', -1 * this.get('sizeSquare'));},
//doesn't work
    down: function() {this.movePacMan('y', this.get('sizeSquare'));},
//works
    left: function() {this.movePacMan('x', -1 * this.get('sizeSquare'));},
//doesn't work
    right: function() {this.movePacMan('x', this.get('sizeSquare'));},
//works
},`

Can anyone help me to fix this? I have no idea how to fix it correctly

P.S.: New to ember, sorry




How to properly destroy ember app and re-initialize a new one without re-defining methods that were previously defined

I am trying to load multiple ember apps in a spa using single-spa and single-spa-ember. However when I try to destroy an ember app and load another ember app I am getting following issue:

index.js:12 Uncaught TypeError: Cannot redefine property: Inflector at Function.defineProperty (<anonymous>) at Module.callback (index.js:12) at Module.exports (loader.js:106) at Module._reify (loader.js:143) at Module.reify (loader.js:130) at Module.exports (loader.js:104) at Module._reify (loader.js:143) at Module.reify (loader.js:130) at Module.exports (loader.js:104) at Module._reify (loader.js:143)

It definitely seems like when loading a new ember app, the Ember.Inflector is trying to be re-defined it again even when "EXTEND_PROTOTYPES" has been disabled. I have an example demonstrating the issue here : https://github.com/dshrestha/ember-spa

single-spa provides hooks to handle loading/unloading the app, while sigle-spa-ember already provides the default implementation of the hook for ember app. I have tried deleting Inflector method before the ember app gets unmount(https://github.com/dshrestha/ember-spa/blob/master/src/ember-4/app/app.js#L30) but that didn't work for me.




vendredi 9 février 2018

Ember JS and nested routes: the provided route name is invalid

I'm currently working my way through my first Ember JS app, using Balint Erdi's excellent book "Rock and Roll with Ember JS"

This is probably a silly question, but I'm stumped and would appreciate some help.

I have the following (fairly simple) routes for my app:

/clients  
/clients/:slug  
/clients/:slug/requests  

So for example, I would want a user to be able to view the requests for a specific client by visiting /clients/abc-company/requests

On the main dashboard, inside clients.hbs, I have the following code to link to each specific client (using dynamic segments):

  
  <tr>
    <td></td>
    <td>
      
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  

Now, the issue is that Ember doesn't seem to recognize the second link-to parameter (client).

The console is yelling at me with the following error message:

WARNING: This link-to is in an inactive loading state because at least one 
of its parameters presently has a null/undefined value, or the provided 
route name is invalid.

but I DID pass the parameters, which is supposed to be client!

Here are the relevant files in my code, I'm hoping someone can point out my obvious mistake or find the semi-colon that I forgot to include, or something.

//app/router.js
(...)
Router.map(function() {
  this.route('clients', function() {
    this.route('client', { path: ':slug' }, function() {
      this.route('requests');
    });
  });
});

//app/routes/clients.js
(...)
var Client = EmberObject.extend({
  id: '',
  name: '',
  contact: '',
  email: '',
  phone: '',
// create slug from client name
  slug: computed('name', function() {
    return this.get('name').dasherize();
  })
});

// app/routes/clients/client.js <-- see the route DOES exist
(...)
  model: function(params) {
    // get the slug from clients, return client matching the slug name in the URL
    var clients = this.modelFor('clients');
    return clients.findBy('slug', params.slug);
  }
});

// app/routes/clients/client/requests.js
(...)
  model: function() {
    return this.modelFor('clients.client');
  }
});

Any help would be appreciated, this is my first Ember.js hurdle and I have a feeling that understanding nested routes properly will be very useful in the future :)

But for now I'm just confused.

Thanks in advance!

EDIT: Added some more code from the template, for clarity.




Stopping bubbling/propagation in Ember 2.x

Is there a proper way to stop bubbling in this scenario in Ember 2.18? I couldn't find an example that matched in the docs, but managed to find two other examples around the web. Both work, but one looks like it might be deprecated as I couldn't find references to it in the newest versions of Ember docs.

Scenario: I have a container. I want to click on it to expand/open it. Inside the container, I have a button. I want to click the button to close it. The general issue is that clicking the button to close also triggers the parent container's click event to open.

To solve, I believe I need to prevent bubbling/propagation when the button is clicked.

The two solutions I have found are as follows:

Solution #1:

event.stopPropagation();

Component JS:

import Component from '@ember/component';

export default Component.extend({
  tagName: "section",
  classNames: ["Container"],
  classNameBindings: ['isOpen:Container--open'],
  isOpen: false,

  click() {
    if (!this.get('isOpen')) {
      this.send('openContainer');
    }
  },

  actions: {
    openContainer() {
      this.toggleProperty('isOpen');
      // JS removed for demo
    },

    closeContainer(event) {
      this.toggleProperty('isOpen');
      // JS removed for demo
      event.stopPropagation();
    }
  }
});

Component HBS:

<button onclick=>Close</button>

Solution #2:

bubbles=false

Component JS:

import Component from '@ember/component';

export default Component.extend({
  tagName: "section",
  classNames: ["Container"],
  classNameBindings: ['isOpen:Container--open'],
  isOpen: false,

  click() {
    if (!this.get('isOpen')) {
      this.send('openContainer');
    }
  },

  actions: {
    openContainer() {
      this.toggleProperty('isOpen');
      // JS removed for demo
    },

    closeContainer() {
      this.toggleProperty('isOpen');
      // JS removed for demo
    }
  }
});

Component HBS:

<button >Close</button>

All feedback is appreciated. Thanks!




Access to component property inside a component method called by an event

I have a component that toggles when the window is clicked anywhere.

To achieve that I bind a component method as global event to the body element.

Moreover, I need to access a component property inside the component method that is called by the click event bound to the body element.

But it doesn't work:

app/components/example-component.js:

import Ember from 'ember';

export default Ember.Component.extend({

  exampleProperty: 'example value',

  didInsertElement() {
    console.log('start didInsertElement() ************************************************************');
    console.log('- "this" is the Ember.js component:');
    console.log(this.$());
    console.log('- "this.exampleProperty" has the Ember.js component value:');
    console.log(this.exampleProperty);
    Ember.$('body').click(this.exampleMethod).click();
    console.log('end didInsertElement() ************************************************************');
  },
  exampleMethod(event) {
    console.log('start exampleMethod() ************************************************************');
    console.log('- "this" is the DOM element that has triggered the event:');
    console.log(Ember.$(this));
    // console.log(this.$()); This doesn't work
    console.log('- "this.exampleProperty" is undefined:');
    console.log(this.exampleProperty);
    console.log('end exampleMethod() ************************************************************');
  },
});

How to get it to work?




jeudi 8 février 2018

how to destroy and recreate a controller object in Ember framework

I am using Ember 2.12, there are two controllers - one for applicant and other for coapplicant for our application flow. When the user decides to delete the coapplicant, I am trying to get rid of its state (that unfortunately lives in the coapplicant controller instead of a separate data object). so i am trying to destroy the controller and then recreate it the next time the page loads.

in the resetController state, I call

this.destroy();

And in the routes/form.js page, in the

setupController(controller,model)

I am checking if the controller is destroyed, i tried to recreate it

if (controller.isDestroyed) {
        Ember.Logger.error('controller is already destroyed');
        this.set('controller',FormEditCoapplicantController.create());
    }
    this._super(...arguments);

but when i do that, I get the error when this._super(...arguments) is called,

Error while processing route: form-edit-coapplicant Assertion Failed: calling set on destroyed object: <account-open@controller:form-edit-coapplicant::ember3345>.model = [object Object] Error: Assertion Failed: calling set on destroyed object: <account-open@controller:form-edit-coapplicant::ember3345>.model = [object Object]
at assert (http://localhost:4200/assets/vendor.js:21056:13)
at Object.assert (http://localhost:4200/assets/vendor.js:32807:34)
at Object.set (http://localhost:4200/assets/vendor.js:37553:22)
at Class.setupController (http://localhost:4200/assets/vendor.js:42366:21)
at Class.setupController (http://localhost:4200/assets/vendor.js:207076:9)
at Class.superWrapper (http://localhost:4200/assets/vendor.js:55946:22)
at Class.setupController (http://localhost:4200/assets/account-open.js:6331:16)
at Class.superWrapper [as setupController] (http://localhost:4200/assets/vendor.js:55946:22)
at Class.setupController (http://localhost:4200/assets/account-open.js:7184:16)
at Class.superWrapper [as setupController] (http://localhost:4200/assets/vendor.js:55946:22)

Is there anything that i missing here.

I don't want to clear the controller state by manually resetting each field because the logic for that is very complex (there are lots of fields, some are computed properties, some conditionally prefilled/not-prefilled depending on data availability, I am assuming if i can somehow destroy and recreate the controller in this case, i can get the brand new created controller with its state back to original without much manual effort.




How to save form data into server through Ember component?

I am working with emberjs.

I made 'form with tabs' with components. I have to save data from component.js.. but I don't have clear idea.

could anyone can help me to work with this?

thank you




mercredi 7 février 2018

isDeleted not changed by rollbackAttributes()

I need to be able to "undelete" a record after it has been marked for deletion (not persisted yet). The guides indicate that rollbackAttributes() is the proper way to do this.

However, the following indicates that rollbackAttributes() is not affecting the isDeleted property on the record. I am using Ember 2.15.

console.log(record.get('hasDirtyAttributes')); // false
console.log(record.get('isDeleted')); // false

record.deleteRecord();

console.log(record.get('isDeleted')); // true
console.log(record.get('hasDirtyAttributes')); // false

record.rollbackAttributes();`

console.log(record.get('isDeleted')); // true
console.log(record.get('hasDirtyAttributes')); // false

What's the proper way to have isDeleted align with the actions of rollbackAttributes(), or to "undelete" a record?




How to abort browser reload/refresh in ember

I am not sure how you can abort a browser reload using ember's route events. The willTransition event only gets triggered when you click the back button or just change the route. I have not been able to find how I can stop page reload for example while an upload is still in progress.




Querying data through emberfire

I am new to ember js and creating a Shopping cart with database stored in Firebase. I am accessing total product data using model() { return this.store.findAll('product'); } I am thinking of implementing cart functionality by creating an array of product id which are added to cart by user for example orderarray:[1,2,3,6,7] and want to return data only belonging to these product ids which are in orderarray by querying it based on this array's values. Can anyone help me to query data accordingly. Thanks in advance




EmberJS app and Broccoli

I have an Ember app (which is actually an addon/engine). My question is very basic (regarding the usage of Broccoli)

Now it is said that Broccoli is the default build tool for Ember-CLI

But I do not find Brocfile.js anywhere within my project.

Just wanted to understand how is Broccoli really used within an Ember project. Also in what practical scenarios do we have to change/define any configurations related to that




How to add "if" condition in ember 1.10 HBS for #each

Hi I want to select the current month as default in the below code in Ember 1.10, current month is a variable in the controller:

currentMonth: moment().format("M"),
allMonths: moment.months()

////// HBS ////////////

<select id="selectMonth">
    
        
            <option selected="selected" value=''></option>   
        
            <option value=''></option>
        
    
</select>   

I am getting Error for this. what is the other way we can add a if condition in this scenario.




mardi 6 février 2018

Ember exclude a mixin from specific route

I have a mixin for authorization checking which is included in application route so that all other routes get access to the mixin without explicitly importing it. However, I want to exclude my login route from inheriting it. How can I achieve that? One workaround is to import the mixin in all routes individually but that's error prone and don't want to resort to it unless I am sure that there is no way out.

Thanks.




Handling Disconnect from Parity Wallet

Im running an application that uses the web3.js library to connect to a parity node being injected by the parity chrome extension. The following is the code I've implemented as a service in my Ember.js application.

import Service from '@ember/service';
import { get, set } from '@ember/object';

import { task, timeout } from 'ember-concurrency';
import Web3 from 'npm:web3';

const { web3 } = window;

export default Service.extend({
  provider: null,

  init() {
    this._super(...arguments);

    this.setProvider();
    get(this, 'maintainProvider').perform();
  },
  setProvider() {
    let provider;

    try {
      provider = new Web3(web3.currentProvider);
    } catch(reason) {
      throw reason;
    }

    set(this, 'provider', provider);
  },
  maintainProvider: task(function * () {
    let listening = yield get(this, 'provider').eth.net.isListening();

    if (!listening) {
      get(this, 'setProvider')();
    }

    yield timeout(1000);

    get(this, 'maintainProvider').perform();
  })
});

Basically, the idea is that I'd like to set a provider using the injected web3 object (this works fine). Then, if you stop the parity application, I'd like the app to notify the user and attempt to reconnect.

What's happening now is, when parity is closed the extension throws an error and haults execution of any app code, which is preventing me from trying to reconnect. Any ideas would be really helpful.




Ember.js re-render links on locale change

My application uses the ember-i18n addon. For SEO purposes, I wanted to put a /[lang-code]/ in the URL.

When changing the language, history.pushState can change the URL and its alright, but the links on the page do not change for the new language, even though router.rootURL is changed.

So far I can just change the window.location.pathname, but thus a new network request is being made.

I tried overriding the href-to helper (from ember-href-to addon) and added this:

_recomputeOnLocaleChange: Ember.observer('i18n.locale', function() {
    console.log("here?");
    this.recompute();
})  

It executes on locale change, but apparently recompute does nothing. Even with setTimeout (because perhaps rootURL didn't change yet). Links are all the same.

Can you suggest anything? Would be greatly appreciated! Thank you!!




Need to get response outside the webservice [duplicate]

This question already has an answer here:

While running the below code, it doesn't the return the response from webservice

workflowsearch: Ember.computed(function () {
            RSuite.services({
               type: 'get',
               service: 'workflow/defaultfilter',
           }).done(function (response) {
               workflowresponse = response;
           }.bind(this));
            return workflowresponse ;
        })

Please guide me for this. Thanks in advance




lundi 5 février 2018

How to set value of Ember computed property within a callback

I have a computed property that checks if a user has already liked a post:

  likeable: Ember.computed(function () {
    const currentUser = this.get('auth.credentials.id');
    const post = this.get('post.id');

    // Get likes and filter by post and current user

    this.get('store').query('like', {
      filter: {
         user_id: currentUser,
         post_id: post
       }
    }).then(function(like) {

      // Check if any likes were returned

      if (like.get('length') != 0) {
        console.log('length is not 0')
        return false
      } else if (like.get('length') === 0) {
        console.log('length is 0')
        return true
      }
    })
  })

Its being called in my template file like this:


  <button class="like-button" >Like This Post</button>


I'm able to see the console.logs and I know the correct records are being retrieved. However, the issue is that the value of likeable is not being updated. I'm pretty sure this is because my if statement is within a callback, and not returning true to the actual computed property. Is there a way around this?




How do I extract the Count value from D3 chart to create a toggle?

I have a D3 bar chart and I am trying to make a toggle that will display the label and count values in a bit of text on the component template.

I have the label value working as follows:

 highlightedLabel: or('selectedLabel', 'hoveredLabel'),

    .on('mouseover', d => {
        this.set('hoveredLabel', d.data.label);


      })
      .on('mouseout', () => {
        this.set('hoveredLabel', null);

      })
      .on('click', d => {
        let clickedLabel = d.data.label;


        if (this.get('on-click')) {
          this.get('on-click')(clickedLabel);
        } else {
          if (clickedLabel === this.get('selectedLabel')) {
            this.set('selectedLabel', '');

          } else {
            this.set('selectedLabel', clickedLabel);

          }
          this.buildChart();
        }
      })

The above gives me the desired result for the label value. I tried to include the 'count1' value as follows:

  highlightedCount: or('selectedCount', 'hoveredCount'),
  highlightedLabel: or('selectedLabel', 'hoveredLabel'),

    .on('mouseover', d => {
        this.set('hoveredLabel', d.data.label);
        this.set('hoveredCount', d.data.count1);

      })
      .on('mouseout', () => {
        this.set('hoveredLabel', null);
        this.set('hoveredCount', null);
      })
      .on('click', d => {
        let clickedLabel = d.data.label;
        let clickedCount = d.data.count1;

        if (this.get('on-click')) {
          this.get('on-click')(clickedLabel);
        } else {
          if (clickedLabel === this.get('selectedLabel')) {
            this.set('selectedLabel', '');
            this.set('selectedCount', '');
          } else {
            this.set('selectedLabel', clickedLabel);
            this.set('selectedCount', clickedCount);
          }
          this.buildChart();
        }
      })

However I don't get the correct behaviour. The hover element works correctly but when I click the bar to toggle on the count value, the value only exists as long as I am hovering over a bar. It doesn't persist like the label value does.

The values are added to the template simply with




dimanche 4 février 2018

yo ember tutorial: Client doesn't have permission to access the desired data

I'm doing the YoEmber tutorial: https://github.com/zoltan-nz/library-app. Getting the following error- Uncaught Error: permission_denied at /authors: Client doesn't have permission to access the desired data.

I create a Firebase database, as the tutorial requires, with the following rules: { "rules": { ".read": true, ".write": true } } Still, the database is not getting authenticated. I also copied the correct apiKey, authDomain, databaseURL, projectId, storageBucket, and messagingSenderId from firebase.

Anyone have any ideas?




What is the difference between class="example" vs. classNames="example" in Ember/handlebars components?

I'm applying a class to a component, and it seems like both of these options work:

Both ultimately result in the rendered HTML having the class, e.g.:

<div class="example-class ember-view">...</div>

Is there a difference between providing the class via class or classNames? Are there any unintended consequences using one over the other?




samedi 3 février 2018

Click check box with ember-cli-page-object

I have a form with an input like so:

I want to click on in and then submit. My page object is like this

export default create({
  form: {
    selectFoo: clickable('.foo'),
    submit: clickable('#search'),
  },
});

However I can't select the checkbox and then submit. What am I doing wrong? I have my form stuff in page.form so it's easier to abstract out from all the other stuff on the page.

My test is like this:

page.form.selectFoo();
page.form.submit();




Accept an array of new objects in response from server

I'm currently running into an issue where I want to build an array of new objects from my Rails server, and provide it to the user to confirm/edit before saving.

However Ember Data requires an ID in the object in order to use it.

Is there something that I can do in the serializer to tell ember that these are new objects and that they won't have an id? Should I be going about this a different way?

The main reason that I'm using the server for this is because there's a library that does exactly what I need, saving me loads of time instead of doing it manually on the client.




How to generate multiple sheets in one excel file using ember-cli-data-export

I am able to generate one sheet only with the ember-cli-data-export through the following javascript function of:

this.get('excel').export(data, {sheetName: 'Overview', fileName: 'test.xlsx'});

I have tried the following way (below) to generate multiple sheets but it is not working.

this.get('excel').export([data1, data2], {sheetName: ['Overview', ,Next'], fileName: 'test.xlsx'});

How do I generate multiple sheets in one excel file test.xlsx using ember-cli-export?




vendredi 2 février 2018

Can't access Ember's class variable

How to properly pass a variable to an Ember's class?

Controller:

import Controller from '@ember/controller';
import Object from '@ember/object';

function totalVotes(company) {
  return company.upvotes + company.downvotes;
}

function calcPercent(company) {
    return (company.upvotes * 100 / (company.upvotes + company.downvotes)).toFixed(2);
}

function percentComparator(a, b) {
    return calcPercent(b) - calcPercent(a);
}

var Company = Object.extend({
  score: function() {
    return (this.get('upvotes') * 100 / totalVotes(this)).toFixed(2);
  }.property('upvotes', 'downvotes')
});

var AppModel = Object.extend({
  topCompanies: function() {
    return this.get('companies')
      .sort(percentComparator)
      .slice(0, 8);
  }.property('companies.@each.upvotes', 'companies.@each.downvotes'),
});

var appModel = AppModel.create({
  companies: getCompaniesJSON().map(function(json) {
    return Company.create(json);
  })
});

export default Controller.extend({
  topCompanies: appModel.topCompanies,
});

Template:

<ul>

  <li> %</li>

</ul>

The result of the above in the browser console:

jquery.js:3827 Uncaught TypeError: Cannot read property 'sort' of undefined

this.get('companies') is undefined. Why? I'm passing companies to AppModel.create. What am I doing wrong?