vendredi 31 août 2018

Ember loading state blocks location.href history updating

When some.route is waiting for slow-model, you can have a some.route-loading loading state to show some kitties while waiting.

In this case it makes sense to have some.route-error too, so you can show a sad face when the payload breaks things.

However, when I click on a link-to to some/route, the location href in the address bar is not updated until the loading completes successfully.

I don't know if this is by design, but I would like to be able to navigate back with the browser history on error.

In other words: Can I have the location href in the address bar update before rather than after the loading state appears?




How to push data to ember's store of a model that have a JSONSerializer as it's Serializer insted of JSONAPISerializer or RESTSerializer in Ember js?

For a model which is using JSONAPISerializer as it's Serializer pushing a record for that model into the store is done by store.push(dataInJSONAPISerializerFormat) https://www.emberjs.com/api/ember-data/3.3/classes/DS.Store/methods/push?anchor=push method.But for the model which is using RESTSerializer as it's Serializer pushing a record for that model into the store is done by store.pushPayload("modelName",dataInRESTSerializerFormat) https://www.emberjs.com/api/ember-data/3.3/classes/DS.Store/methods/pushPayload?anchor=pushPayload method. But incase of JSONSerializer both of them are not working? Can anyone Help me?




jeudi 30 août 2018

how to clone an ember object

I am creating an object like:

let response = Ember.object.create({
               propertyOne: value1
              });

I am using it in the end, and set it as one of the property of model like this:

let userRecord = this.get('store').createRecord('user');
userRecord.set('prop', response.propertyOne);

Now when I do model.save then in my adapter, I am overriding createRecord method where I convert any camelcase property to snake case before sending it on wire. If it fails, then I will retry but the problem is next time I retry, the created object gets modified. I guess it is because i am passing the object and setting on the model as a reference. is there a way to duplicate the ember object so that this can be avoided?




Ember-cli addon dev, how to differentiate addon dev from application dev

When you create an ember-cli addon, you are supposed to be able to run a dummy app.

If a component need to access it's vendor folder you access "public/" in production. While developping the ember app that use the addon you access :

app.options.project.nodeModulesPath + "/"+ this.name+"/vendor/"

However, when you run the ember-cli addon server (the dummy app) you need only "vendor/".

this.getEnv() will return developpement while developping an addon, or an app using the addon.

How can I, in index.js, differentiate app dev from addon dev ?




Ember.js application to upload file and process it on the server and making available for download

I'm building an application that could upload file to server where it is processed and it is available for download. I've implemented the same using JSP, servlets, etc. Now I'm planning to develop this using ember.js. Is there a way that I could use those previous servlet codes in my ember application? and if its not a good practice, which technology should I use to perform file processing tasks in server with ember as client-side?




Ember Snapshot doesnt resolve belongsToRelationships

Im using ember 2.18 and i was trying to access nested api. when im trying to access that i override buildUrl in adapter. i have two models programme and course which has a one to many relationship of programme has many courses

issue im getting here is im trying to access belongsTo model's id which is programme id from course but it is not there.

programme model

export default DS.Model.extend( {

  name:            DS.attr( 'string' ),
  code:            DS.attr( 'string' ),
  welcome:         DS.attr( 'string' ),
  startDate:       DS.attr( 'date' ),
  endDate:         DS.attr( 'date' ),
  published:       DS.attr( 'boolean' ),

  core_group:      DS.attr(),

  courses: DS.hasMany( 'course',{async: true}) });

course model

export default DS.Model.extend( {

  uid: DS.attr( 'string' ),
  name: DS.attr( 'string' ),
  abbreviation: DS.attr( 'string' ),
  startDate: DS.attr( 'date' ),
  endDate: DS.attr( 'date' ),
  country: DS.attr( 'string' ),
  timezone: DS.attr( 'string' ),
  published: DS.attr( 'boolean' ),

  programme: DS.belongsTo( 'programme', { async: true} )
});

adapter/mixin

import Ember from 'ember';

export default Ember.Mixin.create( {
  findRecord: function( store, type, id, snapshot ) {

    return this.ajax( this.buildURL( type.modelName, null, snapshot, 'findRecord' ), 'GET' );
  },

  buildURL: function( modelName, id, snapshot, requestType, query ) {

    var local_snapshot = snapshot;
    var url          = this._super( modelName, id, snapshot, requestType, query ),
        ancestorType = this.get( 'ancestorType' ),
        namespace    = this.get( 'namespace' ),
        ancestor,
        ancestorComponent,
        position;

    console.log(local_snapshot)
    // make a big assumption here, that requests will only be for a given parent,
    // not disparate parents
    if ( local_snapshot instanceof Array ) ancestor = local_snapshot[ 0 ].get( `${ancestorType}.id` );
    else ancestor = local_snapshot.get( `${ancestorType}.id` );

    position          = url.indexOf( namespace + '/' ) + namespace.length;
    ancestorComponent = '/' + Ember.String.pluralize( ancestorType );

    if ( ancestor ) ancestorComponent = ancestorComponent + `/${ancestor}`;

    url = [ url.slice( 0, position ), ancestorComponent, url.slice( position ) ].join( '' );

    return url;
  }


});

adapter/course

import ApplicationAdapter from '../adapters/application';
import NestedMixin from '../adapters/mixins/nested';


export default ApplicationAdapter.extend(NestedMixin, {
  ancestorType: 'programme'
} );

error im getting is

local_snapshot.get is not a function

when i look into model belongsToRelationships are empty means that it is not loaded correctly




Ember Application controller to share data

In an Ember engine app, can an Application Controller be used to share data between

  1. Say parent app & child engine
  2. Between 2 child engines

So one of them would set the data/attribute on the Application Controller & other would access/get it from the Application Controller

Can that be done easily or is it better to use Services.




mercredi 29 août 2018

Update a saved property without refreshing the page

Apologies for this basic question. I feel like I’m misunderstanding some core Ember concept and would appreciate clarification.

In one route, I’m updating a property on an Ember data model when a user selects an option from a dropdown and clicks ‘save’. It’s saving properly. I’ve logged the property, and when it’s done saving, the correct value prints.

In another route, I'm accessing that same model in a component template. I’m just printing it, like so: <div></div>

Because I’m referencing a specific model property from within a template, I expect that the DOM will update with the new property value, without refreshing the page. This is not the case - it only updates after refresh.

In an effort to bypass this, I tried making a computed property, even though I’m fairly sure I shouldn’t have to do that:

  userName: computed('user.name', function() {
    return this.get('user.name');
  })

And then I tried to access the computed property in the template like: <div></div>

Nope.

Obviously I’ve made some grave miscalculation. Can anyone explain expected behavior here (and let me know how I can have this property update without refreshing)? Thanks.




I use an old bootstrap theme in my ember app, how can I update it? How does ember plugin works?

I use this in my ember app : https://github.com/huxinghai1988/ember-adminlte-theme

But recently, it prevent me from building my app because of old dependencies. I forked it to try to repare it.

I tried the following to install it :

npm install bower install

The installation seems to be ok

WHen I try to run the server, here is the error message :

Error: Attempting to watch missing directory: /home/sylvain/dev/ember-adminlte-theme/node_modules/ember-adminlte-theme/vendor/
    at Watcher_addWatchDir [as addWatchDir] (/home/sylvain/dev/ember-adminlte-theme/node_modules/broccoli-sane-watcher/index.js:90:11)
    at /home/sylvain/dev/ember-adminlte-theme/node_modules/broccoli/lib/builder.js:94:35
    at tryCatch (/home/sylvain/dev/ember-adminlte-theme/node_modules/rsvp/dist/rsvp.js:525:12)
    at invokeCallback (/home/sylvain/dev/ember-adminlte-theme/node_modules/rsvp/dist/rsvp.js:538:13)
    at /home/sylvain/dev/ember-adminlte-theme/node_modules/rsvp/dist/rsvp.js:606:14
    at flush (/home/sylvain/dev/ember-adminlte-theme/node_modules/rsvp/dist/rsvp.js:2415:5)
    at process._tickCallback (internal/process/next_tick.js:61:11)

Like if he was looking for itself installed as a dependency.

How do I run the test on what seems to be an ember plugin that cannot be run alone?

How do I procede to migrate module from bower and then upgrade them?




How to pass properties from One controller to another in ember without involving model's setupController?

How to pass properties from One controller to another in ember without involving model's setupController




How to listen for eslint errors in ember dev server?

I want to stop the local dev server in development in case of any eslint errors found. Is there any solution for this case? Please help me if there any there any solution.




Which Serializer or Adapter is best to work with in ember js?

Can somebody explain with example about how to work with JSONSerializer ,RESTSerializer and JSONAPISerializer ? I'm having a hard time working with different types of Serializer and adaptor but I know the basics of Serializer(To convert the payload from/to backend to/from store as it's convenience) and Adapter(To specify the backend url and namespace and headers)




mardi 28 août 2018

Ember: Cannot call writeWatching after the object is destroyed

Encountering the following error occurs when a user logs out and then uses the browser back button to return to a previous page:

Error: Assertion Failed: Cannot call writeWatching after the object is destroyed.

I'm unable to isolate the issue to a point where it is reproducible outside of its current context, a problem other developers (i.e. here and here) on Ember's GitHub repo have reported with regards to reproducibility.

