vendredi 31 juillet 2020

Is it possible to have a model named 'application' in Ember.js app?

I use RESTSerializer and implement it as default in app/serializers/application.js

In my project, I have a model named 'application' and I need to create a custom serializer for this model. And I faced a problem, that they are the same name with default lookup directory.

Can't find any settings in docs to solve this namespace conflict.




jeudi 30 juillet 2020

How can I use font-awesome in my ember.js app?

I have just started learning ember.js, and am currently working on a small project to practice. I'm trying to add some font-awesome icons into the app, yet when I follow the directions from the link font-awesome sends me to for ember.js applications, theres multiple syntactical ways of adding an icon. (The link is: https://fontawesome.com/how-to-use/on-the-web/using-with/ember, and https://github.com/FortAwesome/ember-fontawesome). So when I tried to add I get this error in my console:

Uncaught (in promise) TypeError: Cannot read property 'syscall' of null

and when I try this syntax <FaIcon @icon="coffee" />, I get this error:

Uncaught (in promise) Error: Compile Error: Cannot find component fa-icon

Kind of lost right now. I don't see a lot of relevant tutorials out right now and the docs for the font-awesome instructions are confusing me...Any advice would be highly appreciated. :)




Downloading file with ajax, but download happens in the browser memory

So, I'm trying to download the file with ajax. The file is downloaded but the user only knows of the file after clicking it is when the file is saved to disk. When I open the network tab, I can see that the xhr is downloading the content.

I'm using ember in the front-end.

How could I make it possible that it downloads directly to the file disk?

The backend is Java and it return InputStream.

I use ajax because there are some authorization headers in the request.

