mardi 31 juillet 2018

Is there a way to ensure a request is coming from a trusted UI application?

So to give you a background, we have a backend application that has a huge number of APIs (Spring boot framework). And then there is a UI application with a mix of React and Ember.js. We are using OAuth2.0 access token.

Each page of the UI may use a number of API resources and permissions of the pages (including actions and buttons) are managed separately than permissions for accessing APIs directly.

Now the issue is that in order to stop anyone with their access token can directly call any API. To stop that, we decided to link the services/resources used in each page or a button to the route url (Ember.js routes) so that based on the user's permission to those routes, we determine whether they have access to particular service in the backend or not. In other words, if a user sends a request to a service directly and say that service is linked to a page that he doesn't have access to in the UI world, then security check stop him.

However, this is now becoming a headache. The pages are constantly changing, some services are being removed or new services are added and we have to continously maintain the SQL scripts to keep the linkage between the two. Now to mention that due to hierarchical structure of the UI (routes) this has become even more complicated.

Now I was wondering, if we could determine that a request is coming from a UI then we don't need to check the permission to API and given the UI won't be rendered if they don't have access to it, we can safely let the request comes in and served. And if the same user uses his UI token to access the API directly we simply block it. If a user need direct access to an API, then they have to get a special token used for API (Some user may need to use API directly for their).

Now the question is how can we determine the request is from UI and that UI page is the one we trust? I did a search in internet but couldn't really find anything any framework or protocol for this. Is it even possible?




ember mirage seed db dynamically

I know when application loads, mirage seeds the database. But I wanted to know is there a way to change the seeded database dynamically later on (for example on some user actions).

So, I have an API which gives me the status of the progress and I am polling that API call. Initially Mirage seeds the database for me but every time I make that API call, same data is returned and I want the data to change so that I can test my UI design. Is there any way to do it?




Ember jQuery "one" event handler getting called more than once

In my Ember app, I have some jQuery code to execute (based on paste to an input box)

My question is I have used "one" in my code, but it is getting executed more than once. As per jQuery docs, it should be invoked only once.

didRender: function() {
    var self = this;
    var $inputs = Ember.$("input[id*=my-field]");

    $inputs.on("paste", function() {
        var $this = Ember.$(this);
        var originalValue = $this.val();
        $this.val("");

        $this.one("input", function() {
            // Why is this getting invoked more than once ?
            // Contains code which splits & sets value to multiple textboxes like 
//$inputBox.val('SPLITTED_PASTED_VALUE');
        });
    });
}




How to outline table column using JS/CSS/HTML

I need to select a table column on click. To show selection, I need to outline the table column.

I managed to outline each in the column needed, see pic: What I made

However, that doesn't suit me: I need to get rid of inner lines. CSS (actually, LESS) I currently use:

  td.fd-selected
  {
    outline: 0.25em dashed rgb(79,115,176);
    background-color: rgba(79,115,176, 0.25);
  }

Thanks!




lundi 30 juillet 2018

How is helper 'andThen' in embers different than traditional 'then'

In the code below, I can use then instead of andThen and I see everything is running fine. So, what makes andThen special?

test('Clicked on the About page /about', function(assert) {
    visit('/')
    .click('a:contains("About")')
    .then(function(){
        assert.equal(currentURL(), '/about', 'SHould Navigate to about')
    })
});

test('Clicked on the About page /about', function(assert) {
    visit('/')
    .click('a:contains("About")')
    .andThen(function(){
        assert.equal(currentURL(), '/about', 'SHould Navigate to about')
    })
});




this is undefined in controller (ember, 3.x)

Run into a problem with ember (v.3.x), and cannot figure out why. I did not find anything (that worked in my case) in the docs nor here.

So, here's the problem: this returns undefined in my controller inside the computed property (undefined.get('filter')). The rest of my function works, so I did not put it in here.