From the call stack trace I conducted, I can say that the error is executed by the following Ember function:

  setDebugFunction('assert', function assert(desc, test) {
    if (!test) {
      throw new _emberDebugError.default('Assertion Failed: ' + desc);
    }

And that the call stack begins at this Ember function:

onUpdateURL: function (callback) {
      var _this = this;

      this._removeEventListener();

      this._popstateHandler = function () {
        // Ignore initial page load popstate event in Chrome
        if (!popstateFired) {
          popstateFired = true;
          if (_this.getURL() === _this._previousURL) {
            return;
          }
        }
        callback(_this.getURL());
      };

      window.addEventListener('popstate', this._popstateHandler);
    }, 

However, I'm at a complete loss as to why this is occurring. Any insight would be much appreciated




Why does my record have all nil fields after being saved?

I am making an ember and rails app.

I am trying to do a post request to http://localhost:3000/candidates

My request is getting a 200 and is creating a record but everything is nil: Why is this?

#<Candidate id: 15, name: nil, email: nil, created_at: "2018-08-23 22:28:07", updated_at: "2018-08-23 22:28:07"> 

here is my controller code:

class CandidatesController < ApplicationController
  # POST /candidates
  # def create
  #   @candidate = Candidate.create!(candidate_params)
  #   json_response(@candidate, :created)
  # end

  def create
    puts "create"
    puts params
    puts candidate_params
    candidate = Candidate.create!(candidate_params)

    if candidate.save
      render jsonapi: candidate
    else
      render jsonapi_errors: candidate.errors
    end
  end

  private

  def candidate_params
    # whitelist params
    params.permit(:name, :email)
  end
end

and here is my ember code:

import Ember from "ember";

export default Ember.Route.extend({
  model() {
    // return this.get("store").findAll("candidate");
  },
  actions: {
    createCandidate() {
      console.log("create candidate");
      let candidate = this.get("store").createRecord("candidate", {
        id: 1,
        name: "Katie",
        email: "katie@gmail.com"
      });
      candidate.save();
    }
  }
});

I am also getting this error in my js console: SyntaxError: Unexpected end of JSON input

I am using the 'jsonapi-rails' gem

Thanks, Kato




Inject Relationships into Ember Payload

i have a component that shows and creates comments to say a post, this component has a form for create the new comments and send them via POST to the backend, the normal payload would be:

{data: {
    attributes: {
        created_at: "foo",
        autor: "foo",
        text: "foo"
    },
    relationships: {
        post: {
            data: { type: "posts", "id": 1234 },
            id: "1234",
            type: "loans"
            }
     }
     type: "comment"
     }
}

The problem comes when you need to use the component in another view and more important when the name of the model is different, to say posts_breakdown, in this case the payload would be:

{data: {
    attributes: {
        created_at: "foo",
        autor: "foo",
        text: "foo"
        },
    relationships: {
        post: {
            data: null
            }
        }
     type: "comment"
    }
}

Clearly, in comments there is no relation posts_breakdown, the first thing that I tried to add this relation to the model with "posts_breakdown: belongsTo (posts_breakdown)" the problem is, that the backend cann't recognize it and is not possible to modify it. The backend, is taking the values on the relationships to relate the comment with the post (post_id field into comment table)

My question: There is some way to "trick" the backend and / or modify the payload, so think that the post_breakdown model is post?

Below is a representation of how I have the defined models:

comment.js:
    export default DS.Model.extend ({
        author: DS.attr (),
        text: DS.attr (),
        created_at: DS.attr (),
        post: DS.belongsTo ('post'),
        posts_breakdown: DS.belongsTo ('posts_breakdown'),
    });

posts.js:
    export default DS.Model.extend ({
        text: DS.attr (),
        created_at: DS.attr (),
        author: DS.attr (),
        comments: DS.hasMany ('comments'),
    });

post_breakdown.js
    export default DS.Model.extend ({
        most_commented_post: DS.attr (),
        last_commented_post: DS.attr (),
        frequent_users: DS.attr (),
        comments: DS.hasMany ('comments'),
    });




`checked` attribute on radio button input does not exist

When trying to create an radio button input and setting the checked attribute, the checked attribute never appears. Interestingly, the CSS for :checked state elements works as does VoiceOver read out for the selected radio button at the time.

Here's an Ember twiddle that displays this issue:

https://ember-twiddle.com/1c3c6686c49a0c8338e24acc66b05a26

You'll see that the checked attribute never appears on the selected radio button, but both the DOM element and CSS display as checked or selected.

Does anyone know what might be causing this apparent conflict?




How to pass Array Of Objects from One route to Another Route in EmberJS (Without using query params)

As I am new to ember i don't know how to pass an Array of Objects from one route to another route in ember? (without using query params).Do i need a SessionStorage?




lundi 27 août 2018

What is the difference between application initializer and a service in ember?

As I am new to ember, I got confused between the application initializer and a service. To my knowledge, both of them was doing the same job and both have the lifetime of the application. Could anyone please explain the difference between them with a clear example?




Adding a dynamic variable to an Ember adapter?

have a EmberJS problem I've been struggling with I'm hoping someone can shed some light on.

I have an application that has 2 principal root paths - one for tenants and one for internal admins.

I'm setting up separate adapters in Ember to handle different namespacing, pathing. The problem is, the principal tenant route includes an id for the tenant before branching into specific resources, so I'd like that id to be included in the path for the adapter, but no matter how I try, I can't seem to get Ember to recognize the id when I define it in the adapter.

The internal admin adapter doesn't have this problem, as the path prior to the resource branching is static.

This is the adapter I have:

import Ember from 'ember';
import { pluralize } from 'ember-inflector';
import { underscore } from 'ember-string';
import config from 'config/environment';
import DS from 'ember-data';
import ENV from 'config/environment';



export default DS.JSONAPIAdapter.extend({
  auth: Ember.inject.service('auth'),

  headers: Ember.computed('auth.authToken', function() {
    return {
      "Authorization": `Bearer ${this.get("auth").getAuthToken('user')}`,
    };
  }), 

  host: config.apiHost,
  namespace: ENV.version,

  pathForType: function(type) {
    var underscored = underscore(type);
    return pluralize(underscored);
  },

});

What I'd like to have there is more like:

ENV.version + '/tenant/' + :tenant_id + '/',

But I can't seem to get that to work. I have a service I can grab the tenant id from: app_root/services/auth.js. It looks something like:

import Ember from 'ember';

export default Ember.Service.extend({
    getTenantId(){
        return '1234';
    },
});

Am I allowed to import the service into the adapter? I tried creating a function in the adapter that would call this service and return the value from it but it fails every time. I also tried importing the service but that failed as well. I'm wondering is it even possible to add a dynamic segment in an Ember adapter? If so, how to make it work?

Thanks in advance,




Error: Can't set headers after they are sent Ember/Nodejs

I am trying to fetch data from an API, if you see the console ,you will find that a huge chunk of JSON that is variable a2 is displayed in the console .

But I wish to do res.json(a2); to display all the json on the webpage as JSON data.

I am getting an error--

Error: Can't set headers after they are sent.

What do I do >

var express= require('express');
var app=express();
const port= 5000;

var gotit=[];
var Request = require("request");
Request.post({
    "headers": {
        "content-type": "application/json",
        "Authorization": "34ca0e9b-ecdd-4736-a432-d87760ae0926"
    },
    "url": "https://www.lifeguard.insure/v1/quote",
    "body": JSON.stringify({
        "category": "Auto",
        "zipcode": "90293",
        "age": 35,
        "gender": "Male",
        "key": "a2bf34ab-8509-4aa6-aa9e-13ae7917e1b8"
    })
}, (error, response, body) => {
    if (error) {
        return console.dir(error);
    }
    var a2 = (JSON.parse(body));
    console.log(a2)
    gotit=a2;
});

console.log("Gotiit")
console.log(gotit);

    app.get('/api/customers', (req, res) => {
    res.json(gotit);
    });


app.listen(port, () => console.log("Server Started"));




ember save call not going to success block

I am using ember save call on model to persist and invoke my REST call.

_model.save().then(() =>{
   console.log("success");
 }, (error) {
    console.log("error");
 });

My REST api returned 202 response (as seen on network tab) and on console I always see "Error" getting printed. Is there anything in ember which treats 202 as an error? if yes, how can it be fixed?




how to do model hook of Ember in React?

In Ember when you do route transition there is a model hook for you to retrieve data for this route/page. how to achieve this in React? thanks.




How to exclude a component in ember build

Short Explanation:

How to exclude all component.hbs, component.hbs.js and this.route('component) mention in router.js related to a component while ember build.

Long Explanation:

Think that you have a component in your ember app which you want to be available only in the development environment (lets not worry about how good this approach is, for now!!) and must be removed while building for production.

I have tried a few ember-cli plugins (broccoli-funnel, ember-cli-funnel) which excludes component.hbs.js file but I can still see the references to the component.hbs and this.route('component') in the compiled JS file in /dist folder.




How to convert image to base64 code using ember and RESTful api

I have an ember app to list the details about alumni using django rest framework and postgreSQL. I need to upload image(stored in the my storage) along with other details. How can I achieve this in ember?

My model is:

import DS from 'ember-data';

const {
  attr,
  Model
} = DS;

export default Model.extend({
  firstName: attr('string'),
  lastName: attr('string'),
  image: attr('string'),
});

Can I do it by converting to base64 from ember and storing the encoded string? If possible, how?




Simple `yield` in Ember.js

I'm reading this article about lessons a developer has learned over the years of working with Ember.js

There's one point here that I'm curious about:

Don’t . Think carefully about how to yield as little as possible.


I understand technically what he's saying, but what's the reasoning behind it? Is there a performance problem with being able to access the whole this?




Ember.Logger.log is deprecated and console.info gives 'no-console' build warnings, what to do?

I'm relatively new to Ember development, but keen to do things the right way.

For logging, I used to use Ember.Logger.log('blah'); but that now throws warnings in the console that it's deprecated. There's a link in the warning to https://emberjs.com/deprecations/v3.x#toc_use-console-rather-than-ember-logger, which recommends using console instead.

So I switch to console.info('blah');, but now when I do ember serve there's a bunch of "problems" like:

/Users/mick/Projects/Pop Up Eats/Vendor Website/app/routes/application.js
  22:3  error  Unexpected console statement  no-console
  27:3  error  Unexpected console statement  no-console

✖ 2 problems (2 errors, 0 warnings)

What am I supposed to do? Am I missing something?




vendredi 24 août 2018

ember member actions normalizing response

I am using ember member API actions and was wondering how can response be normalized in such cases.

I have a model "users" with member action "postAddress". It is a post request which returns me a response. Now the problem I am facing is data is not normalized as returned data does not map to any store model. I know when we do a findAll and give a model, then ember automatically normalizes the data returned from API call. But in case of member actions, can anyone suggest how can data be normalized? (snake case to camel case).




@import not working in addon with ember-cli-sass

Addon has

// app/styles/my-addon.scss within addon
@import 'pods';
.testing123 .my-addon {
  color: white
}

// app/styles/pods.scss within addon
// @import 'some components go here';
.testing123 .pods {
  color: black
}

This works in the addon's dummy app. However when I build it into a real app:

// app/styles/app.scss
@import 'my-addon';

Now my app css contains

.testing123 .my-addon {
  color: white
}
// expect to see .texting123 .pods _but don't_

ember-cli-sass ^7.2.0 and ember-cli-sass-pods ^1.3.0 are both in addon's dependencies.

What am I doing wrong?




Ember-Drag-Sort: Custom HTML element

is it possible to specify a custom element tag for the .dragList ? In my scenario right now I need it to be a <ul> as I'm rendering my items wrapped inside of <li> - trying to avoid having to create a fork.

something like this...

    = drag-sort-list [
      tagName="ul"
      childTagName="li"
      class="someClass"
    ]

and instead of default rendering a for the list we could render the tagName passed in - would also be nice to be able to pass down a custom class for the parent list as well




Ember-Drag-Sort: Usage of "handle" selector results in dragEnd params being passed undefined

Whenever I assign a class selector to the "handle" selector and drag, all the params being passed to the DragEndAction are undefined my code below

    = drag-sort-list [
                items=sortedSections
                group='sections'
                dragEndAction=(action 'dragEnd')
                handle=".drag-handle"
            ] as | item |

handle code :

        i.material-icons.drag-handle draggable="true"
          | drag_indicator

which results in this error: console_error *note I am using emblem template syntax

for additional context, heres what my dragEnd action looks like:

        dragEnd({ sourceList, sourceIndex, targetList, targetIndex }) {
          console.log(sourceList, sourceIndex, targetList, targetIndex);
          if (sourceList === targetList && sourceIndex === targetIndex) return;

          const item = sourceList.objectAt(sourceIndex)
          sourceList.removeAt(sourceIndex); 
          targetList.insertAt(targetIndex, item)

everything works when i take the handle selector off, unsure whats going on.




jeudi 23 août 2018

Hiding deleted records from templates

I am trying to figure out if there's a better way to hide deleted records from a template. My ember app is listening to a web socket and if another user deletes a record, there's a handler that removes that record from the store:

_handleDelete({id, type: modelName}) {
  const record = get(this, 'store').peekRecord(modelName, id);

  if (record) {
    get(this, 'store').deleteRecord(record);
  }
}

What I'm currently doing is defining a computed property that filters out any records where isDeleted is true, and using that for other collections:

allItems: computed.filter('items.@each.isDeleted', function(item) {
  return !get(item, 'isDeleted');
}),

Then I'm using this computed property to build other computed properties:

materialCosts: computed.filterBy('allItems', 'proposalCostType', 'material'),

This works fine, but the issue I'm having is that I didn't start with this, so many of my templates are referencing the hasMany relationship directly (items), rather than the filtered collection (allItems). It's a huge app so I'd have to update a TON of templates to get this working, and I don't think that's time efficient.

I never want a deleted record to ever display in the template, so ideally I'd be able to do something where the items relationship automatically filters out deleted records and is updated when they are removed.

I'm on Ember Data 2.14 so maybe there's a newer version that can do this?




Log to terminal when QUnit test suite completes?

When my test suite completes, I need to output some stats, i. e. meta info about tests collected during test execution.

I'm trying this:

QUnit.done(() => console.log("some meta info here"))

This works when I run tests in the browser.

But when I run tests in the terminal, the console.log output is not displayed.

There's probably some debug flag, but it will enable all console.log messages and pollute the output greatly.

Instead, I need to output one specific message to the terminal, so that it's logged to CI.

PS console.log messages sent during test execution seem to make it into the terminal successfully.

PPS Using QUnit in an Ember CLI app, against Chrome headless.




mercredi 22 août 2018

What is the equivalent of Vuex/Redux in EmberJS?

I am trying to understand why a flux architecture is required for react with redux and vue with vuex but not ember.




Object.assign() in add-on in Ember app causes problems in IE11

I have an Ember app that uses several 3rd party add-ons. One of these add-ons uses Object.assign() which causes problem in IE11, specifically the error

Error: Object doesn't support property or method 'assign'

I know why this is happening, but I'm relatively new to Ember, and am not sure of the best way to handle/fix this. Based on my research, some options are:

Option 1: use polyfills (?)

I think there may be some additional libraries I can install, or options in Babel to set that will take care of this, but I have not been able to do so thus far. It's unclear whether any of these options would affect code from add-ons anyway, or if they only apply to code in the primary app.

Option 2: extend the add-on component to avoid Object.assign().

Unfortunately, the problematic lines are in the component's init(). When my extended component calls this._super(), the code I'm trying to avoid is run anyway. Is there a way to 'skip' the base component's init() and go straight to Ember's Component.init() (the add-on's _super()) ?

Option 3: ditch the 3rd party add-on, salvage what I can, and make my own component.

Irritating but do-able. At this point, it probably would have been faster to do that from the start.

I suspect that Option 1, polyfills and/or build settings, is the most correct course of action, but I'm at a loss for what, specifically, to do.

Additional info: My app was developed with Ember 2.7, and I am in the process of updating it to Ember 3.1. This issue exists in both builds.




Ember JQuery UI import overrides JQuery $ Behaviour

I need JQuery UI for dragging and dropping objects in my Ember app. So, after installing via yarn, I import it in the project's ember-cli-build.js as follows:

app.import('bower_components/jquery-ui/jquery-ui.js', {
    using: [{ transformation: 'fastbootShim' }]
});

It gets loaded successfully and drag-drop works fine. However, the form functionality in other part of my codebase breaks with the following error:

TypeError: Ember.$.fn.form.settings is undefined

In this file, $ is imported from jQuery: import $ from 'jquery';

I suspect the import of jquery-ui overrides the behaviour of $ and causes this error. How do I fix this? Am I missing something obvious? Please help, I'm an Ember newbie.




mardi 21 août 2018

Place to put assets for dev/test in emberjs

I'm using mirage to mock some data and I'd like to mock an <img> with the appropriate file.

The problem is that I will have to place the image in /public/assets and the images placed there will be deployed later on as well.

Is there a way to avoid this? I couldn't find a recommendation in the ember cli website (https://ember-cli.com/user-guide/#asset-compilation)

I found one addon that could do this (ember-test-assets), but I'd like to avoid installing extra addons as much as possible.

Thanks!




Responsive view like Whatsapp web using Boostrap 4 and Ember

I'm trying to implement Whatsapp web like UI. I'm using Bootstrap 4 and Ember 3.2. The base idea is working now. I've done the message box which is on the bottom of the view (using fixed-bottom Bootstrap class). I've messages list which is automatically scrolling down using jQuery inside list container custom component like:

export default Component.extend({
    didRender() {
        this.$().parents('html, body').scrollTop(this.$(document).height()); // Scroll immediately
    }
});

Here I have the margin set for list:

    <div id="ember390" class="ember-view">
    <div class="container-fluid pt-5" style="border: 1px solid red;margin-bottom: 32vh;">
            <div class="d-flex flex-column">
                <div class="p-2">
                    1
                </div>
                <div class="p-2">
.......

I'm adding margin-bottom: 32hv which is "lifts up" the message list on the message input box. This solution works on full HD screens. Once I'm trying the same view on small displays the margin-bottom: 32hv is not enough because of Bootstrap responsive.

I've got one solution, but not sure is it correct. I can calculate the margin-bottom value by window size and message box container.

Is it only one way, or can I do the same with pure CSS?

Another issue is to use jQuery with Ember.js, so I can't get access to message input container inside the message list container component.

Here is example https://www.bootply.com/QKVffslOIf




How should DS.AbortErrors ("The adapter operation was aborted") be handled?

I'm currently running Ember Data 2.18 and am having difficulties finding documentation on how to gracefully handle DS.AbortErrors/DS.AdapterErrors. Their documentation reads:

A DS.AbortError is used by an adapter to signal that a request to the external API was aborted. For example, this can occur if the user navigates away from the current page after a request to the external API has been initiated but before a response has been received.

This is consistent with how I've been reproducing the errors – by refreshing the page before the route/model has finished getting responses back from an external API. This is all fine and makes sense, but is there a way to gracefully handle these errors? I'm seeing a tonne of them in New Relic where we monitor our errors and its becoming quite noisy.

For reference, this is the error getting returned when a DS.AbortError is thrown:

Uncaught Error: The adapter operation was aborted

And here is the documentation I've been looking at.

Thanks in advance for your time!




Can I use an environment other than 'test' for Ember tests?

I have Ember.js 2.16 acceptance tests written using the Ember template test libraries (QUnit and testem) that test the general functionality of an Ember app. When I run ember test, the 'environment' for which environment variables are retrieved is always set to test.

Is there a way to run ember test with any environment other than test? Running it with --environment="my_other_test_env" doesn't change the environment as it would for ember build or ember serve.

I’d like to be able to pass parameters to acceptance tests depending on what environment they are running in. Is this behavior supported, and if not, is there a reason I shouldn't be doing this? I understand that for lower-level unit testing, I shouldn't be dealing with external dependencies, but for end-to-end acceptance testing, it seems normal that there would be different environments I would want to run the tests in.




Modify how ember-i18n localizations are loaded, split localization strings from main app.js

I am trying to modify the way ember-i18n localizations are loaded. What I want to do is have the localizations in a separate file from the main app javascript file.

Ideally, the structure would remain the same as now. So I would have app/locales/fr/translations.js and app/locales/de/translations.js , each having content similar to this:

export default {
 key: "value"
}

So I thought I need to write a custom addon, which would alter the build process. This addon would need to:

  1. Ignore app/locales from final build

  2. Compile all the translation files into one

  3. Transpile the new file with babel

  4. Copy the file in dist/assets/translations.js

The combined translation file would look something like this:

export default {
 fr: {
   key: "value"
 },
 de: {
  key: "value"
 }

This way, I would be able to use and instance initializer and simply import and use this module:

import Translations from 'my-translations';

export function initialize(instance) {
   const i18n = instance.lookup('service:i18n');
}

Also, index.html would be:

<script src="assets/vendor.js"></script>
<script src="assets/translations.js"></script>
<script src="assets/my-app.js"></script>

Well, I started writing the custom addon, but I got stuck. I managed to ignore the locales, and I wrote code that parses all the localizations, but I do not know how to write the new translations file in dist. What hook do I neeed to use, to be able to write into dist? Any help? Thank you so much.

Here is the code I wrote:

preprocessTree: function(type, tree) {
    if(type !== 'js') {return tree;}

    var treeWithoutLocales = new Funnel(tree, {
        exclude: ['**/locales/*/translations.js']
    });

    var translations = {};
    var files = fs.readdirSync('app/locales');
    files.forEach((tag) => {
        if(tag !== 'fr') {return;}
        let contents = fs.readFileSync('app/locales/' + tag + '/translations.js', 'utf8');
        contents = contents.replace(/^export default /, '');
        contents = contents.replace(/;$/, '');
        contents = JSON.parse(contents);
        translations[tag] = contents;
    });

    // Should do something with this .. how to write in dist? and when? I need it compiled with babel
    var fileTree = writeFile('/mondly-app/locales/translations.js', 'export default ' + JSON.stringify(translations) + ';');

    return treeWithoutLocales;
}




Ember View does not updating as of the change that happen to the model immediately

When I am making an AJAX request to update some values the data or model is changing. But the updated model is not reflecting immediately. It is reflecting only after clicking refresh. I want to only modify a view of a div in the page. I have tried many things but not successful. Can anyone suggest me the way to solve the issue? The git repo: https://github.com/SyamPhanindraChavva/trell-app-front-end

The UI part is in "notes.hbs" and the ajax request is in "services/work-status.js"

The thing I am trying to make is whenever I change the status of a record the corresponding record in the UI must also go to the corresponding table or container in UI.




Puppeteer not recognizing a node

I have some http I'm attempting to automate with CucumberJS and puppeteer:

<button data-test-foo="true" id="ember1213" class="ao-button ao-button--primary ao-button--large ao-button--block ember-view">
<!---->  <span class="ao-button__label">View Related Payment Requests</span>
</button>

When I attempt to page.clisk it:

async selectBeginImportButton() {
    await this.page.click('[data-test-foo="true"]');
}

I get an error:

✖ And I go to the Import files # features/step_definitions/login_steps.js:58
   Error: No node found for selector: [data-test-foo="true"]

What am I doing wrong?




BroccoliMergeTrees (TreeMerger (lint)): Expected Broccoli node, got [object Object] for inputNodes[1]

04 and in other OS my ember project is working fine, but in this OS,an error is thrown BroccoliMergeTrees (TreeMerger (lint)): Expected Broccoli node, got [object Object] for inputNodes[1]. I am not able to understant why it is happening. Ember Version: 1.13.15 Node Version: 6.11.2

Can any one Help me here? Stack Trace!!

https://i.stack.imgur.com/1pLYd.png




lundi 20 août 2018

How to select EmberJS elements with puppeteer

Okay, I'm currently stuck. I'm trying to implement CucumberJS and Puppeteer on an EmberJS solution.

I've got a emberjs button:

<span class="ao-button__label" >View Related Payment Requests</span>

and I included an HTML attribute: data-test-button-view-related-payments-requests="true"

When I attempt tp select it:

await this.page.click('[data-test-button-view-related-payments-requests="true"]');

I get:

Error: No node found for selector: [data-test-button-view-related-payments-requests="true"]

What am I doing wrong?




How to disable autofill on ember form field

I have a form for updating the details of alumni in ember using RESTful api. Is it possible to prevent the form from auto filling the data I previously entered in the form corresponding to another record in the model?

I have these codes in my update route directory(I am using pod-structure):

controller.js

# app/alumnis/update/controller.js
import Controller from '@ember/controller';
import { get, set } from '@ember/object';

export default Controller.extend({
  firstName: null,

  actions: {
    updateAlumni(value) {
      let firstName = get(this, 'firstName');
      if(firstName) {
        firstName = firstName.charAt(0).toUpperCase() + firstName.slice(1).toLowerCase();
        this.get('store').findRecord('alumni', value).then(function(alumni) {
          alumni.set('firstName', firstName);
          alumni.save();
        });
      }
      this.transitionToRoute('alumnis.show', value)
    },
  },
});

route.js

# app/alumnis/update/route.js
import Route from '@ember/routing/route';
import { set } from '@ember/object';

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

  setupController(controller, model) {
    set(controller, 'alumni', model);
  }
});

template.hbs

# app/alumnis/update/template.hbs
<form class="alumniForm" >
  <div class="form-group">
    <h3>First Name : </h3>
  </div>
  <button class="btn btn-primary" >Submit</button>
</form>

router.js

# 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('alumnis', function() {
    this.route('show', {path: '/:id'});
    this.route('add', {path: '/add'});
    this.route('update', {path: '/:id/update'});
  });
});