$.ajax(assign({
  dataType: 'blob',
  processData: false,
  success: (data, textStatus, jqXHR) => {
    // this.saveFileAs(filename, data, jqXHR.getResponseHeader('Content-Type'));
    console.log(filename);
    let filenamee = '';
    const disposition = jqXHR.getResponseHeader('Content-Disposition');
    if (disposition && disposition.indexOf('attachment') !== -1) {
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
      const matches = filenameRegex.exec(disposition);
      console.log(matches);
      if (matches != null && matches[1]) filenamee = matches[1].replace(/['"]/g, '');
    }
    const type = jqXHR.getResponseHeader('Content-Type');
    const blob = new Blob([data], {
      type: type
    });
    const URl = window.URL || window.webkitURL;
    const downloadUrl = URL.createObjectURL(blob);
    console.log(downloadUrl);
    console.log(filenamee);
    if (filenamee) {
      const a = document.createElement('a');
      if (typeof a.download === 'undefined') {
        window.location = downloadUrl;
      } else {
        a.href = downloadUrl;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
      }
    } else {
      window.location = downloadUrl;
    }
    setTimeout(function() {
      URL.revokeObjectURL(downloadUrl);
    }, 100); // cleanup
  },
  error: (jqXHR, textStatus, errorThrown) => {
    console.warn('Couldnt download');
  },
}, requestSettings));



Is it possible to make a route's model a computed / tracked property?

I'm trying to have a route's model hook return some array that is constantly updated via a polling mechanism using Ember later. The route file looks like this:

export default class IndexRoute extends Route {
  recent: [],

  init() {
    ...
    this.getRecent();
  }

  getRecent() {
    // poll data / fetch latest
    this.recent.push(newStuff);
    
    later(this, this.getRecent, 2000);
  }

  model() {
    return this.recent;
  }
}
 

Then in my controller, I wanted to create a @computed / @tracked property based on the route's model:

export default class IndexController extends Controller {
  // @tracked model; // this also didn't work
  @computed('model.@each') // this doesn't work
  get computedModel() {
    console.log('computedModel'); // prints only once, when the model hook is first run
    return this.model;
  }
}

I thought what this SO post suggested would have worked but it didn't :(

I saw this post but this was for Ember 1.13 so not exactly a modern solution.

Similarly this post had outdated content too.

Is what I'm trying to do possible? Alternatively I was thinking of moving the data into the Controller and making a computed property of a Controller variable instead. Taking all suggestions!




mercredi 29 juillet 2020

Ember cli pagination - unable

Working with Ember 3.19 and trying to use ember-cli-pagination. I have all my posts from JSONplaceholder in the data-store under model type 'post'. I was able to view all the posts from the data-store without pagination but have been unsuccessful in implementing ember-cli-pagination. Console shows currentPage and totalPages as undefined. The Articles element shows in the ember inspector but blank in chrome. The PageNumbers element appears but it is rendered as <<< ... NaN >>>

Controller - articles.js

import Controller from "@ember/controller";
import { tracked } from "@glimmer/tracking";
import { alias, oneWay } from "@ember/object/computed";
import pagedArray from "ember-cli-pagination/computed/paged-array";
import { inject as service } from '@ember/service'

export default class ArticlesController extends Controller {
  // setup our query params
  queryParams: ["page", "perPage"];

  // set default values, can cause problems if left out
  // if value matches default, it won't display in the URL
  @tracked page = 1;
  @tracked perPage = 10;

  // can be called anything, I've called it pagedContent
  // remember to iterate over pagedContent in your template
  @pagedArray('model', {
    page: alias("parent.page"),
    perPage: alias("parent.perPage"),
  })
  pagedContent;

  // binding the property on the paged array
  // to a property on the controller
  @oneWay("pagedContent.totalPages") totalPages;
}

Handlebar - articles.hbs

<h2>Posts</h2>
<div>
<ul>
    
    <li>User:  Title:  - </li>
    
</ul>
</div>

<PageNumbers @content= />

Model - post.js

import Model, { attr } from '@ember-data/model';

export default class ArticleModel extends Model {
  @attr title;
  @attr body;
  @attr userId;
}



How do I display grouped results in an EmberJS Application

I've created a simple EmberJS application that lists jobs from a headless CMS. The jobs data from the backend is in this format

[
   {
      "id": "1234",
      "description": "Test description"
      "category": "Human Resources"
   },
   {
      "id": "4321",
      "description": "Test description"
      "category": "Human Resources"
   },
   {
      "id": "5678",
      "description": "Test description"
      "category": "Information Technology"
   }
]

My app displays the results in the order that they're returned as expected but I'd like to group the results by category so that the results are displayed like this:

Human Resources

  • 1234
  • 4321

Information Technology

  • 5678

Thanks in advance for any help.

Note: I'm using EmberJS version 3.19




mardi 28 juillet 2020

Ember project to Github Pages

I just finished making an ember project (super simple nothing huge) You can check it out <here>

but I am trying to deploy it to make it into a website on github pages and there is hardly any documentation out there and was wondering if I could get some help. Thank you




samedi 25 juillet 2020

Append record onto RecordArray and Dynamically update Component Template

For the base setup of the app referenced in this question, I am using the Ember Guides Tutorial App.

Here is the route specified in my router.js

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

export default class Router extends EmberRouter {
  location = config.locationType;
  rootURL = config.rootURL;
}

Router.map(function() {
  this.route('testing');
});

Here is my route which returns a RecordArray of rental records:

// testing.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class IndexRoute extends Route {

  @service store;

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

Here is my rental model:

// rental.js
import Model, { attr } from '@ember-data/model';

export default class RentalModel extends Model {
  @attr title;
}

My testing template:

//templates/testing.hbs
<MyComp @rentals= />

My MyComp component template:

// components/my-comp.hbs
<h2>Practice Iterate over RecordArray and Add items</h2>

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

<button type="button" >Add an object</button>

Lastly, my accompanying MyComp component class:

// components/my-comp.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { A } from '@ember/array';

export default class MyCompComponent extends Component {
  @tracked myRentals = this.args;

  @action
  addRental() {
    this.myRentals.pushObject({
      title: "My new rental"
    });
  }
}

Here is what the rendered component looks like:

Rendered component

What I expect is that when I click that "Add an object" button, it creates a new Rental record, and it appends that Rental record to the existing RecordArray. Since that RecordArray is tracked, the component template re-renders, and thus the new record's title attribute displays in the template.

When I click the Button, it returns this error in Web Inspector:

Uncaught TypeError: this.myrentals.pushObject is not a function at MyCompComponent.addRental

I did reference the Ember JS Looping Through Lists Guide. I am clearly missing one or more concepts at work here.

Thanks in advance!




DropDown List Ember On Pressing Cancel button should roll back

So I have a dropdown list and on action it make a secondary dialog where it have two button confirm and cancel On cancel I want the old ember dropdown to come .Is there any way to achieve .I tried by setting the current active one as false and the old one as true but it's not working.




vendredi 24 juillet 2020

Ember.js, FontAwesome & Sass

I have an Ember.js project where I use Fontawesome5 and Sass. Creating an icon is easy with <FaIcon @icon="..."/>. But now I want to use an icon from Fontawesome with Sass (more specifically with list-style). I guess I could use the way it is described in the fontawesome-sass-documentation, but this feels wrong in more than one way.

I tried to create a route get-icon, that I could use with list-style: url(...), but as far as I see that can't work with ember.js.

So is there a preferred way to get a fontawesome icon for list-style in an ember project?




Transition to Octane: replace addObserver design

Service requests performed by a service currently trigger "notifications" that components listen to using addObserver pattern ie the aService just toggles its _property and components act on it using aService.addObserver('_property'){action...}. How can I redesign this pattern in Octane, please? Thank you. Karel




jeudi 23 juillet 2020

How to define a relationship with two dimensional array of objects in Ember Data

Am new to Ember and still trying to learn its ways. I have two data models say 'foo' and 'bar' in my application. If a foo object has an attribute which is a two dimensional array of items of type 'bar', how do I define the relationship in foo? I am aware of using a hasMany relationship if it is a single dimensional array but am stumped on how to do handle the current scenario in the right way. Appreciate any help! am using Ember 3.8 btw




"hasMany is not defined" error. Reflexive relationship in Emberjs

I get this error when I click a link to a route that retrieves the model with a reflexive relationship.

Uncaught ReferenceError: hasMany is not defined

This is my model in Ember

// app/models/section.js
import Model, { attr } from '@ember-data/model';

export default class SectionModel extends Model {
  @attr('string') title;
  @attr('string') body;
  @attr('number') order;
  @attr('string') slug;
  @hasMany('section', { inverse: 'superior' }) subsections;
  @belongsTo('section', { inverse: 'subsections' }) superior;
}

This is my route

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

export default class DocsRoute extends Route {
    model() {
        return this.store.findAll('section');
    }
}

This is my rails model in the backend

# app/models/section.rb
# frozen_string_literal: true

class Section < ApplicationRecord
  validates_presence_of :title
  extend FriendlyId
  friendly_id :title, use: :slugged

  validates :order, numericality: { only_integer: true }
  default_scope -> { order(:order) }

  has_many :subsections, class_name: "Section",
                          foreign_key: "superior_id"
  belongs_to :superior, class_name: "Section", optional: true

  scope :root, -> { where(superior: nil) }
end

This is my serializer

# app/serializers/section_serializer.rb
# frozen_string_literal: true

class SectionSerializer < ActiveModel::Serializer
  attributes :id, :title, :slug, :body, :order
  belongs_to :superior
  has_many :subsections
end



SASS: How to substitute imports before build (Ember project)

I have Ember JS project and the main scss file (app.scss), I have an ENV variable (STYLE_NAME).

I need to replace the content of app.scss pasting @import 'STYLE_NAME'; Where STYLE_NAME - a string from process.env.STYLE_NAME;

I have lot of 'STYLE_NAME' scss files in the same folder.

so, by executing the console command "env STYLE_NAME=theme1 ember build", I need to get app.scss with the following content:

...
...
...

@import 'theme1';
@import 'main'; // this import is always the last one



mercredi 22 juillet 2020

Pass variable as a window parameter from node JS

I want to pass one variable to my client (EmberJS) as a window parameter using node JS. Does anyone know how can I do that securely?




Ember JS ways to action in engine from another engine

Consider this situation, I have a engine A and engine B. I try to call/reuse the method/actions in engine A from engine B. Is it is possible? If possible what are the way to call the method/actions in ember js?




mardi 21 juillet 2020

How to share the style guide to ember engines

I am working on an ember project where we have a style guide and we are trying to make that available to our app. The app has a number of engines and I am creating an in-repo addon that will have shared components.

I'm trying to add the style guide to the shared addon and make the styles available/accessible to the host app, the engines, and the components in the shared addon.

Can someone provide me some inputs on this?




Things which are need for run ember without ember-cli?

I am new to emberjs. Can anyone tell how to create ember pages without using ember-cli?




highcharts.js and exporting.js version problem

I'm using highcharts v4.1.9. Currently, I'm in need of exporting highcharts in a pdf or whatever. The problem starts when I include exporting.js file on my website.

exporting.src.js:31 Uncaught TypeError: Cannot read property 'parts/Chart.js' of undefined

Uncaught TypeError: $(...).iCheck is not a function

These were the console error. I guessed this is due to version mismatch b/w highcharts.js and exporting.js (not sure though) so I tried looking for any lower version of exporting.js but no luck. please suggest a way to solve this without updating the highcharts version. Thank you in advance:)




lundi 20 juillet 2020

Ember.js .refresh() not refreshing my page

I am working in an old ember app and the functionality of what I am working on is that a modal is open, tags are selected and the modal is closed. The close modal action uses send to an action in the photos controller that has a refresh action on it but my computed properties in that controller are not getting rerun. I need the quickSearchTagNames computed property to rerun in order to fetch the new tags to display on this page. From reading the Ember docs it was my understanding that calling refresh in the controller should refresh that page.

favorite tags route:

 close() {
        console.log("TRANSITION")
        this.send("sessionChanged");
      },     

photo route

sessionChanged: function() {
      console.log("Photo session change")
      this.transitionTo('franchisor.photos.index').then(() => {
        this.refresh();
      });
    }

computed property that is not reloading after refresh in the photos controller

quickSearchTagNames: Ember.computed('franchisor.id', function() {
      var franchisor = this.get('franchisor');
      var franchisorID = franchisor.get('id');
      const favoriteTagsPromise = this.get('favoriteTags').index({
        franchisorID
      });
console.log("IN quickSearchTagNames")
      const tagNamesPromise =
        favoriteTagsPromise.then(favoriteTags => favoriteTags.filter(tag => tag.get('favorite') === true).map(tag => tag.get('tagName')));
        console.log("tagNamesPromise", tagNamesPromise)
      return DS.PromiseArray.create({
        promise: tagNamesPromise
      });
    }),



Deploying ember_node

Am new to web development and am using ember node express and mongodb.in development I used two severs and used the fetch API in linking my frontend and backend. Am ready deploy my app, but confuse about ember build and integrating it with my backend.




Source Code for Completed Example Apps Built within ember.js Guides

I am working through the Ember Guides. I'm working through the "chat app" that they demonstrate throughout the Components section of the guides.

I'm currently on the Looping through lists page and my app is breaking on me, so I'm trying to see if the completed application source code is somewhere that I can reference.

The closest I found was the markdown of the guides themselves, but not the source code in its entirety of this example "chat app" that is built throughout the Components section of the guides.

Question: Does the source code of the completed example "chat app", referenced in the Components section of the Ember guides, exist somewhere?




dimanche 19 juillet 2020

Ember 3.19 Proper way of updating a record and saving it in an API

I have a small Tic Tac Toe game, and I have a scoreboard functionality. I made a Rails API that will hold a global list of these scores.

What is the proper way for me to update the records on my Rails backend from Ember?

Currently what I'm trying to get to work is:

In my application.js route I have

async model() {
    return {
        score: this.store.findAll('score')
    }
}

My game router has

model() {
    return {
      score: this.store.peekAll("score")
    }
  }

In my game.hbs template, I have a button with an onClick sendScore() method in the game.js controller. This method will look at the store for a specific username (users can enter a username under which their scores will be kept in the rails DB), and upon finding the user what it should be doing is setting the scores for this user to be equal to a localStorage item.

sendScore() {
    const entry = this.store.peekAll('score').filterBy("username", localStorage.getItem("username"))[0]
    entry.wins = parseInt(localStorage.getItem("wins"));
    entry.losses = parseInt(localStorage.getItem("losses"));
    entry.draws = parseInt(localStorage.getItem("draws"));
    entry.save();
}

But this doesn't work.

As an example of what currently happens

I start off with a username "damion" that has 150 wins, 146 draws and 318 losses.

If I console.log entry.wins after the entry.wins = parseInt..., the record has clearly updated with whatever is in localStorage. However, upon calling entry.save(), the PATCH request that gets sent out by Ember has values that are unchanged from what it originally was.

What is the proper way of doing this?

EDIT: My Ember Data score model looks like this

import Model, { attr } from '@ember-data/model';

export default class ScoreModel extends Model {
  @attr username;
  @attr wins;
  @attr draws;
  @attr losses;
}

Very simple model. My adapter just has host = localhost:3000 and nothing else in it.

ember-source and ember-data are both version ~3.19.0

I also checked using entry.changedAttributes() in the line before I call my save(), and sure enough Ember can see that I changed my values.

draws: (2) [146, 0]
losses: (2) [318, 5]
wins: (2) [150, 56]



Handling validation errors in ember and rails

Recently, I switched to using ember as my frontend framework from react. I am saving tons of time writing ember although I am new at ember. Like in every app, validation errors needs to be addressed and I'm having a tough time. I have read multiple articles still some parts don't click and hence this question.

I have a rails backend API server that renders API in json api format as expected by ember. The errors are rendered like:

{
  "errors": [
    {
      "detail": "Title can't be blank",
      "source": {
        "pointer": "data/attributes/title"
      }
    }
  ]
}

I have a ember controller with all the logic and I'm not sure if this is the right place to submit forms etc

// controllers/categories/new.js

export default class CategoriesNewController extends Controller {
  @service store;

  @tracked title = "";
  @tracked description = "";
  @tracked errors = [];

  @action submitData(e) {
    e.preventDefault();
    let category = this.store.createRecord("category", {
      title: this.title,
      description: this.description,
    });

    let self = this;

    category.save().then(
      () => {
        self.transitionToRoute("categories");
      },
      () => {
        self.errors = category.errors.get("title");
      }
    );
  }
}

and an ember template file like

# templates/html/new.hbs

   <p class="mt-1 text-sm font-medium text-red-700">
      
   </p>

This is only the error handling part. I'm sure this is not the correct way to handle validation errors. This article handles error on the model file and I'm not sure how? Can anyone please guide me? Thanks.

PS: I am using ember-cli 3.19.0.




vendredi 17 juillet 2020

Removing console logging from Ember etc apps

Wondering if there’s any built-in way or addon for removing console output from production builds of Ember apps.... I do a lot of debugging via console statements and sometimes these get a bit weird and would like to fid an easy way to remove the chance of this cruft making it into production builds.




Sticky chat box with new version of ember js

I am trying to build a chat with new version of ember js and had a issue with scroll bar On chat body basically what I need is When the user is scrolled to the bottom, new messages should show up. If they scroll up to read old messages, how to get this scenario can anybody help




EmberJS 3.19 PATCHes initial data instead of new data

I have a local-score model

export default class LocalScoreModel extends Model {
  @attr username;
  @attr wins;
  @attr draws;
  @attr losses;
}

I display this local-score model in a scoreboard template. This is the Scoreboard route

export default class ScoreboardRoute extends Route {
  async model() {
    return {
      localScore: this.store.findAll('local-score')
    }
  }
}

The data gets fetched fine and it's all as it should be, no problems there. However, I'm trying to test out some things and created a button that will increase or decrease the draws in my model.

The scoreboard controller looks like this

  @action
  changeDraw(amount) {
    this.store.findRecord("local-score", 1).then((score) => {
      score.draws += amount
      score.save();
    })
  }

What happens, though, is that while the score.wins does change its amount, upon hitting score.save(), for some reason it resets and what ends up happening is that Ember will send a PATCH with the original values instead of the new ones.

If I do something like this:

  @action
  changeDraw(amount) {
    this.store.findRecord("local-score", 1).then((score) => {
      console.log("Before += ", score.draws);
      score.draws += amount;
      console.log("After += ", score.draws);
      score.save();
      console.log("After save() ", score.draws);
    })
  }

The output is

Before +=  1000
After +=  1001
After save()  1001

Checking the Network tab when I click the button, I actually have 2 requests show up:

First, a GET request gets sent to the API. AFTER the GET, my PATCH gets sent, and obviously now the records go back to their original values which is why the PATCH sends out the old data.

What might be causing this initial GET request?




mercredi 15 juillet 2020

Ember websocket/new object collision workaround clobbering hasMany promise

I have an Ember 3.8 app that uses Ember Data 3.8 and a websocket. We use the standard Ember Data API to preload data in Routes before processing, and for creating and deleting records. We also push all relevant updates to the database back to the browser through a websocket, where we pushPayload it into the store.

This pattern doesn't seem too uncommon - I've seen people discuss it elsewhere. A common problem with this pattern, however, is how to handle the collision when you are creating a record and the websocket sends down a copy of this new record before your POST resolves. Normally a pushPayload would simply update the record already existing with the payload's ID. For a record mid-save, the pushPayload creates a new record. Then when the POST returns and Ember Data tries assigning the ID to the pending record, it discovers there was already a record with that ID (from the websocket) and throws an exception.

To get around this we wrapped createRecord in some code that detects collisions and unloads the existing record with the ID so the pending record can be the true instance.

This worked well for a while, but now we're getting some odd behavior.

One of the models we create this way is the target of an async hasMany from another model. Example:

model-parent: {
 children: hasMany('model-child', {async: true}),
}

When we have a collision during a save of 'model-child', the PromiseManyArray returned by get('children') is destroyed, but the content of the PromiseManyArray is not. Further, the parent.get keeps returning this destroyed PromiseManyArray. Later we try binding a computed to it, which throws an exception trying to bind to the destroyed PromiseManyArray.

eg:

> modelParent1.get('children').isDestroyed
true
> modelParent1.get('children').content.isDestroyed
false
children: computed('modelParent1.children.[]')
^^^ blows up at controller setup time when trying to add a chainwatcher to the destroyed PromiseManyArray

I've tried reloading the parent object and also reloading the hasMany to get a 'fixed' PromiseManyArray but it still returns the broken one.

I know this is a pretty specific setup but would appreciate any advice for any level of our issue - the websocket collision, the broken hasMany, etc.

I wouldn't know where to being creating a twiddle for this, but if my workaround doesn't actually work I'll give it a shot.




compile handlebar in javascript side of the ember component

For the optimisation and quick rendering I need to be able to compile html in javascript side of the component. In ember 1.x we could do something like this https://api.emberjs.com/ember/1.0/classes/Ember.Handlebars, But in Ember 3.x I cant see compile function when I use Ember.Handlebars.compile()

What is the best way of doing that? Thanks




EmberJs: how to dynamicaly inject data into ENV?

I need to dynamically inject some data before build stage.

In my config/environment.js i have:

module.exports = function(environment) {
  environment = 'production';
  var ENV = {
    APP: {
      API_HOST: 'https://apihost1.com,
      secret: 'key1'
     }
   };
  return ENV;
};

How do i can to dynamically change "APP" object to something else:

    APP: {
      API_HOST: 'https://apihost2.com,
      secret: 'key2'
     }

before build according to an executing command in my package.json?

"scripts": {
    "build 1": "$CONFIG_NAME ember build",
},

I was thinking about npm scripts but could not implement that. Is anyone has a solution for it?




mardi 14 juillet 2020

fetch request's http version is undefined. how to fix this?

In my ember app I'm using native Javascript fetch-method (after user clicks login at login-form) to request a POST to a server-endpoint.

    //...
    const options = {
      body,
      headers,
      method: 'POST'
    };

    return new RSVP.Promise((resolve, reject) => {
      fetch(url, options).then((response) => {
        response.text().then((text) => {
          try {
            let json = JSON.parse(text);
            if (!response.ok) {
              response.responseJSON = json;
              reject(response);
            } else {
              resolve(json);
            }
          } catch (SyntaxError) {
            response.responseText = text;
            reject(response);
          }
        });
      }).catch(reject);
    });
    //...

If the ember-app is loaded freshly, the first login-click results in an error. The reason seems to be, that the HTTP-Version is undefined at the error-requests. See: enter image description here ember-server output:

enter image description here

If the app is not loaded freshly, fetch works as expected: enter image description here ember-server output:

enter image description here

What could be the reason that the http-version is undefined? How I can set the HTTP-Version?




Add AND condition in Handlebars/HtmlBars template

In my Ember project, I have a button as below;


Currently I have the "enabled" property based on gridItems.length < maxRecordsInGrid I want to add a 2nd condition to this i.e. if a property called "enableBtn" is true

So, essentially, I want the "enabled" property to be an AND between;

  1. gridItems.length < maxRecordsInGrid
  2. enableBtn is true

Is it possible to do this directly in the template using some inbuilt HTMLBars condition without the need of explicit helpers?




lundi 13 juillet 2020

EmberJS testing: Testing a component inside a component

I'm new to Ember, and I'm trying to learn how to write tests.

At the moment I have a component, lets call it "ParentComponent" and to simplify, it looks like this.

<div>
    <div class="childDiv">
        
    </div>
    <div>
        other stuff
    </div>
</div>

I am writing an integration component test on ParentComponent and I would like to test to make sure "trait" is true. someBoolean is determined inside the ParentComponent, and can be true or false. At the moment my test looks something like this:

test('my test', async function(assert){
    this.set('someBoolean', true)
    await render(hbs`
    
    `)
    
    // insert code here
});

At the "insert code here", I'd like to be able to check that childComponent's "trait" is indeed equal to true.




dimanche 12 juillet 2020

include highcharts as a html or image in an export pdf

I have to send email to my clients with an attachment that contains a highchart, an unordered list (side by side) and a table below these two! I've gone through many answers that exports highcharts. But I would like to include the highchart as an image inside the pdf and continue including unordered list and table. I'm using ember.js! Please help me with this:(




vendredi 10 juillet 2020

How to use ember.js files in tomcat server?

I'm very new to ember.js. I using java as back-end as language. There is any tutorial for using Tomcat and ember.js. Thank you in Advance.




jeudi 9 juillet 2020

While creating components on ember. Skipping .js file?

If i run below, comment for generating component in ember.

$ ember generate component my-new
installing component
create app\components\my-new.hbs
skip app/components/my-new.js
tip to add a class, run ember generate component-class my-new
installing component-test
create tests\integration\components\my-new-test.js

It doesn't create both componentName.js and template files. How to solve it?




Ember invoke jQuery code only on initial render

In my Ember component class, I want to run some jQuery code to hide some elements. However, I want this code to run only on initial render and not on other events (say grid refresh)

hidePositionElements: function() {
    var self = this;
    var currPosLabelElements = $( ".my-grid-footer-value:contains('" + self.nls('current_position__label') + "')");
    currPosLabelElements.hide();
},

I tried adding to "didRender", but that runs multiple times.

The other thing I need to consider is the access to a property on my component instance from within this jQuery code i.e. self.nls('current_position__label')




mercredi 8 juillet 2020

ember-cli: how to prevent incremental storybook builds when running `ember test -s`?

When running ember test -s, after any file save, storybook will incrementally build and slow down testing a lot. Is there a way to prevent incremental storybook buildings when running ember test -s?

Below is a screenshot of storybook building after a file save when running ember test -s

screenshot of storybook building after a file save when running ember test -s




ember-intl for translating html

I'm using ember-intl and would like to translate html (href with link):

en-us.json:

{
   "sign-up": "Didn't get it? check your spam folder, or try to '<a {myLink}>'send a new passcode'</a>'",
}

My controller has an action that is called: signUp:

actions: {
    signUp: function() {
      console.log('success');
    },
}

In my hbs file, I tried:

}

The text was set, and the link looks as a link, but when I click on this link, the log is not written.

Any help appreciated!




samedi 4 juillet 2020

I got issue with ember application after cloning disk

I began to learn ember and did working app. It was working well. Then I had to change my hard disk to ssd by cloning my old disk/ After cloning i restore my ember app from bup and tried to start it. And got error.

C:\inetpub\tracker> npm start

> tracker@0.0.0 start C:\inetpub\tracker
> ember serve

The "id" argument must be of type string. Received undefined


Stack Trace and Error Report: C:\Users\tnfoms\AppData\Local\Temp/error.dump.90e842d8b8af33fd44bc24b48197a6bd.log
An error occurred in the constructor for ember-data at C:\inetpub\tracker\node_modules\ember-data

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! tracker@0.0.0 start: `ember serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the tracker@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tnfoms\AppData\Roaming\npm-cache\_logs\2020-07-04T17_45_40_052Z-debug.log

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.14.4
3 info using node@v12.18.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle tracker@0.0.0~prestart: tracker@0.0.0
6 info lifecycle tracker@0.0.0~start: tracker@0.0.0
7 verbose lifecycle tracker@0.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle tracker@0.0.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\inetpub\tracker\node_modules\.bin;C:\Python38\Scripts\;C:\Python38\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Brackets\command;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files\nodejs\;C:\ProgramData\chocolatey\bin;C:\Program Files\watchman;C:\Users\tnfoms\AppData\Local\Microsoft\WindowsApps;C:\Users\tnfoms\.dotnet\tools;C:\Users\tnfoms\AppData\Local\atom\bin;C:\Users\tnfoms\AppData\Roaming\npm;C:\Users\tnfoms\AppData\Local\Programs\Git\cmd
9 verbose lifecycle tracker@0.0.0~start: CWD: C:\inetpub\tracker
10 silly lifecycle tracker@0.0.0~start: Args: [ '/d /s /c', 'ember serve' ]
11 silly lifecycle tracker@0.0.0~start: Returned: code: 1  signal: null
12 info lifecycle tracker@0.0.0~start: Failed to exec start script
13 verbose stack Error: tracker@0.0.0 start: `ember serve`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:315:20)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:315:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid tracker@0.0.0
15 verbose cwd C:\inetpub\tracker
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.18.0
19 verbose npm  v6.14.4
20 error code ELIFECYCLE
21 error errno 1
22 error tracker@0.0.0 start: `ember serve`
22 error Exit status 1
23 error Failed at the tracker@0.0.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

I tried to reinstall node, ember but unsuccessfully




mercredi 1 juillet 2020

Ember-Data "Error: Assertion Failed: You made a 'findRecord' request for a 'user' with id 'current', but the adapter's response did not have any data"

I'm using Ember 3.17 and trying to set up Ember Data to make a server call using the JSONAPIAdapter, however I keep getting this error:

Error: Assertion Failed: You made a 'findRecord' request for a 'user' with id 'current', but the adapter's response did not have any data

Am I doing something wrong with my adapter?

Below find my adapter, route and the expected data for this call (I have a model set up, with one attribute). The only thing that's a little weird is my endpoint is /users/current but current does not match the ID on the object. (However when I do match the ID, which is a valid endpoint, I get the same error)

adapters/application.js

import JSONAPIAdapter from '@ember-data/adapter/json-api';
import ENV from 'rendia-tv-web/config/environment';

export default class ApplicationAdapter extends JSONAPIAdapter {
  host = ENV.APP.API_HOST;
  namespace = 'tv/v1';

  headers = {
    'Authorization': <authHeader>,
  };

  ajax = function(url, method, hash) {
    hash.crossDomain = true;
    hash.xhrFields = {withCredentials: true};
    return this._super(url, method, hash);
  }
  
}

routes/application.js

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

export default class ApplicationRoute extends Route {

  @service store;

  async model() {
    return this.store.findRecord('user', 'current');
  }

}

expected data

{
    "data": {
        "id": "12345",
        "type": "users",
        "attributes": {
            "username": "email@email.com",
            "name": "User 1"
        },
        "relationships": {
            "practice": {
                "data": {
                    "type": "practice",
                    "id": "55555"
                }
            }
        }
    },
    "included": [
        {
            "type": "practice",
            "id": "55555",
            "attributes": {
                "date_created": "2016-09-23T04:21:38-04:00",
                "name": "Practice Name",
                "expiration_date": "2024-10-23T23:59:59-04:00"
            }
        }
    ]
}

Any help is appreciated, thanks!