// in dic.js (controller):
export default Controller.extend({
  filter: '',
  filteredTerms: computed('filter', () => {
     const x = this.get('filter');
     // ...
}),

The corresponding input field:

// in dic.hbs


In my route I just return the model, which should be filtered by that function.




Authenticating with Socialite on Laravel + JWT + Ember JS

I have some issue authenticating with Socialite on Ember JS with Laravel. I have an app where backend and frontend is separated. I am using JWT (tymondesings) as an authentication service. I am successfully redirecting to facebook, and receiving the response to my API and successfully registering the user on DB and getting the user via $token = JWTAuth::fromUser($user). The only problem I have is returning it in front end and authenticating so it can use the app. Any suggestion or help would be appreciated :)




dimanche 29 juillet 2018

Ember: Getting Assertion Failed error when saving persisted data

I am going through the video tutorial provided below and am unable to resolve an Assertion Failed error message (see below). Per the video tutorial, the author originally runs the save() function and gets the Assertion Failed error message. The author then instructs us to call the transitionTo() function after the save() function has been called in order to get around the error message; however, I am still receiving the error message.

In my project, I notice that the database has two new records when I click on submit, which also results in the error message. If I click on submit again then the application takes me back to the todo-items page where it shows the two records. Can anyone advise what I am doing wrong?

Current versions:

  • Ember : 3.2.2
  • Ember Data : 3.2.0
  • jQuery : 3.3.1

Video tutorial (the error occurs at the 11:30 mark): https://www.youtube.com/watch?v=bZ1D_aYGJnU

Ember Error Message

route/add.js

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

export default Route.extend({
    model(){
        return this.store.createRecord('todo-item');
    },

    actions: {
        submitAction() {
            this.get('controller.model')
            .save()
            .then(() => {
              this.transitionTo('s.todo-items');
            });
        }
    },
});




How can I pass an attribute from one component to another in EmberJS?

I have a component that has anchor tag click that opens a modal and within the model is a youtube . When the modal opens I want the id in the Youtube url to change in order to play the correct video, but I'm having trouble figuring out how to get this done. I added data-attributes with the id I need and was looking to pass this into the component to have it added to the url. I was thinking I could update an id in the component JS file.

src="https://www.youtube.com/embed/?rel=0&showinfo=0"

Below is the Handlebars templating and JS.


  


JS:

import Component from '@ember/component';
export default Component.extend({
  click(evt){
  let ytId = evt.target.getAttribute('data-id');
  this.set('id', ytId);
  },
  id: null,
  actions: {
    openModal() {
      this.get('onOpen')();
    }
  }
});




How to get original event object in action handler?

I would like to clarify the ways to get original event object in action handler.

The documentation says:

To utilize an event object as a function parameter:

  • Define the event handler in the component (which is designed to receive the browser event object).
  • Or, assign an action to an inline event handler in the template (which creates a closure action and does receive the event object as an argument).

So to get an event object on inline handler we do like so:

hbs:

<form onsubmit=>

js:

actions: {
  submit(e) {
    console.log(e); // original event
  }
}

And what about the first option to define event handler in component?




jeudi 26 juillet 2018

Create a generic select for belongTo in Ember, stuck on having the select show the already existing value

I am trying to make a select element to set up a belongsTo relation.

The params of the componenent are :

collection: a collection of element displayed in the select colText: column of the collection displayed in the select. It's a string model: The model currently being edited relation: String of the name of the model to wich it belong to

hbs :

<select class="form-control"
onchange=>
  <option value=""></option>
  
    <option value= 
      selected=>
      
    </option>
  
</select>

JS :

import Ember from 'ember';

export default Ember.Component.extend({
  store: Ember.inject.service(),
  currentForeignId: Ember.computed(function(){
    debugger;
    return this.get('model').get(this.get('relation')).id
  }),
  actions:{
    selectValue(value){
      this.get('model').set(this.get('relation'),
        this.get('store').peekRecord( this.get('relation'), value ))
    }
  }
});

Despite all my attempts, I cannot make currentForeignId return an ID. I tried with a debbuger to display the value but I cannot access it.




How to deep copy a complex object with EmberJS

I would like to copy a complex object with EmberJS. This object contains arrays, other objects, data values, strings and other values. I see the Copy method is deprecated and there is an addon called ember-copy to replace it.

I tried to use the ember-copy addon but when I set the second argument to true (indicating that I want a deep copy) it says I cannot copy an object that does not implement Ember.Copyable. I transformed this object to an EmberObject, passing the Copyable mixing, but even with that it says I need to implement a Copy method. I do not understand why I would need the ember-copy addon if I need to implement it manually.

I believe cloning an object should be something a framework must be capable of doing. Every framework I used provided a way to do it with no effort, but it seems to be a hard thing to do with Ember.




How to return data based on promise

I have a "virtual attribute" in a model, and I want the setter to wait for the promise before returning the value :

idShop:Ember.computed('shop',function(){
    get(key){
      return this.get('shop').id;
    },
    set(k,v){
      this.get('store').findRecord('shop',key)
      .then(shop =>{ 
        this.set('shop', shop)
      })
    }
  })

In the set, I need to return either k(key) or shop.id after findRecord and it's then are solved. How can I do that?




Loading spinner in ember-js

I'm trying to display loading spinner in emberJS during Ajax call. My Code is as given below.I had given the ajax call in the controller action. The problem gif image is shown and hidden after the ajax call.I had also tried ajaxStart and ajaxStop but didn't get the expected results.

$.ajax({
        beforeSend:function(){
            $('#wait').show();
          console.log("started t");
        },
          type:"POST",
          url:"/getdata",
          async:false,
          data:"some",
          complete:function(){
                  $('#wait').hide();
                 }
  });
<div id="wait" style="height: 500px;width: 1200px;display:none">
  <img src="assets/images/pageloader.gif" alt="Loading....">
</div>

Can anyone suggest me the way to display the image on loading.Thank you for any answer in advance.




Resize text and inputs

Im looking for external library or some solution how can I resize text in ember application. I have tried *jfontsize.js*, *textbig*, *flowtype.js*, *resize-text*- for ember and many others, but all of them are not good enough.
Best was jfontsize.js but...

Problem: If we are talking about normal text in div or something similar than everything was okey, but the problem appears when I have some inputs on my view ( espacialy those hidden which will active after some choose of option "Yes/No" )

To the point. Inputs are scaling (text inside was resizing, and was bigger), but after choose some of select or radio-button and new input appear then it has not the same size like old brother but it is small (has normal size) and here is the problem.

All inputs have the same class .inputs, I tried do it manualy via JQuery and $(".inputs.css").css("font-size", "20px") but it didn't work for new inputs which were not active(visible) yet.

Someone have maybe idea how can i solve it? BR. Kacper




mercredi 25 juillet 2018

Ember action not triggered in FireFox

This twiddle working in Chrome but not working in firefox

https://ember-twiddle.com/aa8196622fcd6b8f6ce441c8a9174600?openFiles=controllers.application.js%2C

I found similar issue here, but there is no reason for why it is not working.




Installing packages: --save or --save-dev and why?

When installing npm packages/addons in Ember.js, when to use --save or --save-dev and why?

Sounds quite simple, but I don't have it clear to when to use each one. Tried both to understand the difference, and the application seems to run fine.




How do I access grandparent model attribute in Ember using ember data

I have 3 models that are related: Parent > Child > Grandchild.

Parent hasMany Child Child hasMany Grandchild

I have a route /grandchildren that loads all grandchild records.

In the grandchildren template I am able to call .

My question is how do I access the Parent's attributes from the same template? I tried but it's coming up empty.

What is the Ember way to access a related model's attribute that's 2 levels deep?




Installing dygraphs with bower install fails on Ember.js

Issuing a statement:

bower install dygraphs --save

And than adding reference to dygraphs:

app.import('vendor/dygraphs/src/dygraph.js')

Causes an error:

Uncaught SyntaxError: Unexpected identifier

on line:

import DygraphLayout from './dygraph-layout';

And:

Uncaught ReferenceError: define is not defined at ember-adater-file.js:1

What can be the cause of this and how to fix it?




Ember JS testing - Factory guy

I am using ember 2.18 and ember-data-factory-guy 3.3.0.

I want to test an action inside a component. In the action, I am using makeList in order to create and return a list of models. In my ember app, I pass the store to the component and I am doing a query when I a call the action.

Here is my Factory:

import FactoryGuy from 'ember-data-factory-guy';

FactoryGuy.define('contact', {
  sequences: {
    first_name: (num) => `FirstName${num}`,
    last_name:  (num) => `LastName${num}`,
    email:      (num) => `contact${num}@example.com`,
    phone:      (num) => `01234567${num}`,
    linkedin:   (num) => `samplelinkedinurl${num}`,
  },
  default: {
    first_name: FactoryGuy.generate('first_name'),
    last_name:  FactoryGuy.generate('last_name'),
    email:      FactoryGuy.generate('email'),
    phone:      FactoryGuy.generate('phone'),
    linkedin:   FactoryGuy.generate('linkedin'),
    position:   'CEO',
    client_office: FactoryGuy.belongsTo('office')
  },
  traits: {
    withClient: {
      client: FactoryGuy.belongsTo('client')
    },
    withOffice: {
      client_office: FactoryGuy.belongsTo('office')
    }
  }
});

Additionaly, my action is the followin:

_this.store.query('contact', {term: searchTerm}).then(function(contacts) { ... })

I have create a TestStore class in order to test actions like these. It is a minimal replication of the querying methods of ember data store. The query method looks like that:

query(modelName, attributes, trait=null) {
  console.log('ATTRIBUTES PASSED TO TEST STORE QUERY: ', attributes)

  // make a new record of selected model with factory guy
  let _this = this,
       records = Ember.isEmpty(trait) ? makeList(modelName, 4) : makeList(modelName, 4, trait);

  // Push it to test-store
  if (!this.models[modelName]) {
      this.models[modelName] = Ember.A([]);
  }

  records.forEach(function(record) { 
  _this.models[modelName].pushObject(record); })


  // Create promise to return
  let recordPromise = new Ember.RSVP.Promise((resolve) => {
    resolve(records);
  });
  return DS.PromiseArray.create({promise: recordPromise});
}

In rendering tests it is working just fine. If I am to run the action manually (e.g. like in unit tests ), I get the following error:

FactoryGuy does not have the application's

manualSetup is not working as well, as the store service is stuck in the "willDestroy()" of the store and _pushedInternalModels is null so no Models can be pushed to the store.

Any ideas/suggestions on that?




Using GITHUB API for ember-app dashboard. How to achieve the response from github api https://ift.tt/2JREhW2

Hi I have been using the GITHUB API for practices purposes only and I came across with the API endpoint with this URL URL: https://api.github.com/users/mojombo/repos

On my ember app, I would like to show all the repos of a selected github user.

My approach was

On my route.js let parentModel = this.modelFor('dashboard.users.repos');

return this.store.query('repo', {
  filter: {
    'username': parentModel.get('login') //mojombo
  }
})

However, I am getting a 404 not found

Can someone would share their ideas on what is the approach for the above’s scenario? Thanks in advance




mardi 24 juillet 2018

ember modal popup not closing if i clicked background overlay to the modal

I want to close a modal if i click background overlay. i'm using clickOutsideToClose=false but its bot working.

installed versions:

ember: 2.12

ember-modal-dialog: 3.0.0




Where can I find documentation for Ember 0.9.8?

I have a client from years ago that wants a few changes to an Ember app that was written in ember-0.9.8. I haven't used ember since then, and I know a lot has changed. But, I still need to refer to the old documentation, and the website seems to only go back as far as 1.10.




How to Simulate a 404 Not Found Api endpoint with EmberJs Mirage

In config.js of Mirage. For example:

this.get('path/to/endpoint', (schema, request) => {
  return '404';
});

How should the returned response be formatted so that Mirage treats it like a real 404?




How to create a chat application in ember using sockjs?

I'm trying to create an ember app with chat rooms. I have used sock js to establish the connection. It worked when I used the plain html and js and connected it to backend in spring. How to integrate this working in ember? Also suggest if there is some tutorials. My html,css and js files are as follows:

'use strict';

var usernamePage = document.querySelector('#username-page');
var chatPage = document.querySelector('#chat-page');
var usernameForm = document.querySelector('#usernameForm');
var messageForm = document.querySelector('#messageForm');
var messageInput = document.querySelector('#message');
var messageArea = document.querySelector('#messageArea');
var connectingElement = document.querySelector('.connecting');

var stompClient = null;
var username = null;
var category = null;

var colors = [
    '#2196F3', '#32c787', '#00BCD4', '#ff5652',
    '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
];

function connect(event) {
    username = document.querySelector('#name').value.trim();

    if(username) {
        usernamePage.classList.add('hidden');
        chatPage.classList.remove('hidden');

        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);

        stompClient.connect({}, onConnected, onError);
    }
    event.preventDefault();
}


function onConnected() {
    // Subscribe to the Public Topic
    category = document.querySelector('#category').value.trim();
    console.log("category",category);
    stompClient.subscribe('/topic/public/'+category, onMessageReceived);

    // Tell your username to the server
    stompClient.send("/app/"+category+"/chat.addUser",
        {},
        JSON.stringify({sender: username, type: 'JOIN',category:category})
    )

    connectingElement.classList.add('hidden');
}


function onError(error) {
    connectingElement.textContent = 'Could not connect to WebSocket server. Please refresh this page to try again!';
    connectingElement.style.color = 'red';
}


function sendMessage(event) {
    var messageContent = messageInput.value.trim();
    console.log("category11",category);
    if(messageContent && stompClient) {
        var chatMessage = {
            sender: username,
            content: messageInput.value,
            type: 'CHAT',
            category:category
        };
        stompClient.send("/app/"+category+"/chat.sendMessage", {}, JSON.stringify(chatMessage));
        messageInput.value = '';
    }
    event.preventDefault();
}


function onMessageReceived(payload) {
    var message = JSON.parse(payload.body);

    var messageElement = document.createElement('li');

    if(message.type === 'JOIN') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' joined!';
    } else if (message.type === 'LEAVE') {
        messageElement.classList.add('event-message');
        message.content = message.sender + ' left!';
    } else {
        messageElement.classList.add('chat-message');

        var avatarElement = document.createElement('i');
        var avatarText = document.createTextNode(message.sender[0]);
        avatarElement.appendChild(avatarText);
        avatarElement.style['background-color'] = getAvatarColor(message.sender);

        messageElement.appendChild(avatarElement);

        var usernameElement = document.createElement('span');
        var usernameText = document.createTextNode(message.sender);
        usernameElement.appendChild(usernameText);
        messageElement.appendChild(usernameElement);
    }

    var textElement = document.createElement('p');
    var messageText = document.createTextNode(message.content);
    textElement.appendChild(messageText);

    messageElement.appendChild(textElement);

    messageArea.appendChild(messageElement);
    messageArea.scrollTop = messageArea.scrollHeight;
}

function getAvatarColor(messageSender) {
    var hash = 0;
    for (var i = 0; i < messageSender.length; i++) {
        hash = 31 * hash + messageSender.charCodeAt(i);
    }
    var index = Math.abs(hash % colors.length);
    return colors[index];
}

usernameForm.addEventListener('submit', connect, true)
messageForm.addEventListener('submit', sendMessage, true)
* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

html,body {
    height: 100%;
    overflow: hidden;
}

body {
    margin: 0;
    padding: 0;
    font-weight: 400;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 1rem;
    line-height: 1.58;
    color: #333;
    background-color: #f4f4f4;
    height: 100%;
}

body:before {
    height: 50%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: #128ff2;
    content: "";
    z-index: 0;
}

.clearfix:after {
    display: block;
    content: "";
    clear: both;
}

.hidden {
    display: none;
}

.form-control {
    width: 100%;
    min-height: 38px;
    font-size: 15px;
    border: 1px solid #c8c8c8;
}

.form-group {
    margin-bottom: 15px;
}

input {
    padding-left: 10px;
    outline: none;
}

h1, h2, h3, h4, h5, h6 {
    margin-top: 20px;
    margin-bottom: 20px;
}

h1 {
    font-size: 1.7em;
}

a {
    color: #128ff2;
}