export default Router;

On the first rendering of update route after every reloading, no form fields are filled automatically. But, once we enter data to the firstName input field, it is rendered to form field in update page of any other record in the model alumni.




How to create dynamic elements based on selection of dropdown

I have a use case where I want to showcase properties related to a cluster once the cluster is selected from a dropdown.

Eg : Initial state of dropdown : enter image description here

On selecting cluster3, a new field must be added to the modal to show properties related to the cluster. enter image description here

The route gets details about the clusters including the dynamic properties. These properties may differ in number depending on the cluster chosen :

clusters : this.store.query('cluster', {detailed: true})

The /clusters api response shows :

 {
  "data": [
  {
    "id": 1, 
    "type": "clusters",
    "attributes": {
      "clustername": "cluster1",
      "properties": {
        "queue.name": "name"
       }
     }
    },
    {
    "id": 2, 
    "type": "clusters",
    "attributes": {
      "clustername": "cluster2",
      "properties": {
        "os.name": "os"
       }
     }
    }
  ]
}

How do I achieve this?

I could create a block that has style of "display:none;" This will then be switched to "display:block;" on the click of the cluster name (in setSelection action).

But how do I populate the value beforehand?

My template file has contents for the cluster as follows :

<label class="form-label" for="cluster">Cluster</label>
<div class="dropdown form-control full" id="cluster" style="width: 100%; max-width: 600px;" >
<div class="selected-value" tabindex="0">
     <span>Select</span><span class="fa fa-caret-down"></span>
</div>
<ul class="dropdown-options">
     
          <li value=""></li>
     
 </ul>
</div>

And for the new field :


<div class="form-field" style=" display:none;">
 <label class="form-label" for="queuename">Queue name</label>
  <div class="dropdown form-control full" id="queuename" style="width: 100%; max-width: 600px;">
    <input id="QueueName" style="width: 100%; max-width: 600px; value= "/>
  </div>
</div>


How do I populate the values here based on what is selected in the clusters dropdown? Is this done in the actions method, setSelection?

what should I iterate over given the properties is a field within the clusters object?




ember evented on error: Assertion Failed: on called without valid event names

i have a controller in my ember 2.18 app and i want to make it listen to some event 'myEventName' triggered somewhere in the app, to change the model properties.

according to the API docs for this version the way to catch an emitted event is like this:

import Evented from '@ember/object/evented';
import Controller from '@ember/controller';
// extend some object, like a Controller
const myExtendedObject = Controller.extend(Evented, { 
    // stuff ...
     });

myExtendedObject.on('myEventName', function (args) {  
    console.log("catch importDone  ok", args); 
    });
export default myExtendedObject;

the code compiles well with ember build dev, but in the browser's JS console i get this error message:

Error: Assertion Failed: on called without valid event names error.js:40

i tried renaming event, but i cannot find why the event name is wrong. also tried to set 3 arguments to the "on" method, but it is still bugging with the event name. what am i missing ?




dimanche 19 août 2018

How to detect an array of strings and an array of objects in my data using JavaScript?

I have an array of strings