button {
    box-shadow: none;
    border: 1px solid transparent;
    font-size: 14px;
    outline: none;
    line-height: 100%;
    white-space: nowrap;
    vertical-align: middle;
    padding: 0.6rem 1rem;
    border-radius: 2px;
    transition: all 0.2s ease-in-out;
    cursor: pointer;
    min-height: 38px;
}

button.default {
    background-color: #e8e8e8;
    color: #333;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
}

button.primary {
    background-color: #128ff2;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
    color: #fff;
}

button.accent {
    background-color: #ff4743;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.12);
    color: #fff;
}

#username-page {
    text-align: center;
}

.username-page-container {
    background: #fff;
    box-shadow: 0 1px 11px rgba(0, 0, 0, 0.27);
    border-radius: 2px;
    width: 100%;
    max-width: 500px;
    display: inline-block;
    margin-top: 42px;
    vertical-align: middle;
    position: relative;
    padding: 35px 55px 35px;
    min-height: 250px;
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    margin: 0 auto;
    margin-top: -160px;
}

.username-page-container .username-submit {
    margin-top: 10px;
}


#chat-page {
    position: relative;
    height: 100%;
}

.chat-container {
    max-width: 700px;
    margin-left: auto;
    margin-right: auto;
    background-color: #fff;
    box-shadow: 0 1px 11px rgba(0, 0, 0, 0.27);
    margin-top: 30px;
    height: calc(100% - 60px);
    max-height: 600px;
    position: relative;
}

#chat-page ul {
    list-style-type: none;
    background-color: #FFF;
    margin: 0;
    overflow: auto;
    overflow-y: scroll;
    padding: 0 20px 0px 20px;
    height: calc(100% - 150px);
}

#chat-page #messageForm {
    padding: 20px;
}

#chat-page ul li {
    line-height: 1.5rem;
    padding: 10px 20px;
    margin: 0;
    border-bottom: 1px solid #f4f4f4;
}

#chat-page ul li p {
    margin: 0;
}

#chat-page .event-message {
    width: 100%;
    text-align: center;
    clear: both;
}

#chat-page .event-message p {
    color: #777;
    font-size: 14px;
    word-wrap: break-word;
}

#chat-page .chat-message {
    padding-left: 68px;
    position: relative;
}

#chat-page .chat-message i {
    position: absolute;
    width: 42px;
    height: 42px;
    overflow: hidden;
    left: 10px;
    display: inline-block;
    vertical-align: middle;
    font-size: 18px;
    line-height: 42px;
    color: #fff;
    text-align: center;
    border-radius: 50%;
    font-style: normal;
    text-transform: uppercase;
}

#chat-page .chat-message span {
    color: #333;
    font-weight: 600;
}

#chat-page .chat-message p {
    color: #43464b;
}

#messageForm .input-group input {
    float: left;
    width: calc(100% - 85px);
}

#messageForm .input-group button {
    float: left;
    width: 80px;
    height: 38px;
    margin-left: 5px;
}

.chat-header {
    text-align: center;
    padding: 15px;
    border-bottom: 1px solid #ececec;
}

.chat-header h2 {
    margin: 0;
    font-weight: 500;
}

.connecting {
    padding-top: 5px;
    text-align: center;
    color: #777;
    position: absolute;
    top: 65px;
    width: 100%;
}


@media screen and (max-width: 730px) {

    .chat-container {
        margin-left: 10px;
        margin-right: 10px;
        margin-top: 10px;
    }
}

@media screen and (max-width: 480px) {
    .chat-container {
        height: calc(100% - 30px);
    }

    .username-page-container {
        width: auto;
        margin-left: 15px;
        margin-right: 15px;
        padding: 25px;
    }

    #chat-page ul {
        height: calc(100% - 120px);
    }

    #messageForm .input-group button {
        width: 65px;
    }

    #messageForm .input-group input {
        width: calc(100% - 70px);
    }

    .chat-header {
        padding: 10px;
    }

    .connecting {
        top: 60px;
    }

    .chat-header h2 {
        font-size: 1.1em;
    }
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Spring Boot WebSocket Chat Application</title>
    <link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<noscript>
    <h2>Sorry! Your browser doesn't support Javascript</h2>
</noscript>

<div id="username-page">
    <div class="username-page-container">
        <h1 class="title">Type your username</h1>
        <form id="usernameForm" name="usernameForm">
            <div class="form-group">
                <input type="text" id="name" placeholder="Username" autocomplete="off" class="form-control" />
                <input type="text" id="category" placeholder="Category" autocomplete="off" class="form-control" />
            </div>
            <div class="form-group">
                <button type="submit" class="accent username-submit">Start Chatting</button>
            </div>
        </form>
    </div>
</div>

<div id="chat-page" class="hidden">
    <div class="chat-container">
        <div class="chat-header">
            <h2>Spring WebSocket Chat Demo</h2>
        </div>
        <div class="connecting">
            Connecting...
        </div>
        <ul id="messageArea">

        </ul>
        <form id="messageForm" name="messageForm">
            <div class="form-group">
                <div class="input-group clearfix">
                    <input type="text" id="message" placeholder="Type a message..." autocomplete="off" class="form-control"/>
                    <button type="submit" class="primary">Send</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script src="/js/main.js"></script>
</body>
</html>



TypeError: Cannot read property 'length' of null doesn't make sense

I keep getting a TypeError: Cannot read property 'length' of null and it doesn't make sense why it's throwing..

Test:

await render(hbs``);

assert.equal(this.element.querySelector('div.card-details div#summary').length, 1);

await click('.card-details__show-more-link');

assert.equal(this.get('isExpanded'), true);

Compiled .hbs file for card-details:

this is a picture of it from the chrome dev console, the actual .hbs file is too big and confusing.




lundi 23 juillet 2018

Ember.js - Accessing nested data via serializer

What is the best approach for accessing a single nested record in Ember?

The JSON response which we are trying to manipulate looks gets returned as the following: (the attribute being targeted is the tradeIdentifier property)

trade:
    tradeIdentifier:"83f3f561-62af-11e7-958b-028c04d7e8f9"
    tradeName:"Plumber"
userEmail:"test@gmail.com"

The project-user model looks partially like:

  email: attr('string'),
  trade:attr(),
  tradeId: attr(),

The project-user serializer looks partially like:

export default UndefinedOmitted.extend(EmbeddedRecordsMixin, {
  primaryKey: 'userRoleId',
  attrs: {
    'email': { key: 'userEmail' },
    'trade': { key: 'trade' },
    'tradeId': { key: 'tradeIdentifier' },
  },
});

The trade attr here is a placeholder to make sure that the data was accessible. I would like to be able to access the tradeIdentifier without having to do the following in the component:

const trade = get(formRole, 'trade');
if (trade) {
  set(formProps, 'tradeId', trade.tradeIdentifier);
}

Have tested creating a trade-id transform (referenced via tradeId: attr('trade-id')), however to no avail.

export default Transform.extend({
  deserialize(val) {

    const trade = val;
    const tradeId = val.tradeIdentifier;

    return tradeId;
  },
  serialize(val) {
    return val;
  },
});

Can anyone suggest where I'm going wrong?




Creating a component that is the "mix" of two components (extending from 2 components)

I'm building a set of components which can have variants in their behavior.

More specific, I have a x-tag component, which can behave as a <span> that simply renders text or an <a> that also renders text and links to another route.

For the "link" part I'm using the link component provided by Ember (which is the link-to) to not reimplement all the routing logic by myself.

The ideal would be to only have two components:

  • x-tag, simple text version that handles the base logic.
  • x-tag-link-to, link version which should be a component extending from the link-to and x-tag components.

Since you cannot extend from two components, I moved the logic in the x-tag component into a tag mixin. So the components ended up like this:

  • x-tag, compoents that implements the tag mixin.
  • x-tag-link-to, compoents that extends the link-to component and also implements the tag mixin.

This solves the problem, but is confusing having the logic in several files, also I have a lot more components like the tag that also have a link version, filling the mixins folder with a lot of mixins which have almost the whole component logic. That just feels wrong, or is this the right approach?

I can provide code examples if needed.




any ideas solve iterator implementation?

some one give me an ideas for the coding challenge: - The task is to write an iterator which polls a number of external services and if a certain criterion is met, redirects the user elsewhere.

From the user's perspective, the experience is as follows:

  • user arrives to the site,
  • clicks a button,
  • sees a loader,
  • and is redirected to another page.

From the technical perspective, the flow follows a similar pattern:

  • user arrives to the site,
  • front end makes a request to the first service,
  • the first service responds with the url of the second service and instructs to make an XHR request, 4. front end makes a request to the second service,
  • 3-4 are repeated n times
  • the (n+1)th service responds with the next url and instructs to redirect the user to the page

Spec Example of backend service responses including the next request's URL and what to do with it:

GET / (Response instructing an XHR request)

    {
    "activity": "xhr"
    "activity_url": "http://example.com/xhr_endpoint"
    }

GET / (Response instructing a redirect)

    {
    "activity": "redirect",
    "activity_url": "http://example.com/landing_page"
    }

  • The first activity url should be predefined (offer_url).

  • The "activity_url" param is sent to you encoded using base64 URL-safe alphabet.

so can any one help me for writing that iterator ?




How to handle the array of objects in Ember Js Handlebars

I'm getting the response from the server like

category:{
    listOfCategory: [
        "diabetes",
        "general"
    ],
    id:1

}

using Ember data findAll method. I'm returning this to my model and I'm trying to display in hbs file using each loop.

js code

model(){
       return this.store.findAll('category');
}

hbs code


     <h1></h1>


Output :

diabetes,general

I want to display as separate category.




dimanche 22 juillet 2018

How to include the icon inside the tooltip message

I need to include the download icon inside the tooltip message, I have tried the below code:

ObjectIconView: Ember.ContainerView.extend(childMOMixin, {
                iconDownload: function () {
                              model: 'download'
                },
                mouseEnter: function(e) {
                if(type == 'Text'){
                var textUrl = {content: 'Preview is Not Available, Use '+ this.iconDownload() +'Menu'};
                this.$().tooltip(textUrl);
}

In that I have called the iconDownload inside the tooltip. But it's saying undefined in the output. I'm using Ember 1.4.0 version. Can anybody please provide the suggestion for this. I'm new to the Ember. Thanks in advance




vendredi 20 juillet 2018

Ember nested routes but non-nested templates

In an Ember app, is it possible to have nested routes but non-nested templates ?

Any examples for reference would be really helpful.




Get popup modal innerHTML in Ember Qunit test

I'm doing integration component testing with ember-qunit. So how to get popup modal body text once its open from an action.

text-bar-test

test('it renders with title', function(assert) {
    assert.expect(1);

    this.render(hbs``);
    this.$('.open-app').click();  // opening from text-bar hbs template
    assert.equal(this.$('.body-text').innerHTML(), 'its modal-body text', 'Modal body text test once opens');

});




jeudi 19 juillet 2018

Need to call the Action inside the function

I'm new to the ember and doing the action for while click on the download icon in the folder type. It have to download as zip. For that they wrote already in the java and created a service for that as like below:

Core.Action({
    id: 'core:downloadZip',
    invoke: function (context) {
        console.log(context);
        var mos = Ember.get(context, 'managedObjects') || [Ember.get(context, 'managedObject')];

    var moIdResult = [];
    var moArray ='';
    mos.forEach(function (mo) {
        moArray = moIdResult.push(mo.get('finalManagedObject.id'));
      });
      Core.services({
        download:true,
          type: 'get',
          service: 'content/zip',
          iframe: true,
          data: {
            coreId: moIdResult
          }
      }).done(function (response) {
          console.log(response);
      }.bind(this));
  },isValid: rules.all(
          rules.any(rules.isMO, rules.areMOs),
          rules.not(rules.isHome)
      )
});

In that service: 'content/zip' doing that action as download as zip from the java file. But when I'm calling the above code in the same file as like below:

           click: function(e) {
                  var type = this.get('content.kind');
                  if(type == 'Folder'){
                      Core.Action('core:downloadZip', context);
                  }
           }

When I'm calling as like above, its not taking and moreover not even showing any error. Cany anybody please provide me suggestion on this. I'm new to the Ember and I'm using ember 1.4.0 version. Thanks in advance




Ember.set and Ember.setProperties gives different results

I ran into a problem in my Ember application where setting multiple properties using Ember.set and Ember.setProperties produced a buggy result in the latter. Constructed an exact scenario here.

HBS:

Name: <br>
Place: <br><br>

<button >this.setProperties({name:"Vignesh Raja",place:"Namakkal"})</button>

<br><br><br>

<button >this.set("name","Vignesh Raja");<br>this.set("place","Namakkal");</button>

<br><br><br>

When set seperately, we get the latest value - {name:"Vignesh Raja", place:"Namakkal"}<br>
When set together, we get the latest value from the observer- {name:"Vignesh Raja", place:"Chennai"}<br>
<br>
<br>

JS:

import Ember from 'ember';

export default Ember.Controller.extend({
    name:"Vignesh",
    place:"Nmkl",

    handleName1 : function(){
        this.set("place","Chennai");
    }.observes("name"),

    actions:{
        modifyTogether:function(){
            this.setProperties({name:"Vignesh Raja",place:"Namakkal"})
        },

        modifySeperately:function(){
            this.set("name","Vignesh Raja");
            this.set("place","Namakkal");
        }
    }
});

Ember Twiddle

In the above code, clicking first button (Ember.setProperties) gives Name: Vignesh Raja Place: Chennai, but clicking second (multiple Ember.set) gives Name: Vignesh Raja Place: Namakkal




Implementing Ember computed property behavior in Angular

I was working on an Ember project and currently I'm redesigning it with angular. My Ember project use computed property technique in a lot of places and it makes the implementations very straightforward.

I would like to use a similar pattern in my new angular project. But I couldn't find such behavior yet. Great if anyone can give a support. Thanks in advance.




What's the conventional directory for classes in an Ember project?

If I create a custom class according to https://guides.emberjs.com/release/object-model/classes-and-instances/,

e.g.

// person.js
import EmberObject from '@ember/object';

const Person = EmberObject.extend({
  say(thing) {
    alert(thing);
  }
});

Is there a conventional directory in the ember project for person.js?

None of these conventional directories seem quite right...

  • adapters/ (specific purpose)
  • components/ (specific purpose)
  • controllers/ (specific purpose)
  • helpers/ (specific purpose)
  • models/ (for actual DS Models)
  • routes/ (specific purpose)
  • styles/ (not js)
  • templates/ (not js)
  • serializers/ (specific purpose)
  • utils/ (too generic)



Ember sorting/filter table

I am looking to add a filter/sorter table into the application. I need to choose which column can be sorted - and provide change of class glyphs up/down arrows on the columns. The filter box also needs to be outside of the table.

  • I tried looking at this example, but there are no glyph class changes on the cols and the filter box is inside the table.

http://crodriguez1a.github.io/ember-sort-filter-table/

  • I looked at this custom solution, but I couldn't see a way of locking the filter to specific cols.

http://www.jarrodctaylor.com/posts/Filter-And-Sort-Tables-In-Ember/ http://emberjs.jsbin.com/yezonaxu/12/edit?html,css,js,output




What does "Cannot destructure property `owner` of 'undefined' or 'null'." mean and how do I combat it when running acceptance tests in Ember.JS

I'm running acceptance tests on Ember.JS 2.16 and I keep getting this error.

On localhost:4200/tests

Died on test #1     at Module.callback (http://localhost:4200/assets/tests.js:26:19)
    at Module.exports (http://localhost:4200/assets/vendor.js:111:32)
    at requireModule (http://localhost:4200/assets/vendor.js:32:18)
    at TestLoader.require (http://localhost:4200/assets/test-support.js:10741:9)
    at TestLoader.loadModules (http://localhost:4200/assets/test-support.js:10734:14)
    at loadTests (http://localhost:4200/assets/test-support.js:12393:22)
    at start (http://localhost:4200/assets/test-support.js:12143:33): Cannot destructure property `owner` of 'undefined' or 'null'.

TypeError: Cannot destructure property `owner` of 'undefined' or 'null'.
    at visit (http://localhost:4200/assets/test-support.js:9653:21)
    at Object.<anonymous> (http://localhost:4200/assets/tests.js:27:28)
    at runTest (http://localhost:4200/assets/test-support.js:4276:30)
    at Test.run (http://localhost:4200/assets/test-support.js:4262:6)
    at http://localhost:4200/assets/test-support.js:4483:12
    at advanceTaskQueue (http://localhost:4200/assets/test-support.js:3875:6)
    at advance (http://localhost:4200/assets/test-support.js:3856:4)
    at advanceTestQueue (http://localhost:4200/assets/test-support.js:3901:4)
    at Object.advance (http://localhost:4200/assets/test-support.js:3859:5)
    at begin (http://localhost:4200/assets/test-support.js:5881:20)

And this is the test..

import { test } from 'qunit';
import { visit, currentURL, andThen } from '@ember/test-helpers';
import moduleForAcceptance from '../helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | basic');

test('find /plans', function(assert) {
  visit('/plans');

  andThen(function() {
    assert.equal(currentURL(), '/plans');
  });
});

It's pretty basic and I followed the guide from https://guides.emberjs.com/v2.16.0/testing/acceptance/

I'm not sure what this error means or how to combat it, any bit of information helps. Thanks.




mercredi 18 juillet 2018

Ember: Revert unloadRecord

I'm listing a hasMany relationship, of which a record can be updated, deleted or added.

I want to provide the user with a revert option, which should revert the list to its last saved state.

For deletion, I do item.deleteRecord(), so that I can revert the changes using rollbackAttributes(). Changes are reverted as expected, but it behaves inconsistently while saving (saving the model to which the items belong doesn't update its dirty state on first save, next record disappears from the view though the changes sent to the back-end properly, and so on).

So I decided to use unloadRecord, but once a record is unloaded, I'm unable to revert it without reloading the page.

One way would be to save the old state and use it on revert. Please help me with a cleaner to achieve this.

For an idea of my model, Ember: Model's property changes not detected in computed property




Ember.sj - How to deal with API-Platform - resource link instead of Id in payload

I use Emberjs 3.2 with Api-Platform and I ran into the following problem:

Here is my API payload:

{
      "id": "/api/articles/0d8cb40c-221b-4c54-9e29-43877093b839",
      "type": "Article",
      "attributes": {
        "_id": "0d8cb40c-221b-4c54-9e29-43877093b839",
        "title": "Article",
        "content": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>",
        "dateCreated": "2018-07-17T18:20:29+03:00",
        "dateUpdated": "2018-07-17T18:20:29+03:00"
      },
      "relationships": {
        "author": {
          "data": {
            "type": "User",
            "id": "/api/users/b26e0381-6800-4f47-b269-9a92b27ad331"
          }
        }
      }
    }

As you can see, I got an IRI instead of id in the payload.

I turned on api-platform option: allow_plain_identifiers: true but I still get IRI instead of ID for the related entities.

How can I deal with this using EmberData JSONApi Adapter?

I appreciate any ideas!




mardi 17 juillet 2018

How to define nested routes with module unification turned on

I am new to Ember and am likely making a simple mistake somewhere, but I am having trouble getting nested routes (3 levels of nesting) working in a simple app with module unification turned on, in both ember 3.2.0 and 3.3.0.

(I was able to get the same routes working in another app without module unification.)

In my app, I have module unification turned on by setting the following environment variables in my .bashrc:

export EMBER_CLI_MODULE_UNIFICATION='true'
export MODULE_UNIFICATION='true'

Here are the relevant lines of my src/router.js:

Router.map(function() {
  this.route('peach', function() {
    this.route('pear', function() {
    });
  });
});

Here is src/ui/routes/peach/index/template.hbs:

peach


Here is src/ui/routes/peach/pear/index/template.hbs:

pear

Navigating to http://localhost:4200/peach/pear results in a blank browser page with the following error:

jQuery.Deferred exception: this._config.collections[specifier.collection] is undefined _checkDefaultType@http://localhost:4200/assets/vendor.js:69136:11

TypeError: this._config.collections[specifier.collection] is undefined

Why are these routes not working with module unification turned on, and how can I get them working?




Add a download icon that is only visible on hover

I need to create the download icon and it needs to visible on Mouse Hover and have to click that icon for download the corresponding items. In that I have created download icon and while clicking its downloading the file correctly. But I want to hide the download icon and it need to visible on mouse hover and click to download the items.

Here I have tried the below code:

DownloadItem: Ember.ContainerView.extend(childMOMixin, {
                classNames: ['download-icon'],
                classNameBindings: [ 'clickable' ],
                attributeBindings: [ 'style', 'src' ],
                style: function () {
                    console.log(this);
                    return 'font-size: ' + this.get('size') + 'px';
                }.property('size'),
                click: function(e) {
                var type = this.get('content.kind');
                if(type == 'Image'){
                var imgUrl = this.content.streamingUri;
                window.location = imgUrl;
                }
            childViews: [
                            'DownloadIcon',
                        ],
                        size: 20,
DownloadIcon: Core.component.DownloadIcon.extend(childMOMixin, {
              sizeBinding: 'parentView.size',
              loadStateBinding: 'parentView.loadState',
              downloadBinding: 'parentView.download'
            })

I'm using Ember 1.4.0 version. please provide me some suggestion regarding this update. Your help will be appreciate. Thanks in advance.




How to add apple-app-site-association file to my Ember app?

Ember newbie here. I am trying to host the apple-app-site-association file in our s3 instance and am not sure how to do it. We have a website and a web application written in Ember. Like mysite.com leads to the site and mysite.com/app leads to the app.

The apple-app-site-association file needs to be in the root of the domain so when I invoke mysite.com/apple-app-site-association, I should be able to download the file. When I try adding the file to the public folder of the website and try to access it, the web app's 404 route is triggered.

So when I try to reach mysite.com/apple-app-site-association the url changes to mysite.com/app/apple-app-site-association and it says page not found.

The website itself doesn't have a redirect. Only the web app has the redirect so am not sure why it is triggered. Am new to Ember so am sorry if it is something obvious.




Is there a way to get all the attributes passed to an Ember component?

For example, given the following code:



Inside the my-component/component.js file, I need a method to get all the passed attributes, something like this:

{
    foo: "bar",
    baz: "qux"
}

Does Ember have something to accomplish this? Or the only way is to do something hacky?




Localization in ember-pikaday

How can we apply localization to ember-pikaday addon ?

I followed the steps described in their README but the months are still displayed in English. I've even open an issue but it has no responses yet.

Thank you !




How to run jQuery from html - The ember way

I'm and trying to run jQuery from the .hbs file, which works by putting the handlebars in the file. But, then the text '[object Object]' is placed into my HTML as text. What can I change so that the jQuery still runs but does not place '[object Object]' in the HTML?


app.js below

import Controller from '@ember/controller';
import { computed } from '@ember/object';
import $ from 'jquery';

export default Controller.extend({
  NavIsViewable: true,
  fixedMenu: computed(function(){
    return $(".navbar").width($(".disable-listing-style").width());
  })
});



app.hbs below


   <div id="nav" class="nav">
     
     
   </div>


Resulting Issue below
enter image description here




Autocomplete search with One letter is not working

When I search the user name in the search box of autocomplete by using the first letter of the user name. Its not showing any names. When I enter the second letter its showing the names. But when I erase the second letter of the name and its showing the names with the single letter.

Here are the code I'm using:

keyUp: function (e) {
                var inputFieldName = this.name;
                var inputFieldValue = this.value;
                console.log(inputFieldName);
                console.log(inputFieldValue);
                var autocompletedata='';
                if(inputFieldValue != undefined){
                if(inputFieldName==='checkedoutuser' && inputFieldValue.length >= 1) {
                    var inputFieldValue = this.value;
                    Vsuite.services({
                           service:'searchsuggestion',
                          async: false,
                           type: 'get',
                           json: true,
                           data: {
                                  facetValue: inputFieldValue, 
                                  resultSetLimit: 20
                         }
                          }).done(function (responseData) {
                              console.log(responseData);

                              var checkedOutId = $('.repeat-instance input[name="'+inputFieldName+'"]').attr('id');
                              this.setProperties({
                                  autocompletedata: responseData,
                            });
                              console.log(autocompletedata);
                              console.log(responseData);
                               $('#'+checkedOutId).autocomplete({
                                    source: responseData,
                                    delay: 1000,
                                    minLength: 1,
                                    open: function () {
                                        console.log($('#autocomplete-add-refine').length)
                                        console.log(checkoutUserList.length)
                                        if ($('#autocomplete-add-refine').length == 0 && checkoutUserList.length >= 5) {
                                                $('<li id="autocomplete-add-refine"><b>Continue typing to refine further</b> </li>').appendTo('ul.ui-autocomplete');
                                                console.log($('#autocomplete-add-refine').length);
                                                $('ul.ui-autocomplete').css({
                                                    'max-height': '120px',
                                                    'overflow-y': 'auto',
                                                    'overflow-x': 'hidden'
                                                });
                                        }
                                        else {
                                            $('#autocomplete-add-refine').remove();
                                        }
                                   }
                              if($('#autocomplete-add-refine').length > 0 && checkoutUserList.length <=20) {
                                $('#autocomplete-add-refine').remove();
                            }

                               });
                          }.bind(this));
                }
                else {
                    Ember.run.later(this, function () {
                        this.$().change();
                    }, 125);
                }
                }
            },

I need the search names needs to come when I enter the single letter of the name on the first time itself. Your help will be appreciate. I'm using Ember 1.4.0.




lundi 16 juillet 2018

Ember Upgrade from 3.1 to 3.2 breaks subclassing class from addon

My project uses Ember Table, and we create a subclass of their 'ColumnDefinition' model. When I upgrade from Ember/Ember-data 3.1 to Ember 3.2 (regardless if I upgrade Ember-Data). I get the following error

jquery.js:3827 Uncaught TypeError: Class constructor ColumnDefinition cannot be invoked without 'new'
at new Class (VM64 ember.debug.js:40121)
at Function.create (VM64 ember.debug.js:40546)
at s.callback (VM73 about:srcdoc:24)
at s.exports (VM62 loader-9d2ccefb0dfd6784cc87f799ef2c9f44.js:17)
at requireModule (VM62 loader-9d2ccefb0dfd6784cc87f799ef2c9f44.js:4)
at Class._extractDefaultExport (VM68 twiddle-deps-86f6227589c097fcadf3a3088942a69b.js:65)
at Class.u (VM68 twiddle-deps-86f6227589c097fcadf3a3088942a69b.js:31)
at Class.superWrapper [as resolveOther] (VM64 ember.debug.js:43503)
at Class.resolveController (VM64 ember.debug.js:13856)
at Class.resolve (VM64 ember.debug.js:13763)

I know there are problems subclassing native classes in Ember, but the EmberTable object is itself an extension of Ember.Object

I have a twiddle reproducing the problem here: https://ember-twiddle.com/a1c519a2ee39714027dc12df2248464f?openFiles=twiddle.json%2C




How do I send details from the form to a rest API in ember.js?

I'm relatively new to ember and I have been trying to send a POST request to REST API. Can someone explain how POST request is done in ember?




dimanche 15 juillet 2018

Need to create the download icon on the child view only

I'm in the process of creating the download Icon on near to the item as like pdf, image, xml etc, and it need to download the corresponding file once I click that Icon.

I have created the below code for creating the download icon:

DownloadItem: Core.view.Icon.extend(childMOMixin, {
                model: 'download',
                classNames: ['download-icon'],
                classNameBindings: [ 'clickable' ],
                attributeBindings: [ 'style', 'src' ],
                style: function () {
                    console.log(this);
                    return 'font-size: ' + this.get('size') + 'px';
                }.property('size'),
            }).named("ManagedObjectDownloadItem"),

In that, download icon fetching from the model: 'download', But when I used this, its getting affect on folder as well as the corresponding items:

enter image description here

In that attached image can see the affected folder. But it need to come only near to the corresponding item. I'm using Ember 1.4.0 (Quite Old version). Can anyone please help me on this to create download icon only near to the corresponding item. Thanks in advance.




Error: permission_denied at /items: Client doesn't have permission to access the desired data

I can neither receive nor write data in the Cloud Firestore (Firebase). I do everything in an application based on Ember.

In the file config/environment.js were added all the data from the "console" Firebase.

I also changed the access rules for testing:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

When I try to retrieve the data:

model () {
  return this.store.findAll('item')
}

I'm getting errors:

Error while processing route: index – "permission_denied at /items: Client doesn't have permission to access the desired data."

And:

Error: permission_denied at /items: Client doesn't have permission to access the desired data.

What is the problem?




Ember Responsive: cannot get setBreakpoint() acceptance test helper to work

Attempting to use the Ember Responsive add-on to add breakpoints to my acceptance test. I think I'm setting everything up right, and the breakpoints work fine in my handlebar templates, but I'm getting a weird error when running my test. Here is the error:

Error: Could not find module `ember-responsive/media` imported from `{my_repo}/tests/helpers/responsive`

TypeError: Cannot read property 'exports' of undefined

I'm using the beta version (as specified in my package.json):

    "ember-responsive": "^3.0.0-beta.3",

I'm importing the helper into my start-app.js:

import './responsive';

And in my testing file, I import setBreakpoint as follows:

import { setBreakpoint } from 'ember-responsive/test-support';

Here's my failing test:

test('menu icon appears on mobile', function(assert)  {
  assert.expect(1);

  setBreakpoint('mobile');
  visit('/home');

  andThen(function() {
    assert.equal(find('#menu .app-menu .menu-icon').length, 1);
  });

});

:( :( :( Any ideas? I had to upgrade ember-responsive from v.2 so maybe I did something wrong? I just uninstalled using npm and then reinstalled.




samedi 14 juillet 2018

Using and binding JSONAPI attributes data in ember js

I have an ember.js toy application that I want to hook into a JSONAPI REST service for obtaining and displaying data. I can trace in my browser's developer console, that indeed, ember-data initiates the appropriate GET requests and receives proper, valid JSONAPI response bodies.

// ./app/models/person.js
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  email: DS.attr('string'),
  birthdate: DS.attr('string')
});
// ./app/adapters/person.js
import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({
  pathForType() {
    return "persons";
  }
});
// ./app/adapters/application.js
import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    host: 'http://localhost:5000'
});
// ./app/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('persons', function() {
    this.route('show', { path: '/:person_id' });
  });
});
export default Router;
// ./app/routes/persons/show.js
import Route from '@ember/routing/route';

export default Route.extend({
  model(params) {
    return this.get('store').findRecord('person', params.person_id);
  }
});
// ./app/routes/persons/index.js
import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return this.get('store').findAll("person");
  }
});
// ./app/routes/application.js
import Route from '@ember/routing/route';

export default Route.extend({
});
// ./app/app.js
import Application from '@ember/application';
import Resolver from './resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';

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

loadInitializers(App, config.modulePrefix);

export default App;
// ./app/resolver.js
import Resolver from 'ember-resolver';

export default Resolver;

Unfortunately, when I want to use the model in my template, I can only access the element ids, and not the data attributes like name (Remains empty when rendered).

<!-- ./app/templates/persons/index.hbs -->

<li>
    Person  
    
    
    Link 
    
</li>


I am a bit at loss for why this happens. Am I doing something wrong?




Ember - No Data in hasMany Relationship On Initial Load

ember-cli - 3.20, ember-data - 3.30

I am trying to modify the data in a hasMany relationship in the controller setup but the relationship has no data. However, all the data is there after the page is fully loaded (i.e. in my template/actions, all relationship data is there)

I have a Quiz application with Many-Many relationship with Questions.

models/Quiz.js

import { computed } from '@ember/object';
import DS from 'ember-data';

const { attr, hasMany, Model } = DS;

export default Model.extend({
  description: attr('string'),
  questions: hasMany('question', {async: true}) //also tried with async false

});

models/Question.js

export default Model.extend({
  question: attr('string'),
  quizzes: hasMany('quiz', {async: true}) //also tried with async false
});

Go to url '/quiz/1' and Route calls findRecord on quiz

routes/quizzes/quiz.js

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

export default Route.extend({
  model(params) { return this.store.findRecord('quiz', params.quiz_id); }
});

controllers/quizzes/quiz.js

import { computed } from '@ember/object';
import Controller from '@ember/controller';

export default Controller.extend({
  quiz: computed.alias('model'),

  modelChanged: function() {
    let quiz = this.get('quiz');
    let questions = quiz.get('questions'); //questions has no data
    questions.then(questions => {
      Promise.all(questions.map(question => {
        //modify questions/answers here
      }));
    });
  }.observes('model')

actions: {
  getQuestions() {
    let questions = this.get('quiz.questions');  //questions now has data
  }
})};

I have tried to get the question data in both setupController() and afterModel() with no luck.

What has worked:
The quizzes are nested routes able to select between each quiz to display. So if you navigate from '/quiz/1' to '/quiz/2' and then back to 'quiz/1', the question data is available in the observer, setupController, afterModel, etc. So, the second time you access a specific quiz, the data is available in setup. (data is always available in template/actions).

Any ideas?




How to load custom test helpers in Ember 3.2 tests?

I seem to be missing some info about how to register a test helper in Ember 3.2, looking for some guidance:

I'm trying to use a test helper (see here) which I've placed in my tests/helpers directory, and am trying to reference it in a test:

import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';

module('Integration | Component | my-component', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  test('it renders nothing by default', async function(assert) {
    const company = server.create('company');
    this.pushMirageRecordsToStore(); // this doesn't work
    await render(hbs``);

    assert.equal(this.element.textContent.trim(), '');

  });

When this.pushMirageRecordsToStore() is called the error is:

TypeError: this.pushMirageRecordsToStore is not a function

Which leads me to believe the registerAsyncHelper helper in that link is not being called.

My question is how do I make the Ember test framework call registerAsyncHelper in that test helper so I can do this.pushMirageRecordsToStore()?




vendredi 13 juillet 2018

How do I access object property in Handlebars template?

My Ember component JS looks like below;

row = {};
Ember.set(row[my.constants.fieldKey], "cssType", 'leftPadding')

and my component HBS looks like below;



In short, how do I access the following (evaluated example here) in hbs dynamically ??

row['my-field-key'].cssType




Stuck creating new Ember project in WebStorm with Ember.js plugin

I'm getting stuck creating a new project using the Ember plugin with WebStorm. At the bottom it says "/usr/local/Cellar/node/9.5.0/bin/node "" init --name=untitled" and there's a line that just keeps spinning under it. Is it missing the script for node to run and what should I look at to fix this? I tried specifying some different path for node and ember but it didn't help.

enter image description here




Gin-Gonic EmberJS routing

I have an issue and I'm not quite certain how to get around it.

Basically I have a GIN server running and have Ember as the frontend. Basically the issue I have is when I reach out to my Ember routers, GIN grabs them and says they couldn't be found. It does however send the initial index route from my ember app.

If I have:

r.Use(static.Serve("/", static.LocalFile("./emberpages/public", true)))

The above does render my index correctly and I can redirect within the index.js router however if I try to get to a different page by appending hte route everything seems to crap out and GIN says it couldn't find the file.

Eg.

https://myserver/register  = 404 from gin

https://myserver = 200 serves the index.html page and the index route.

My question is, how can I redirect all of the get requests for my ember app to the ember router without GIN commandeering them?

router.js

Router.map(function () {
    this.route('login');
    this.route('register');
    this.route('dashboard');
});

Note: If I call the following in my controller, the register page loads correctly so ember is routing correctly it is just GIN taking over hardtyped get request.

this.transitionToRoute('register') 




Failed to load resource: the server responded with a status of 403 ()

I have an application based on Ember (as SPA). I'm doing the deployment in Firebase Hosting. Also I have a Rails application that works as an API provider. Rails application has on board GraphQL. Also Rails application has a connection with Google Storage.

In one of the Rails requests, the application returns a list that contains links to the images:

https://files.site.com/uploads/image/file/88/7d/5a/0ab3beg2fea0af6c.jpg

If I insert a link in a new browser tab, an image is opened.

But on the SPA page I see such errors (in the list, for example, 12 items):

Failed to load resource: the server responded with a status of 403 ()
Failed to load resource: the server responded with a status of 403 ()
Failed to load resource: the server responded with a status of 403 ()
# etc

What could be the problem?




What is Ember metal?

What is Ember metal? Can I use it?

I tried getting ember metal from Ember.metal and Ember.Metal but they were not defined.

I saw it because I was reading ember core code, and I see it's used a couple of times. _emberMetal




Use Ember Js with java backend in Tomcat

I was given a task to do ember js as front end and java backend in tomcat . I searched around and got some idea about frontend in ember but how to i use it with tomcat .I am completely new to this and I don't know if i have to use any API for that backend rather than using web.xml and url pattern to match servlets. Please give some link to docs so i can refer. Thanks in advance.




jeudi 12 juillet 2018

Ember test fail with `testem.js not loaded?`

i'm getting below error message mentioned below for an ember project when running tests locally with ember test. most of time PhantomJS was hanging.

$ ember test

not ok 1 Chrome - error
---
    message: >
        Error: Browser failed to connect within 30s. testem.js not loaded?
        Stderr: 
         2018-07-13 11:24:43.115 Google Chrome[47537:547312] Errors logged by ksadmin: KSKeyedPersistentStore store directory does not exist. [com.google.UpdateEngine.CommonErrorDomain:501 - '/Library/Google/GoogleSoftwareUpdate/TicketStore' - 'KSKeyedPersistentStore.m:368']
        KSPersistentTicketStore failed to load tickets. (productID: com.google.Chrome) [com.google.UpdateEngine.CoreErrorDomain:1051 - '/Library/Google/GoogleSoftwareUpdate/TicketStore/Keystone.ticketstore'] (KSKeyedPersistentStore store directory does not exist. - '/Library/Google/GoogleSoftwareUpdate/TicketStore' [com.google.UpdateEngine.CommonErrorDomain:501])
        ksadmin cannot access the ticket store:<KSUpdateError:0x100404060
            domain="com.google.UpdateEngine.CoreErrorDomain"
            code=1051
            userInfo={
                function = "-[KSProductKeyedStore(ProtectedMethods) errorForStoreError:productID:message:timeoutMessage:]";
                date = 2018-07-13 03:24:43 +0000;
                productids = {(
                    "com.google.Chrome"
                )};
                filename = "KSProductKeyedStore.m";
                line = 102;
                NSFilePath = "/Library/Google/GoogleSoftwareUpdate/TicketStore/Keystone.ticketstore";
                NSUnderlyingError = <KSError:0x100515350
                    domain="com.google.UpdateEngine.CommonErrorDomain"
                    code=501
                    userInfo={
                        date = 2018-07-13 03:24:43 +0000;
                        line = 368;
                        filename = "KSKeyedPersistentStore.m";
                        function = "-[KSKeyedPersistentStore(PrivateMethods) validateStorePath]";
                        NSFilePath = "/Library/Google/GoogleSoftwareUpdate/TicketStore";
                        NSLocalizedDescription = "KSKeyedPersistentStore store directory does not exist.";
                    }
                >;
                NSLocalizedDescription = "KSPersistentTicketStore failed to load tickets.";
            }
        >
        [47537:28675:0713/112447.920274:ERROR:ssl_client_socket_impl.cc(1026)] handshake failed; returned -1, SSL error code 1, net_error -107
        [47537:28675:0713/112448.006779:ERROR:ssl_client_socket_impl.cc(1026)] handshake failed; returned -1, SSL error code 1, net_error -107
        2018-07-13 11:24:52.494 Google Chrome Helper[47600:548065] Couldn't set selectedTextBackgroundColor from default ()


    Log: |
        { type: 'error',
          text: 'Error: Browser failed to connect within 30s. testem.js not loaded?' }
        { type: 'error',
          text: '2018-07-13 11:24:43.115 Google Chrome[47537:547312] Errors logged by ksadmin: KSKeyedPersistentStore store directory does not exist. [com.google.UpdateEngine.CommonErrorDomain:501 - \'/Library/Google/GoogleSoftwareUpdate/TicketStore\' - \'KSKeyedPersistentStore.m:368\']\nKSPersistentTicketStore failed to load tickets. (productID: com.google.Chrome) [com.google.UpdateEngine.CoreErrorDomain:1051 - \'/Library/Google/GoogleSoftwareUpdate/TicketStore/Keystone.ticketstore\'] (KSKeyedPersistentStore store directory does not exist. - \'/Library/Google/GoogleSoftwareUpdate/TicketStore\' [com.google.UpdateEngine.CommonErrorDomain:501])\nksadmin cannot access the ticket store:<KSUpdateError:0x100404060\n\tdomain="com.google.UpdateEngine.CoreErrorDomain"\n\tcode=1051\n\tuserInfo={\n\t\tfunction = "-[KSProductKeyedStore(ProtectedMethods) errorForStoreError:productID:message:timeoutMessage:]";\n\t\tdate = 2018-07-13 03:24:43 +0000;\n\t\tproductids = {(\n\t\t\t"com.google.Chrome"\n\t\t)};\n\t\tfilename = "KSProductKeyedStore.m";\n\t\tline = 102;\n\t\tNSFilePath = "/Library/Google/GoogleSoftwareUpdate/TicketStore/Keystone.ticketstore";\n\t\tNSUnderlyingError = <KSError:0x100515350\n\t\t\tdomain="com.google.UpdateEngine.CommonErrorDomain"\n\t\t\tcode=501\n\t\t\tuserInfo={\n\t\t\t\tdate = 2018-07-13 03:24:43 +0000;\n\t\t\t\tline = 368;\n\t\t\t\tfilename = "KSKeyedPersistentStore.m";\n\t\t\t\tfunction = "-[KSKeyedPersistentStore(PrivateMethods) validateStorePath]";\n\t\t\t\tNSFilePath = "/Library/Google/GoogleSoftwareUpdate/TicketStore";\n\t\t\t\tNSLocalizedDescription = "KSKeyedPersistentStore store directory does not exist.";\n\t\t\t}\n\t\t>;\n\t\tNSLocalizedDescription = "KSPersistentTicketStore failed to load tickets.";\n\t}\n>\n[47537:28675:0713/112447.920274:ERROR:ssl_client_socket_impl.cc(1026)] handshake failed; returned -1, SSL error code 1, net_error -107\n[47537:28675:0713/112448.006779:ERROR:ssl_client_socket_impl.cc(1026)] handshake failed; returned -1, SSL error code 1, net_error -107\n2018-07-13 11:24:52.494 Google Chrome Helper[47600:548065] Couldn\'t set selectedTextBackgroundColor from default ()\n' }



1..1
# tests 1
# pass  0
# skip  0
# fail  1
Testem finished with non-zero exit code. Tests failed.

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

installed Versions: MacOS Sierra 10.12.6 node: 6.12.2 npm: 5.6.0 ember: 2.12.0 ember-cli: 2.18.2 phantomjs: 2.1.1

Below is partial of my tests/index.html file:

<script src="testem.js" integrity=""></script>
<script src="assets/vendor.js"></script>
<script src="assets/test-support.js"></script>
<script src="assets/myApp.js"></script>
<script src="assets/tests.js"></script>

also tried with ember test --server but same error. So anyone has any idea on how to narrow down this and why testem is not loading.




Ember Deploy CLI - not reading .env files

Trying to deploy to an AWS S3 deployment target using the ember-cli-deploy plugin.

Have tested deploying using AWS key and secrets hardcoded in the /config/deploy.js file, which worked fine, so can confirm that it is something to do with my environment file setup.

The files are stored in the root of the directory (as per docs). Have tested .env and target-specific variables such as .env.deploy.develop. These files contain the AWS in the following format:

AWS_KEY​=ABC
AWS_SECRET​=ABC123

Running the deployment process (i.e. ember deploy develop --activate --verbose) with the environment file setup results in the errors detailed in my previous question on the matter.

Fairly sure that there is only need for the .env file, since the AWS keys and secrets are simply referenced in the deploy.js file in the following manner (w/o any target conditions):

let credsConfig = {
  accessKeyId: process.env.AWS_KEY,
  secretAccessKey: process.env.AWS_SECRET,
};

Any clues as to what's going on here would be much appreciated!




ember redirect mirage requests to another route in imported module

my ember app has an adapter which generates below URL when I query for all employee models:

/proxy/v1/employees/details (namespace i have defined is /proxy/v1)

I am importing one node module which is an another ember app that has a route defined in mirage as: /employee/details

Is there a way my main app can call this route? Currently mirage throws me an error saying that route: /proxy/v1/employees/details is not defined.




Ember Simple Auth: 'authorize' is deprecated. [deprecation id: ember-simple-auth.session.authorize]

In fact, I get two warnings. I'll describe the script in order.

At the time of authorization (GraphQL mutation), I don't receive a warning. Requests to receive anything (for example, a list of posts) without authorization - also without warning. But when I successfully logged in, all requests are accompanied by two warnings:

The first:

DEPRECATION: Ember Simple Auth: 'authorize' is deprecated. [deprecation id: ember-simple-auth.session.authorize] See https://github.com/simplabs/ember-simple-auth#authorizers for more details.

And the second:

DEPRECATION: Ember Simple Auth: Authorizers are deprecated in favour of setting headers directly. [deprecation id: ember-simple-auth.baseAuthorizer] See https://github.com/simplabs/ember-simple-auth#deprecation-of-authorizers for more details.

I collected all my code from their repository.

app/authorizers/custom.js:

import Base from 'ember-simple-auth/authorizers/base'
import { inject as service } from '@ember/service'

export default Base.extend({
  session: service(),

  authorize(sessionData, block) {
    const { email, token } = sessionData
    block('X-User-Email', email)
    block('X-User-Token', token)
  }
})

Part of the code from app/authenticators/custom.js file:

restore(data) {
  return new RSVP.Promise((resolve, reject) => {
    if (!isEmpty(data.token)) {
      resolve(data)
    } else {
      reject()
    }
  })
},

Authorization works. The server receives data in each request.

But these warnings do not allow me to live normally. They appear only in development mode. In the production application (from dist) there are none.




need to avoid the icon for the parent element

I'm creating the download icon for the all items in the project, Ihave tried the below code:

DownloadItem: Ember.ContainerView.extend(childMOMixin, {
                classNames: ['download-icon'],
                classNameBindings: [ 'clickable' ],
                childViews: [
                Core.view.Icon.extend({
                model: 'download',
                size: 20
                }),
                ],
            }).named("ManagedObjectDownloadItem"),

Download Icon is fetching from the model attribute. because of that I'm occuring download icon main parent folder Icon and also the sub-folder item icon. I need on only the place of sub-folder items. Can anyone please guide me on this. I'm using Ember 1.4.0 version. Thanks in advance




mercredi 11 juillet 2018

Ember handlebars template access deep object property

In my Ember app, I have the following code

Component JS

row = {};
Ember.set(row[my.constants.fieldKey], "cssType", 'leftPadding')

Component HBS



So I want to pass 'cssType' property of my-field as 'leftPadding' in my component.

The hbs code above does not work.

Essentially I am trying to access a deep/nested object property in my hbs template I even tried with lookup, but did not work. Please suggest.




Ember: Model's property changes not detected in computed property

I have 2 models.

models/calendar.js

export default Model.extend({
  holidays: hasMany('holiday'),
  date: attr(),
  occasion: attr()
})

models/holiday.js

export default Model.extend({
  calendar: belongsTo('calendar')
})

And a component.

holidays/component.js

export default Component.extend({
  init() {
    this._super(...arguments);
    this.store.findAll('calendar')
      .then(calendar => this.set('calendar', calendar));
  },

  calendarIsDirty: computed('calendar.holidays.@each.{date,occasion}', function () {
    // This is not executed
  })
})

holidays/template.hbs


  
  



  <button>Save</button>


I'm displaying the holidays in the UI and when the user edits the date or occasion of the holiday, I want to do something. But the computed property that listens to these changes is not executed at all. Kindly help me with this.

I have an 'Add Holiday' button that adds an empty holiday that the user can edit. When I add a holiday, that computed property is executed. Only when I make changes to an existing holiday, the computed property is not executed.




EmberError could not find template or view

We have an EmberJS application and the below runtime error occurs around startup time each time I attempt to run the app. This is a problem that is only window specific. Mac works perfectly fine. I believe vendor.js contains many of our 3rd party libraries our app depends upon. Where can I start to debug this problem? One suggested a potential problem maybe with web pack? Is this the right place to start? I'm new here to this project and as far as I know no one at the company has ever developed using a windows environment. I suspect there are many mac specific items that are in place. Just not exactly sure where to begin with this. Any hints would be great. Thanks

 EmberError description : undefined fileName : undefined lineNumber :
 undefined message : "Assertion Failed: Could not find "svg.iconCharts" template or view." name : "Error" number : undefined stack : 
"Error: Assertion Failed: Could not find "svg.iconCharts" template or view.↵  
 at new EmberError (https://localhost:3000/vendor.js:39962:23)↵    at
 Object.Ember.assert (https://localhost:3000/vendor.js:29576:15)↵    at
 Class.render (https://localhost:3000/vendor.js:51100:17)↵    at
 Class.renderTemplate (https://localhost:3000/main.js:63561:18)↵    at
 apply (https://localhost:3000/vendor.js:45385:27)↵    at
 Class.superWrapper [as renderTemplate]
 (https://localhost:3000/vendor.js:44956:15)↵    at Class.setup
 (https://localhost:3000/vendor.js:50366:16)↵    at applyHook
 (https://localhost:3000/vendor.js:72695:30)↵    at callHook
 (https://localhost:3000/vendor.js:72689:14)↵    at
 handlerEnteredOrUpdated (https://localhost:3000/vendor.js:71449:7)"
    __proto__ : Error
    reportError @   errors.js:6
    error   @   base.js:71
    triggerEvent    @   ember.debug.js:26351
    trigger @   ember.debug.js:46873
    trigger @   ember.debug.js:46718
    finalizeTransition  @   ember.debug.js:45907
    (anonymous) @   ember.debug.js:45309
    tryCatch    @   ember.debug.js:47307
    invokeCallback  @   ember.debug.js:47319
    publish @   ember.debug.js:47290
    (anonymous) @   ember.debug.js:29435
    invoke  @   ember.debug.js:679
    flush   @   ember.debug.js:749
    end @   ember.debug.js:135
    (anonymous) @   ember.debug.js:521
    setTimeout (async)      
    createAutorun   @   ember.debug.js:519
    defer   @   ember.debug.js:219
    run.schedule    @   ember.debug.js:18411
    raf @   fastdom.js:67
    scheduleFlush   @   fastdom.js:197
    measure @   fastdom.js:98
    (anonymous) @   eq.js:376
    load (async)        
    addEvent    @   eq.js:38
    (anonymous) @   eq.js:375
    fn  @   bootstrap:98
    ./app/scripts/dependencies.js   @   wizard.js:204
    __webpack_require__ @   bootstrap:721
    fn  @   bootstrap:98
    ./app/scripts/app.js    @   ajax.js:90
    __webpack_require__ @   bootstrap:721
    fn  @   bootstrap:98
    1   @   main.js:123381
    __webpack_require__ @   bootstrap:721
    ./app/fonts/MaterialIcons-Regular.eot.module.exports    @   bootstrap:788
    (anonymous) @   bootstrap:788




Ember AWS deploy failing - CredentialsError & EHOSTUNREACH

Having trouble getting the ember-cli-deploy addon to deploy successfully to our AWS development environment.

The pipeline seems to fail resulting in one of two errors:

...
- build ok
|
+- didBuild
|
+- willPrepare
|
+- prepare
|  |
|  +- revision-data
- creating revision data using `version-commit`
- generated revision data for revision: `0.1.9+4a4f79a3`
|
+- didPrepare
|
+- fetchInitialRevisions
|  |
|  +- s3-index
|
+- didFail
CredentialsError: Missing credentials in config
CredentialsError: Missing credentials in config
    at ClientRequest.<anonymous> (/Users/certus/Desktop/branz-web/node_modules/aws-sdk/lib/http/node.js:83:34)
    at Object.onceWrapper (events.js:293:19)
    at emitNone (events.js:86:13)
    at ClientRequest.emit (events.js:188:7)
    at Socket.emitTimeout (_http_client.js:679:10)
    at Object.onceWrapper (events.js:293:19)
    at emitNone (events.js:86:13)
    at Socket.emit (events.js:188:7)
    at Socket._onTimeout (net.js:352:8)
|
Pipeline aborted

Or:

...
- build ok
|
+- didBuild
|
+- willPrepare
|
+- prepare
|  |
|  +- revision-data
- creating revision data using `version-commit`
- generated revision data for revision: `0.1.9+4a4f79a3`
|
+- didPrepare
|
+- fetchInitialRevisions
|  |
|  +- s3-index
events.js:163
      throw er; // Unhandled 'error' event
      ^

Error: connect EHOSTUNREACH 169.254.169.254:80 - Local (192.168.20.110:64572)
    at Object.exports._errnoException (util.js:1050:11)
    at exports._exceptionWithHostPort (util.js:1073:20)
    at internalConnect (net.js:889:16)
    at lookupAndConnect (net.js:977:5)
    at Socket.realConnect (net.js:945:5)
    at Agent.connect [as createConnection] (net.js:77:22)
    at Agent.createSocket (_http_agent.js:195:26)
    at Agent.addRequest (_http_agent.js:157:10)
    at new ClientRequest (_http_client.js:212:16)
    at Object.request (http.js:26:10)

The AWS keys are stored, as per the ember-cli-deploy docs, in a file at the root of the project called .env.deploy.develop containing the AWS key and secrets:

AWS_KEY​=ABC..
AWS_SECRET​=ABC…

I am confident that there is nothing wrong with the build setup, as it was used extensively before me, however, what else could be going wrong on my end assuming the key and secret are correct?

I have read elsewhere that memory available could play a factor; accordingly, I closed down most of the apps running before attempting to deploy. Have also cleared node_modules and cleared the npm cache before reinstalling. However, to no avail.

Any suggestions would be most welcome.

  • npm - v4.2.0
  • node - v7.10.1
  • ember-cli - v2.13.0
  • ember-cli-deploy - v1.0.2



How can I hang the "active" class only on the current route?

I have such routes:

this.route('posts', function() {
  this.route('index', { path: '/' })
  this.route('show', { path: '/:post_path' }, function() {
    this.route('people', { path: '/people' })

    this.route('files', function() {
      this.route('images', { path: '/images' })
      this.route('videos', { path: '/videos' })
    })
  })
}),

I have a problem with the class "active".

Take, for example, this link:

http://localhost:4200/posts/1-best-post/files/images

In this case, the class "active" will hang on two links - on posts.show.files.images and on posts.show.

How to make the class "active" only for posts.show.files.images?




Ember.js computed: Shortest way to return single object from array

Given an array of objects with ids:

array: [
    {id: 3, value: 'foo'},
    {id: 6, value: 'bar'},
    {id: 9, value: 'baz'},
    // ...
],

What is the shortest way to return a single object from the array that matches an id? Keep in mind that the array can be undefined while the model is loading. In that case, the computed property should also return undefined.

This works:

_test       : computed.filterBy('array', 'id', 6),
test        : computed.alias('_test.firstObject')

But it is not pretty, using a temporary variable.

This is better:

test        : computed('array.[]', function() {
    let array = this.get('array')
    if (array) return array.find(el => el.id == 6)
})

But it is not pretty, because it uses 4 lines.

Ember contains a lot of syntactic sugar, but I haven't figured out how to shrink this.




Ember.js: Move controller computed properties from multiple models into a new model

Given a model substances containing an attribute measurements which is an array with objects. Every object is a measurement with some attributes like (int) value. Second model elements is a collection containing global data for all specific elements, such as average values.

I want every measurement to contain the respective element as an attribute, so I can pass it to components. E.g.:


    
    
    


I'm doing a single findAll(elements, {limit: 300}) once, so that every substance doesn't do dozens of requests to the jsonapi server.

I tried combining the two in model:substance, but model:elements is not available there (for obvious reasons). So I am doing this in the page controller like so:

export default Controller.extend({
    substance       : computed.alias('model.substance'),
    measurements    : computed.alias('substance.measurements'),
    elements        : computed.alias('model.elements'),
    contents        : computed('{elements,measurements}.[]', function() {
        if (!this.get('elements')) return null
        if (!this.get('measurements')) return null
        return this.get('measurements').map(m => {
            const element = this.get('elements').find(detail => detail.id == m.id)
            if (element) set(m, 'element', element)
            return m
        })
    }),

    // More calculations w/ `utils` here based on `contents`

This works, but there are some problems. First (1), the contents:computed fires 3 times.

  1. When it is referenced is the template;
  2. when model.substance is loaded;
  3. when model.elements is loaded.

Not a big problem because the first two times, it will return null.

Second (2), all references to a specific measurement in the template (e.g.: ) will literally display undefined until everything is calculated in the 3rd iteration. I would like it to display nothing ('') until it is loaded.

However, my final goal is to be able to pass substance (with the combined measurements + elements) to a shopping-cart-like service so you can compose your own list of substances, after which it can make calculations and show a summary, independent.

How do I move these controller:substance computations to a self-contained item (model?) that can be passed around to services (3), given that I cannot do this inside model:substance?

I cannot reference the controller:substance from a service, because controllers are singeltons.




mardi 10 juillet 2018

How to apply style to descendent div based on ancestor div?

Assuming the html structure below I need to override a style in the app-dropdown__trigger__icon class based on the existence of an ancestor with class ancestor-module. I'm using ember so the app-dropdown__trigger__icon and the ancestor-module live in separate modules i.e. I cannot easily reference the ancestor from the child's scss. Is there a way to achieve conditional styling based on an ancestor's class?

<td id="ember1249" class="lt-cell align-center ember-view">
  <div id="ember1254" class="ember-view">
    <div class="ancestor-module">
      <div id="ember1259" class="ember-view">
        <div id="ember1264" class="__app-dropdown__aa494 ember-view">
          <div id="ember1274" aria-owns="ember-basic-dropdown-content-ember1269" tabindex="0" data-ebd-id="ember1269-trigger" role="button" class="app-dropdown__trigger ember-basic-dropdown-trigger ember-view">
            <span class="app-dropdown__trigger__icon">
                                                <i id="ember1275" aria-hidden="true" class="fa fa-house ember-view"></i>
                                        </span>
          </div>
          <div id="ember-basic-dropdown-content-ember1269" class="ember-basic-dropdown-content-placeholder" style="display: none;"></div>
        </div>
      </div>
    </div>
  </div>
</td>



Emberjs view not updating on new record creation?

I have route which uses ember hash to load multiple models like

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

export default Route.extend({
    model(params) {
        return Ember.RSVP.hash({
            contest: this.store.query('contest',{match: params.matchId}),
            match: this.store.findRecord('match', params.matchId)
        })
    }
});

and i create a new instance of contest in controller using the following code

    newContest() {
         this.store
            .createRecord('contest', {
                name: this.get('contestName'),
                fee: this.get('contestFee'),
                winning: this.get('contestWinning'),
                capacity: this.get('contestCapacity'),
                match: this.get('model').match.get('id')
            })
            .save();
    }

The problem being that it is not reflected in template which i am rendering as follows

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

where am i going wrong with this ?