arrayOfStrings = ['test', 'test] 

And an array of objects

arrayOfObjects = [{}.{}]

I need to be able to detect if my data is an array of strings and is so stringify it and if it's an array of objects do Y.




safari iOS renders blank page when height is set together with flex

I have a website which makes use of the following css:

html {
  height: 100%;
}

body {
  height: 100%;
  display: flex;
  flex-direction: column;
}

I have found that this causes issues when rendered on safari (especially on iOS). Either a subset of the page is rendered blank, or sometimes even the whole page. This also does not happen on every request, but about on every second. When the mouse is hovered over elements that are rendered blank, the elements start to appear. Switching the screen rotation on iOS works as well and everything suddenly appears.

I do need both, the height set to 100% (as vh is unreliable on iOS and has the same issue) and the flexbox. However, removing one of both gets rid of the issue. Are there known workarounds, except not setting a height when using flexbox? If I don't set the height to take the whole screen the flexbox only takes the space it actually needs, but it always needs to fill the whole screen.

website actually is an ember application. iOS is 11.3.1. I have tested on iPad and iPhone. Strangely it seems to be not as easy to reproduce on iPhone as it is on iPad.

I'll add a fiddle with a minimal reproduction once I have been able to create one.

EDIT

I was able to track this down to an overflow-y property. Markup basically looks like this:

<html>
  <body>
    <section>
    </section>
    <footer>
    </footer>
  </body>
</html>

and the added css is:

body > section {
  flex: 1 0;
  overflow-y: auto;
}

interestingly, changing to overflow to scroll seems to fix the issue. I probably need to do some more digging though, as I still haven't been able to create a simple reproducer




Cannot transitionTo, the error "more context objects were passed than there are dynamic segments" is incorrect

I'm using Ember 3, and I am having an issue using the Router service with dynamic segments. In my component, I use the Router Service to transitionTo a child route on a click, but I get this error:

Error: More context objects were passed than there are dynamic segments for the route: data.images.image

This is in the component js, where I use transitionTo and pass one parameter for the one dynamic segment:

router: service(),
actions: {
    navToSubpage() {
        // this.image is a single Ember Data record/object
        this.router.transitionTo('data.images.image', this.image)
    }
},

This is from my router, which has nested routes with one dynamic segment:

Router.map(function() {
  this.route('data', function() {
    this.route('images', function() {
      this.route('image', {path: '/image_id'});
    });
  });
});

What am I doing wrong? The error doesn't make sense to me in this case.




samedi 18 août 2018

Ember js filtering the the data from the model

I am trying to filter the data from the ember model but I am unable to find the solution.

<h2>
//The file is in app/routes/notes.js<br/>
import Route from '@ember/routing/route';
<br/>
export default Route.extend({<br/>
 model()  {<br/>
 let l= this.store.findAll('note');<br/>
 return l;<br/>
 }<br/>
 });<br/>
 </h2>

------------------------------------------


<h2>
 //The file is app/templates/note.hbs <br/><br/>
 <br/>
 Title: <br/>
 Description: <br/>
 Date:<br/>
 
  <br/>
  </h2>

I am trying to filter the data return from a model but it is not working as I am thought.The JSON format used in this is

{title:title,description:description,date:date,status:status}

,I want to filter the output based upon the status and display on the template.But I am unable to modify the data it showing some errors. I Have tried filtered from the model itself or by controllers actions but not worked. Can anyone suggest the solution?


vendredi 17 août 2018

ember concurrency, how to set timout value based on conditions

I am using ember-concurrency where I have to make API calls every 10 seconds and update the setup status for my application install phase. If there is an error, then I need the timeout value to be 1 seconds instead if default value of 10 seconds. Seems like every time timeout value is 10 seconds only and even with an error, user is on the screen for 10 seconds and then sees an error modal. Can anyone tell what can be a possible solution? or what I am doing wrong?

induceWait: task(function*() {
  while (continue) {
   // make the api call here
   //if error in any evaluating conditons, set timeout value to be 1 seconds, else 10 seconds
   this.get('store').findAll('status').then((response) => {
     if (response.flag) {
        this.set('timeout', 10000);
     } else {
        this.set('timeout', 1000);
      }
   }, (error) => {

   });
   yield timeout(this.get('timeout');
   this.get('induceWait').perform();
}




jeudi 16 août 2018

Something about dynamic segments in ember.js?

I am a new starter in ember.js, and recently i get a problem like this

Assertion Failed: You attempted to define a `` but did not pass the parameters required for generating its dynamic segments. More context objects were passed than there are dynamic segments for the route: cryptid

I will show my code below and Anyone can explain what’s wrong and how to fix it?

in models(cryptid.js)

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  cryptidType: DS.attr('string'),
  profileImg: DS.attr('string'),
  sightings: DS.hasMany('sighting')
});

in routes(crypteds.js)

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

export default Route.extend({
  model(){
    return this.store.findAll('cryptid');
  }
});

in cryptids.hbs

<div class="row">
  
    <div class="col-xs-12 col-sm-3 text-center">
      <div class="media well">
        
          <img class="media-object thumbnail" src="" alt="" width="100%" height="100%">
        
        <div class="caption">
          <h3></h3>
        </div>
      </div>
    </div>
    
      <div class="jumbotron">
        <h1>No Creatures</h1>
      </div>
  
</div>

in router.js

Router.map(function() {
  this.route('sightings', function() {
    this.route('new');
  });
  this.route('sighting', function() {
    this.route('edit');
  });
  this.route('cryptids');
  this.route('cryptid'), {path: 'cryptids/:cryptid_id'};
  this.route('witnesses');
  this.route('witness');
});




I want to understand the bit masking and shifting process in embedded c. Therefore, can anyone explain me the working of below commands in detail?

I am working on ADS1299 and Atmel. Therefore, I am interfasing ADS1299 with Atmel SAM4E. For that I want to be very good at Bit Masking and shifting. Therefore, can anyone help me with understanding those concept by explaining the below lines?? 1. #define SINE_CONTREG_BASE (0x1 << 13) 2. #define SINE_PHASEREG_BASE (0x3 << 14) 3. #define IOPORT_MODE_MUX_MASK (0x7 << 0) /*!< MUX bits mask / 4. #define IOPORT_MODE_MUX_D ( 3 << 0) /!< MUX function D */ 5. PORTB |= (1 << PB2); 6. PORTB &= ~(1 << PB2);




Asynchronously loading translations with ember-intl

I'm trying to achieve asynchronous fetching of translations. I set up the publicOnly to true as docs say:

// config/ember-intl.js
module.exports = function() {
  return {
    publicOnly: true
  }
};

Skipped the step of setting up the locales key, because translations are stored in /translations folder.

Next, I should modify beforeModel hook to asynchronously fetch the translations, and that's where docs are pretty vague:

// app/routes/application.js
export default Ember.Route.extend({
  intl: Ember.inject.service(),
  async beforeModel() {
    let translations = await fetch('/api/translations.json');
    this.get('intl').addTranslations('en-us', translations);
    this.get('intl').setLocale('en-us');
  }
});

How these lines supposed to work:

let translations = await fetch('/api/translations.json');
this.get('intl').addTranslations('en-us', translations);

In runtime I have no translations.json file anywhere in the dist folder. I've got dist/translations/en-us.json only for my one and only translation and no clue how to make it work.

Service API misses documentation of addTranslations method.

Would appreciate any help.




Wrapping npm modules as Ember Addons

I am working on an Ember application and would like to create an ember addon for it. The use case for the addon would be to create an ontology tree for the consuming application. The repository for the module I would like to make into an addon is inspire tree and I am needing to wrap this module.

Inspire Tree Repository ===> (https://github.com/helion3/inspire-tree).

I am aware of the general structure of Ember addons and an idea on how to make one, but if anyone can give advice on best practices & how to wrap npm modules as addons in general would be very helpful.




Ember-data: How to deal with inheritance objects

I have a JSON-Api backend and I can't find the good way to deal with inheritance objects, because the Route ressource name is the parent Class but the "type" attribute in the payload correspond to the child class. Example of payload (GET /api/pets):

{
    "data": [
        {
            "id": "1",
            "type": "cat",
            "attributes": {
                "name": "Tom"
            }
        },
        {
            "id": "2",
            "type": "dog",
            "attributes": {
                "name": "Max"
        }
    ]
}

Now, I load it with a Route:

# app/routes/pets.js
import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return this.get('store').findAll('pet');
  }
});

Models:

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

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

# app/models/cat.js
import DS from 'ember-data';
import Pet from './pet';

export default Pet.extend({
});

# app/models/dog.js
import DS from 'ember-data';
import Pet from './pet';

export default Pet.extend({
});

And finally, I want to display them on a simple page:

# app/templates/devices.hbs
<h3>Pets list</h3>


  <h4></h4>


The objects are well loaded by the Route (I saw them with the Ember inspector), but there are not Pet objects, so they are not rendered. At this point, I don't know how to deal with that, without changing the api structure.




progress bar in ember js

I am looking for a progress bar kind of add-on for my ember app. Requirement is user goes through a setup process and in the end when user clicks submit, then I have to show him the complete progress with a loading bar indicating how much work is done.

I used ember-progress-bar but the problem is animation starts from 0 all the time whenever I update the percent value. Is there anything which we can use and is easily available? I can design my own but still wanted to confirm first if there is something which can be used.




mercredi 15 août 2018

Resolving keypaths (or chained relationships) in route

I am processing a bunch of records and producing an array of hashes for a third party library. For the life of me I can't figure out why this doesn't work.

export default Route.extend({
  model: function(params) {
   let qp = {viewName: 'byDay'};

  return this.store.query('job-receipt', qp).then(
   (receipts)=>
    all(
      retval.map(
        (receipt)=>
          hash({
            stockCode: receipt.get('job')
                                   .then(job => job.get('stockCode'))
                                   .then(stockCode => stockCode.get('stockCode')),
            productClass: receipt.get('job')
                                  .then(job => job.get('stockCode'))
                                  .then(stockCode => stockCode.get('productClass'))
                                  .then(productClass => productClass.get('descr')),
            qtyRecvd: receipt.get('qtyRecvd')
          })
        )
      )
);

If I keep reentering the route, eventually the promises resolve. If I check, the productClass promise just straight up gets called with a null value. Why isn't it waiting for the stockCode.get('productClass') to resolve? I know there are real values in there because it does eventually resolve.

I'm missing something super basic. I've tried Ember.get(thing, keypath) etc. Don't these all return promises? Isn't the RSVP.hash supposed to wait for all the promises to resolve before proceeding? Like I said, I know the data is good because eventually it does resolve (as opposed to me just not handling a rejection).

Thanks in advance, John




Ember queryParams in Router VS in Controller

I am confused about queryParams from Ember's documentation. It shows that you can put queryParams to Controller or Route. What are the differences having queryParams in Route vs Controller except syntax?

As far as I understand, having queryParams as object in Route allows me to do following things:

  1. Use replace: true and refreshModel options.
  2. Capture queryParams faster than controller.
  3. Model hook can receive params values

In what case would you choose to have queryParams in Controller?




mardi 14 août 2018

WARNING: Node v10.8.0 is not tested against Ember CLI on your platform

I successfully installed Node 10.8.0, npm 6.3.0 and ember-cli 3.3.0 on my mac:

$ ember -v
ember-cli: 3.3.0
node: 10.8.0
os: darwin x64

$ npm -v
6.3.0

However, when I run

ember serve

on the ember demo project (super-rentals), I still get this error - even though the link says that the combination of ember & node is fine:

WARNING: Node v10.8.0 is not tested against Ember CLI on your platform. We recommend that you use the most-recent "Active LTS" version of Node.js. See https://git.io/v7S5n for details.

Any ideas what I am doing wrong ?




ember has many with async true

I has many relation in my ember app but it is not working recursively. here is my model. -->tree.js

>  export default DS.Model.extend({
>           parent  : DS.attr(), 
>           parentId : DS.attr('number', {defaultValue: "0"}),
>           childrens: DS.hasMany('menu', {async:true}),    
>           name    : DS.attr(),
>     });

route code-->

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

hbs-->>


<div class="col-lg-12">


  
    
    <div class="col-lg-12" style="margin-left:30px;">
      
    </div>  
    
    
 
</div>


sub-tree-view component js file -->

    > showRecord:function(){  
let self = this; 
  let tree = self.get('tree');
    >     var test = tree.get('childrens'); }.property(),

But it not calling the model again with children id . With hasmany relation it should call the menu model recursively but it is not making the request again. How to deal with the has many relationship data.?




Can I add a class to a div, when hovering over another class, without using jQuery in Ember

I have created a table in Ember, and when I hover over the specific header cell for a column, I want to highlight the entire column.

I accomplished this quite easily, but I'm told that this may not be "the ember way".

New to ember, so I'm double checking.

HTML

  • onmouseover I call highlightBlocks I send the ID of the header cell
  • onmouseout I call unhighlightBlocks (removes class, not adding it because)

Ember component

highlightBlocks(value) {
 this.$(`.${value}`).addClass('highlighted-block');
}

Is there a better way to do this? What's the ember way?




emberJS resetting form fields when the user clicks on a browser's forward and back buttons

I am working on an emberJS application and I have a question regarding a browsers forward and back buttons: If a user navigates to a form, then fills out some information, then hits the browser back button, then the forward button, what is the proper way to reset the form so that the fields are blank again?

Do I need to explicitly set the fields to empty string or is there some way I can force a refresh rather than having the browser go to the cache?

Thanks,

Terry




ember-cli-mirage factory only includes one child

I have my mirage setup with two models and factories like so

mirage/models/user.js

import { Model, hasMany } from 'ember-cli-mirage';

export default Model.extend({
  posts: hasMany()
});

mirage/models/post.js

import { Model, belongsTo } from 'ember-cli-mirage';

export default Model.extend({
  user: belongsTo()
});

mirage/factory/user.js

import { Factory, faker } from 'ember-cli-mirage';
export default Factory.extend({

  name(i) {
    return `Person ${i}`;
  },

  afterCreate(user, server){
    server.create('post', 10, { user });
  }

});

mirage/factories/post.js

import { Factory, association } from 'ember-cli-mirage';

export default Factory.extend({

  title(i) {
    return `Show ${i}`;
  },

  description(){
    return faker.lorem.paragraph();
  },

  user: association()
});

mirage/serializers/user.js

import { RestSerializer } from 'ember-cli-mirage';

export default RestSerializer.extend({
  include: ['posts']
});

mirage/scenarios/default.js

export default function(server) {
  server.createList('user', 10);
}

In my model hook I make a request to this.get('store').findAll('user') and then I loop over it in my template. The problem I have is that this get request only includes 1 post per user. What I would have expected is to get 10 posts created per user.

What am I missing here?




Chrome headless screenshot on local machine

I have a localhost website created with ember which is just working fine.

I want to use Lighthouse to get some metrics about the performance over time. Of course I want this to be in Chrome and headless. I installed Lighthouse using NPM and run the following command:

lighthouse http://localhost:4200 -chrome-flags='--headless'

When running above, I got the following error resulting in a question mark as a performance metric:

Chrome didn't collect any screenshots during the page load. Please make sure there is content visible on the page, and then try re-running Lighthouse. (SPEEDINDEX_OF_ZERO)

I tried running the dist folder of ember with the http-server package, but no differences in the result. The same error occurs.

When I run the test against google.com or against a website in our test environment I get a result back and not the error. When a colleague is running it on his local machine, no error occurs. Only difference we can find is he is running win8.1 and my machine is win10.

When I run Chrome without the headless flagg I also get a result, but I need it to work headless.

I'm using all the latest versions of Lighthouse, Chrome, Windows10, node. Also tried Chromium but no differences.

Hopefully someone got an idea




lundi 13 août 2018

Ember if helper for component attribute

I want to do the following



The above does not work for some reason. What is the correct way to do the same ?

P.S: I want to do this for a custom component attribute & not a DOM element ?




Possible to guarantee ember-cli addon hook run order?

Is there a document (or a test) that guarantees the run order of addon hooks?

I need to do work in both config and included, but they run in different orders depending on environment.

With ember serve it is config -> included -> config. But ember test runs them as included -> config.

I’m wondering if I rely on config running at least once after included if that will keep working.




What is node_modules directory in ember

What is the usage of node_modules directory in ember?

I could see this directory created accross my ember application. When does it get created and what is the significance?

What harm if i delete this directory?




dimanche 12 août 2018

Basic use of `this` in Ember.js

I'm fairly adept in Javascript but I'm having a hard time understanding how Ember is handling the this context in certain scenarios.

I have a component controller:

import Component from '@ember/component';

export default Component.extend({
  keyPress(e) {
    // here I want to call a method in the `actions` hash
    this.get('onAccept')
  },

  actions: {
    onAccept() {
      console.log('action accepted!')
    }
  }
}

Every time I run this though, I get the following error:

Uncaught TypeError: this.get(...) is not a function

This seems to always happen when I have a method outside of the actions hash that needs to access a function inside the actions hash, or the other way around.

And this behavior seems necessary, because component events belong outside of the actions hash.

So how am I supposed to have event methods outside of the actions hash but still be able to call methods that belong inside of the actions hash?

This seems to be a poorly documented part of controllers in Ember. Maybe I am just missing something here. Any help is greatly appreciated.




Ember how to render value of key if the key is also an object in each-in

In my ember app, I have the following "each-in"


  <tr><th></th><td class="space-left"></td></tr>


Which renders my data i.e. customer_name Test example_one New

But I also have data is that is an object (another lawyer) right now it looks like so

drops [object Object],[object Object]

or

summary [object Object]

And the API returns different data so it can change, is there a way in ember to also render the child data so it's not showing object object




Ember: Add attribute to element generated by helper

I have the following template file:

<h2 style="margin-top: 20px" class="ui header"></h2>
<div id="sessions-list">
  
    
      <div class="unscheduled" data-toggle="tooltip" data-animation="false" data-placement="top" draggable="true">
        <span class="text">
           | 
        </span>
        
          <span class="text speaker">
            
          </span>
        
      </div>
    
  
</div>

I want to add a data attribute to the elements generated by the helper. This attribute should essentially have its value as session, and it's not the same as content. Any idea how to accomplish this?




Ember - different keys for serialization and deserialization

I have an issue where an property needs to be serialized and deserialized using to different keys.

In the serializer, the property addresses the key trade:

'tradeId': { key: 'trade' },

This works when addressing the deserialization endpoint.

However, for serialization, the endpoint property is called trade-identifier, requiring the serializer reference to be changed to the following:

'tradeId': { key: 'tradeIdentifier' },

Is there any way to define seperate keys for serialization and deserialization in an Ember serializer?




NodeJS and client-side Javascript in Ember application

I am working on developing a client-side application built on EmberJS.

Now, while I test the code in the browser ultimately, I have the following locally for development;

  1. NodeJS & NPM
  2. I have defined bower.json & package.json
  3. I use ember-cli & do ember build & ember server to start the local server
  4. I hit the URL http://localhost:4200 in the browser to access the app

Now my question is I wanted to understand, what exactly is happening here ? Meaning what exactly happens before code runs in the browser.

I understand when the build happens, it actually pushes code into the 'dist' directory.

Is there any role in NodeJS in all of this (meaning any JS run on server-side in the background) OR we just utilize npm/bower for this case ?

So I just wanted to connect all the dots regarding running in the browser.




samedi 11 août 2018

AJAX call inside Ember.RSVP.Promise

I have the following common code to invoke AJAX requests. My question is if the "return" keyword is necessary for the $.ajax (since doing $.ajax would anyways return a promise) OR if it is for some other purpose ?

doXhr: function(postData, requestUrl){  
    var promise = new Ember.RSVP.Promise(function(resolve, reject) {        
        return $.ajax({ //Is the "return" required on this line ?
            url: requestUrl,

        })
        .done(function(response, status, xhrObject) {         
          resolve(response);
        })
        .fail(function(xhrObject, status, error){           
            reject(errorObj);
        });
    })  
    return promise;
},




Ember load variable everytime page is loaded

I want a variable called "name" in my router or controller , which i will use in my hbs template. Right now , I'm doing this. But the get() is not loading if i navigate backward and click the link to the current page again. It only loads the first time and if i refresh the page . Due to this, the value of name in my form is not reloading everytime i hit the page.

      #controller
      name: computed('model.name', {
        get() {
          return this.get('model.name');
        }
      })



      #.hbs
      
      <button >Update Post</button>




vendredi 10 août 2018

How to access Ember Data store when registering test helper? Ember 3.3

I'm using a custom test helper which requires access to the Ember data store, but I don't know how to access it from the given application argument.

export default registerAsyncHelper('myCustomHelper', function(app) {
  console.log(app); // how to access store?
  let store = app.__registry__.registrations['service:store'].prototype;
  store.pushPayload(// json payload);
});

How can I get access to the store when registering a custom helper?




Ember Component does not reload on route reload or transitionTo

I have an ember route that calls an ember component to display all the data.

I have a case in which the route's key changes and I reload using route.transitionTo. The data is loaded fine. But the problem is the component does stuff in the init and didInsertElement methods, which on the route.transitionTo aren't triggered.

How can I make sure on transitionTo the component is called again?

I can't use route.refresh because that doesn't do the model hook.

Any help will be appreciated, Thank you!




EmberJs Promises - Now to make .map() or .forEach() asynchronous?

Here is my controller action:

saveArticle(article, blocks) {
  let self = this;

  return RSVP.all(article.get('blocks').invoke('destroyRecord')).then(function () {
      blocks.data.map(function (item) {
        let block = self.get('store').createRecord('block', {
          article: article,
          type: item.type,
          format: item.data.format,
          text: item.data.text,
        });
        block.save();
        article.get('blocks').pushObject(block);
        debug('Block added.');
      });
      //article.save();
  });
}

How can I perform article.save () right after all the blocks have been created? That is, I want to delete all current blocks, create new ones, and save the article only after all these actions have been executed. I appreciate any ideas!




How to enable forced listing with ember serve

I need to enable forced es-linting with ember serve. When ever ember serve is run server should hold till all the es-lintings errors are fixed. I can do it with custom npm script, but want to look for ember-cli alternatives before writing my own scripts.




jeudi 9 août 2018

What does proto() in ember.js mean?

Could anyone explain what does proto() in this line mean ? It is from an ember code.

Client.Details.proto().set('isAdminUser',win.isAuthenticatedAdmin);




Ember JS Component - Cannot read property 'currentHandlerInfos' of undefined

In Ember Component action method, whenever I try to return an ajax call synchronously either by using preventDefault() or return false, I get a following error form the console:

route-action.js:15 Uncaught TypeError: Cannot read property 'currentHandlerInfos' of undefined at getRoutes (route-action.js:15) at getRouteWithAction (route-action.js:20) at Class.action (route-action.js:52) at Backburner._join (backburner.js:814) at Backburner.join (backburner.js:529) at Function.run.join (ember-metal.js:4453) at action.js:364 at exports.flaggedInstrument (ember-metal.js:4012) at action.js:363 at Class. (action.js:333)

Has anyone encountered this issue with Ember before?




Everytime i want go to a route path, when an invalid path is given

import EmberRouter from '@ember/routing/router'; 

const Router = EmberRouter.extend({ 
}); 


Router.map(function() { 
  this.route('index', {path: '/templates'}); 
  this.route('show', {path: '/templates/:id'}); 
}); 

export default Router;

I want to go to /templates, whenever any invalid path is given like /wrongquery.




While uncheck the checkbox needs to reload the search item

I'm having the search column with checkbox along with folder names. when I click the checkbox of corresponding folder, it will show their items. As well as when I click on multiple checkbox it will show their corresponding items. But when I uncheck the folder, the corresponding items doesn't remove. So I need the hard reload or refresh when I check or uncheck the checkbox or need to clear the cache for every check or uncheck.

Here is my Code:

    Checkbox: Core.component.Checkbox.extend({
        click: function () {
            var ret=null;
            var nav = this.get("controller").get('selectedNavigator');
            ret = this._super.apply(this, arguments);
            var states=null;
            Ember.run.schedule('sync', this, function () {
                Ember.run.schedule('render', this, function () {
                    states = this.get('parentView.itemStates');
                    var values =  Object.keys(states).filter(function (key) {
                        if(states[key]){

                        return states[key];}
                        else{return;}
                    });
                    if (values.length === 0) {
                        Core.Action('core:contentHome', {});
                    } else {
                        this.set('parentView.model.values',values);
                        nav.publish();
                    }
                });
            });
            return ret;
        }
    }),

Please provide me suggestion on this. Thanks in advance.




JQueryUI at Ember upgrade

After upgrade and dismissing Bower as recommended: Is there a way to include JQueryUI into an Ember project without using Bower? My project depends heavily of JQueryUI dialogs.

$ ember -v
ember-cli: 3.3.0  
node: 8.11.3  
os: linux x64  

Do I have to reintroduce Bower into my project? Like in this old Using jquery in Ember-cli advice?




mercredi 8 août 2018

Issue with Ember Server: Port 4200 is already in use when no application runs on 4200

I'm trying to make my ember application run but whenever I start it with ember serve -e local I get:

Port 4200 is already in use.

Which is weird because no application is running on 4200... I tried to open a dummy HTTP server on 4200 with http-server and it works just fine... Useless to say that I already:

  • Restarted my computer.
  • Removed the node_modules.
  • Remove the ember tmp directory.
  • Disabled my firewall.
  • Tried with disabled wi-fi.

Any thoughts?

I'm running on masOS High Sierra 10.13.6 with the following versions:

  • node: 8.11.3
  • ember-cli: 2.18.2
  • npm: 5.6.0 (also tried with 6.3.0)

Also useful to know:

  • I have other ember applications running on my computer just fine.
  • I started to have this problem only recently.
  • In the past, macOS would keep asking me about authorizing incoming traffic whenever an app was opened, but now it stopped asking me.

I suspect the problem is coming from the operating system rather than the app in itself, but I can't wrap my head around the issue.

Any help is greatly appreciated!




Custom route for record.save() in ember

In ember , I have a model called "Post" . If i perform
record.save()

on creating a post , by default it posts to my /post url in Rails(backend). This works in my case. But for future uses, how do i specify a custom route? Let's say I want to post this model to my backend to a route called

"/post/save" .

How do i make record.save() in ember to go to this route?




ember acceptance tests wait helpers

I am writing acceptance tests for my ember app and one of the component take user input and validates credentials after which user can click continue and proceed ahead. The problem I am facing is as soon as tests fill in the input fields, then it clicks on the next button and andThen helper is not inducing sufficient wait or pause because of which test fails as I am setting some property once validation is completed.

Is there a way to induce delay while writing acceptance tests apart from andThen.




How to disable pagination in ember models table

I am using ember models table for a project to display data. I would like to get rid of the table pagination. So far I was not able to find a viable solution to accomplish this.

Does anyone has an idea how to implement this?




mardi 7 août 2018

Page loading before model is deserialized

Use case :

I am trying to render a page that compare outputs of 2 performance benchmark runs.

Issue :

Only part of the data is getting deserialized at the time of the page render. On multiple refreshs all of the data gets rendered.

The network tab seems to show that the output is sent correctly by the backend.

Execution:

1) The data is rendered using the api /reports/:reportId.

This api is called twice using 2 reportIds to be compared and the difference is then displayed on the UI.

The /reports/:reportId api returns an output like :

 {
  "data": {
    "id": 87,
    "type": "reports",
    "attributes": {
      "status": "STARTED",
      "startdatetime": 1532511531000,
      "enddatetime": 1533485380052,
      "queries": [
       {
        "startdatetime": 1532511531000,
        "enddatetime": 1533485380056,
        "reportId": 87,
        "id": "Q1"
      }
    ]
   }
  }
}

The output intermittently renders everything but the "queries" array while deserializing the array perfectly in some runs.

2) To parse the queries array I used a custom array transform like :

import DS from 'ember-data';

export default DS.Transform.extend({
   deserialize: function(serialized) {
      return (Ember.typeOf(serialized) == "array")
        ? serialized
        : [];
   },
   serialize: function(deserialized) {
      var type = Ember.typeOf(deserialized);
      if (type == 'array') {
        return deserialized
      } else if (type == 'string') {
        return deserialized.split(',').map(function(item) {return jQuery.trim(item);});
      } else {
        return [];
      }
  }
});

3) The model for reports looks like:

status: DS.attr('string'),
startdatetime: DS.attr('number'),
enddatetime: DS.attr('number'),
queries: DS.attr('array')

4) My route for compare looks like :

import Route from '@ember/routing/route';
import { hash } from 'rsvp';
import { inject as service } from '@ember/service';

export default Route.extend({
model(params) {
   return hash({
     leftrun: this.store.findRecord('report', params.id1),
     rightrun: this.store.findRecord('report', params.id2)
   })
 }
});

On running the page on debug mode when the queries array doesn't get deserialized,

1) I can see that the "status" and other attributes is accessible.

2) The network tab shows that the output for reports/:runId is "pending" (Which doesn't make sense as the "status" is set.) Once the page is fully loaded, the network tab shows that the full data including the queries array was received by the webapp.

Is there an issue with the flow or my transform that is causing this issue?




Ember.js - Hamburger menu disable click on div

I am a newbee in Ember. I am designing an application that has a hamburger menu. The menu slides in as an overlay from left to right when clicking the icon. My HTML and CSS for menu component is something like this:

&{  
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0%;
    left: 0%; 
    background-color: rgba(54, 53, 69, 0.65);
    @include set-z-index(LOADING_OVERLAY);
    @keyframes slideIn{
        from{
            transform: translate3d(-100%,0,0);
        }
        to{
            transform: none;
        }
    }
    @keyframes slideOut{
        from{
            transform: none;
        }
        to{
            transform: translate3d(-100%,0,0);
        }
    }
    .slideIn{
        animation-name: slideIn;
        animation-duration: 0.3s;
        animation-direction: normal;
    }
    .slideOut{
        animation-name: slideOut;
        animation-duration: 0.3s;
        animation-fill-mode: forwards;
    }
    .modaldiv{
        width: 17%;
        height: 100%;
        float: right;
    }
    .menu{
        width: 83%;
        height: 100%;
        /* rest of the menu css goes here */
    }
}
<div class="modaldiv"></div>
 <div class="menu slideIn">
   <!--Entire menu component goes here like user details -->
 </div>
</div>

 

I have a header component that has the hamburger menu icon. The HTML and JS for it is,

export default Component.extend({
openMenu: null,
 actions: {
  toggleMenu() {
   if (!this.get('openMenu')) 
   {
                 this.set('openMenu', true);
         } 
   else 
   {
    this.set('openMenu', false);
   }
 }
});
<div class="header">
    
        <div class='switcher menu' onclick=>
            
            
                
            
        </div>
    
</div>
As of now, the entire screen is clickable and the menu component slides in. I want to disable click on the menu component so that the user closes the menu by clicking outside it and it slides out. Can someone help? Thanks.


Ember project crashes after upgrading Bootstrap from 4.1.2 to 4.1.3

I have encountered a very strange problem while updating my project dependencies. I had Bootstrap 4.0.0 installed and installing the latest (4.1.3) version makes my project unusable. While rendering the page I get those errors:

TypeError: Cannot read property 'commit' of null
    at Environment.commit (vendor.js:22569)
    at Environment.commit (vendor.js:32631)
    at InteractiveRenderer._renderRootsTransaction (vendor.js:34756)
    at InteractiveRenderer._renderRoot (vendor.js:34686)
    at InteractiveRenderer._appendDefinition (vendor.js:34611)
    at InteractiveRenderer.appendOutletView (vendor.js:34599)
    at invokeWithOnError (vendor.js:24513)
    at Queue.flush (vendor.js:24422)
    at DeferredActionQueues.flush (vendor.js:24575)

Uncaught TypeError: Cannot read property 'off' of null
    at Class.teardown (vendor.js:110423)
    at Class.willDestroyElement (vendor.js:110416)
    at Class.trigger (vendor.js:60712)
    at Class.superWrapper [as trigger] (vendor.js:58700)
    at ComponentStateBucket.destroy (vendor.js:35913)
    at SimpleBlockTracker.destroy (vendor.js:18333)
    at SimpleBlockTracker.destroy (vendor.js:18333)
    at SimpleBlockTracker.destroy (vendor.js:18333)
    at SimpleBlockTracker.destroy (vendor.js:18333)
    at UpdatableBlockTracker.destroy (vendor.js:18333)

I tried to debug it with Ember Inspector. I have three pending promises with the same trace:

Ember Inspector (Promise Trace): 
    at new Promise (http://localhost:4200/assets/vendor.js:66433:28)
    at new Enumerator (http://localhost:4200/assets/vendor.js:66009:22)
    at Function.all (http://localhost:4200/assets/vendor.js:66173:12)
    at all$1 (http://localhost:4200/assets/vendor.js:66950:20)
    at Class.sendPending (<anonymous>:801:22)
    at Class.watch (<anonymous>:861:14)
    at sendEvent (http://localhost:4200/assets/vendor.js:37374:18)
    at Class.trigger (http://localhost:4200/assets/vendor.js:52321:33)
    at wrap (<anonymous>:3462:14)

I consider it weird for a couple of reasons:

  1. After downgrading to 4.1.2, everything works fine.
  2. 4.1.3 is a bugfix release, which doesn't change anything important in the JS files.
  3. After 4.1.2 -> 4.1.3 upgrade, the only difference in yarn.lock is a version of bootstrap package, so it's not caused by the update of some Bootstrap's dependencies.

What's the reason of this behaviour?

Here's my package.json dependencies list. Thank you in advance for the help.




lundi 6 août 2018

How can i write a dropdown in .hbl?

I'm working on a project where I need to do some changes. I want to add a dropdown to present some values in user end. I am new to ember, handlebars, and javascript. Please help me with this. I searched all over google for solutions and I raise this due to I couldn't find a solution.

This is the code,



    
        <p>Find or Test Your Book Idea</p>
        
        
    




This is the rendered interface, enter image description here

Under "Book or eBook" I want to have a dropdown. How can I achieve this?




Ember includedCommands: HTTPS request does not fetch

I am writing an ember includedCommand for fetching and updating the app/index.html file - which uses NodeJS https and fs module to replace the indexFile by calling a function BuildIndexFile, where I am facing a weird issue -

  • When I perform command ember server --update-index - I can see the BuildIndexFile is being called and the https request is made to the remote server which downloads the file and gets written by fs.writeFileSync in app/index.html.

ember server --update-index

  • But when I perform ember update-index which is an included command, I can see BuildIndexFile has been called, and it reaches till console.log('Fetching index.html'); and I believe it is calling https.request... but it closes from there, I have no idea why the call didn't go through, when I debugged using node --inspect-brk ./node_modules/.bin/ember update-index I can see the https is available on the file, but not executing.

ember update-index

I am attaching my sample code available as a in-repo-addon available at lib/hello/index.js -

lib/hello/index.js

/* eslint-env node */
'use strict';


const parseArgs = require('minimist');
const watchman = require('fb-watchman');

let client = new watchman.Client();

client.capabilityCheck({optional: [], required: ['relative_root']}, function (error, response) {
  if (error) {
    console.log(error);
  }
  console.log('Watchman', response);
});

const ServeCommand = require('ember-cli/lib/commands/serve');

const ARGS = parseArgs(process.argv.slice(2));

const fs = require('fs');
const https = require('https');

module.exports = {
  name: 'hello',

  isDevelopingAddon() {
    return true;
  },
  includedCommands: function() {
    var self = this;
    return {
      hello: ServeCommand.extend({
        name: 'hello',
        description: 'A test command that says hello',
        availableOptions: ServeCommand.prototype.availableOptions.concat([{
          name: 'updateindex',
          type: String
        }]),
        run: function(commandOptions, rawArgs) {
          console.log(commandOptions, rawArgs);
          if (commandOptions['updateindex']) {
            console.log('Update Index')
          }
          const sampleHelloPromise = sampleHello();
          const servePromise = this._super.run.apply(this, arguments);
          return Promise.all([sampleHelloPromise, servePromise]);
        }
      }),
      updateIndex: {
        name: 'update-index',
        description: 'Update Index File',
        availableOptions: [{
          name: 'index-file',
          type: String
        }],
        run: function(commandOptions, rawArgs) {
          BuildIndexFile(self.project.root, 'https://yahoo.com', {});
        }
      }
    }
  },
  preBuild: function(result) {
    let self = this;
    if (ARGS['update-index']) {
      BuildIndexFile(self.project.root, 'https://google.com', {}).then(function() {
        delete ARGS['update-index'];
      })
      .catch(function(e) {
        console.log(e);
      });;
    }
  }
};

async function sampleHello() {
  return await new Promise(resolve => {
    setTimeout(() => resolve('hello'), 2000);
  })
}

const BuildIndexFile = (rootPath, target, headers) => {
    try {
        debugger;
        const indexFile = `${rootPath}/app/index.html`;
        let noIndexFile = !fs.existsSync(indexFile);

    return new Promise(function (resolve, reject) {
      let options = {
        hostname: target.replace(/^http(?:s):\/\//i, ''),
        port: 443,
        method: 'GET'
      };

      let dataContent = '';

      console.log('Fetching index.html');
      var request = https.request(options, function(response) {
        response.on('data', function(d) {
          dataContent += d;
        });

        response.on('end', function() {
          fs.writeFileSync(indexFile, dataContent);
          return resolve();
        });
      });

      request.on('error', function(e) {
        console.log(e);
        return reject(`Error: Creating Index File`);
      });

      request.end();
    });
} catch(e) {
    throw e;
}
}




dimanche 5 août 2018

NPM: exists-sync is deprecated

I am receiving the following warning:

npm WARN deprecated exists-sync@0.0.4: Please replace with usage of fs.existsSync

Is there any NPM command that I need to do in order to get rid of this warning? I checked GitHub and understand that this project is for checking if a file exists (see link below). Currently, my project does not have any dependency on this function. So, I am just trying to find out if there is anything I need to do?

https://github.com/ember-cli/exists-sync

Update

I followed Leesei's advice and got the result below, which I think it means to say that exists-sync still exists under ember-maybe-import-regenerator@0.1.6. Am I correct? Is it safe to uninstall exists-sync?

enter image description here




Nested list of objects not getting deserialized in emberjs

I have a /reports api that returns an output like :

 {
  "data": {
    "id": 87,
    "type": "reports",
    "attributes": {
      "status": "STARTED",
      "startdatetime": 1532511531000,
      "enddatetime": 1533485380052,
      "queries": [
       {
        "startdatetime": 1532511531000,
        "enddatetime": 1533485380056,
        "reportId": 87,
        "id": "Q1"
      }
    ]
   }
  }
}

The models looks like:

model/report.js

status: DS.attr('string'),
startdatetime: DS.attr('number'),
enddatetime: DS.attr('number'),
queries: DS.hasMany('query')

model/query.js :

report : DS.belongsTo('report'),
startdatetime: DS.attr('number'),
enddatetime: DS.attr('number')

In my component (template.js), I try to access the queries and it seems to not be able to deserialize it right :

queriesLength: Ember.computed('report', function(){
  return this.get('report').get('queries').length;
}

Running queriesLength() returns 0 for the above mentioned json.

1) There are no issues in the console.log.

2) The browser network shows that the api returned the output correctly.

3) When accessing other properties like startdatetime, it returns the right value.

Is the model/api response missing something?