samedi 24 décembre 2022

cordovaProj.create is not a function with Emberjs + corber

I'm trying to add corber to my existing EmberJS application. When I run corber init then I get

stack: TypeError: cordovaProj.create is not a function at Class.run (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/lib/targets/cordova/tasks/create-project.js:33:26) at /Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/lib/tasks/create-project.js:97:24 at tryCatcher (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:326:21) at invokeCallback (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:498:33) at publish (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:484:9) at flush (/Users/denisk/.nvm/versions/node/v18.12.1/lib/node_modules/corber/node_modules/rsvp/dist/rsvp.js:2441:7) at process.processTicksAndRejections (node:internal/process/task_queues:77:11)

My env is:

ember-cli: 4.9.2 node: 18.12.1

How can I add corber and build mobile app with Ember?




lundi 19 décembre 2022

How do i get the ember-concurrency ajax-throttling example to work in my dev environment?

My question is, what do i need to fix so that my implementation of the ember-concurrency Ajax Throttling example works as expected. Specifically, in my implementation no log entries are displayed (as they are on the example page), and the console.log statement that i added in the loopingAjaxTask inner function is not executed nor is the console.log statement in the task. I have copied the example nearly verbatim with the only changes being that i've added in those console.log statements.

The line 'looping Ajax task outer function' is written to the console 8 times as expected, but the 'looping Ajax task inner function' is never written to the console log. The 'Hello World' text from the component is written to the page.

I am using ember 4.8 and ember-concurrency 2.3.7.

Here's the template where i've included the AjaxThrottling component.

app/templates/example.hbs


<p>Here's where the log entries should appear</p>
<AjaxThrottling />
 

app/components/ajax-throttling.hbs

<div>
    hello world
  <ul>
    
      <li style= ></li>
    
  </ul>
</div>

and here is component's js page

import Component from '@glimmer/component';
import { enqueueTask, task, timeout } from 'ember-concurrency';

function loopingAjaxTask(id, color) {
    console.log('looping Ajax task outer function');
    return function* () {
        console.log('looping Ajax task inner function');
        while (true) {
        this.log(color, `Task ${id}: making AJAX request`);
        yield this.ajaxTask.perform();
        this.log(color, `Task ${id}: Done, sleeping.`);
        yield timeout(2000);
      }
    };
  }

export default class AjaxThrottlingComponent extends Component {

    tagName = '';
    logs = [];
  
    ajaxTask = enqueueTask({ maxConcurrency: 3 }, async () => {
      // simulate slow AJAX
      console.log('inside the task')
      await timeout(2000 + 2000 * Math.random());
      return {};
    });
  
    @task({ on: 'init' }) task0 = loopingAjaxTask(0, '#0000FF');
    @task({ on: 'init' }) task1 = loopingAjaxTask(1, '#8A2BE2');
    @task({ on: 'init' }) task2 = loopingAjaxTask(2, '#A52A2A');
    @task({ on: 'init' }) task3 = loopingAjaxTask(3, '#DC143C');
    @task({ on: 'init' }) task4 = loopingAjaxTask(4, '#20B2AA');
    @task({ on: 'init' }) task5 = loopingAjaxTask(5, '#FF1493');
    @task({ on: 'init' }) task6 = loopingAjaxTask(6, '#228B22');
    @task({ on: 'init' }) task7 = loopingAjaxTask(7, '#DAA520');
  
    log(color, message) {
      let logs = this.logs;
      logs.push({ color, message });
      this.set('logs', logs.slice(-7));
    }
}




vendredi 16 décembre 2022

Specifying a different template path for an ember component

Suppose I have this structure:

modals/
├─ index.hbs
├─ base.ts
├─ new/
│  ├─ index.ts (extends base.ts)
├─ rename/
│  ├─ index.ts (extends base.ts)

(Basically I have two components which have exactly the same template, but different logic within the .ts/.js files)

Is it possible to specify the template path in both of those index.ts files to point to the index.hbs which is located one level above?

Or something similar, the idea is to not have to duplicate the template between those two components.

I've tried the structure above but it does not seem to work. I imagine I must specify a template path somewhere but I just can't find something like that in the documentation.




Is `store.find` function different to `store.findRecord` function on Ember JS?

There are two similar functions on Ember JS service "store". In this example they work alike.

find function

  @service store;

  async model(params) {
    return this.store.find('rental', params.rental_id);
  }

findRecord function

  @service store;

  async model(params) {
    return this.store.findRecord('rental', params.rental_id);
  }

Are they different? Or just an alias?




vendredi 9 décembre 2022

Socket hangup error while proxying my local ip using wsl

im running wsl for proxying the ember project it raising the socket hangup exception when only i use local ip of wsl by this command "cat /etc/resolv.conf" But i use remote ip like vpn's ip it will be working fine and other ip's of others working fine. when only using my local ip it throwing an eroor [enter image description here](https://ift.tt/Yteo7rPenter image description herem/yP0pw.png) see the images attached to understand my problem.

i want to run fine as i attached images when give local ip but here i gave vpn ip [enter image description here]enter image description here kindly, give any solution for this




dimanche 27 novembre 2022

How to access child component from parent component in Ember

The concept is fairly simple.

Assume I have a child component with its own separate js and hbs. Child-component.hbs =>

<Button options =  selected=
> Submit <Button

Child-component.js

listOptions =[{id: 124, name: 'Mywork'} selected => performing an action after getting the value from hbs selection.

Now I'm importing this into another component Main-component.hbs like this

<ChildComponent />

This is rendering as expected with options and all, but based on the selectedOption I want to do something in my main component. Handling the action in the Main-component is not an option for me as its not what I was told to do. Is it possible to access selectedOption from the main-component? Kindly help.

Please note that I want to achieve this in Octane version.




vendredi 25 novembre 2022

Does an ember package imported component use its parents library version?

  • I tried to use a component from an imported package inside a class in ember.
  • I expected the component to use it's own version of ember-intl.
  • It resulted in the imported package using the parents version of ember-intl.

I have ember-intl 5.7.0 in parent and 4.3.0 used in an imported package.

There is a component called <Calendar> from the imported package used in a parent class which has a string that looks like: "{Date} was selected for <span class='exampleName'".

4.3.0 will handle this string fine but 5.7.0 will fail as the major version change was that apostrophes were made into escape characters :[

node_modules shows that the child package resolves to 4.3.0 but during runtime it fails due to the apostrophe.

The imported component uses a service by injecting it:

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

intl: service()

I've added logging to both versions to see which is used and it is the parent version. I would prefer not to downgrade the parent or alter the child library.

Can anyone explain why this is happening?

If any more info is needed, let me know, thanks.




mardi 22 novembre 2022

How to create a dependency graph of components in Ember?

I'm trying to navigate through a large Ember project and would like to create a visual graph of the component tree.

Is there a way to parse a .hbs file and create a dependency graph of the components and sub-components in it?

Is there a way to do the same for an Ember route?

What I've found




jeudi 17 novembre 2022

asynchronous/non-blocking Javascript

I am trying to make the existing code to async/non-blocking code. Can anyone help me with this? This is in route.js

async model(params) {
    let userCertificate = await Certificate.findByPublicId(this, params.certificate_public_id, { competencies: true }),
      product,
      competency,
      user = await User.find(this, userCertificate.user_id);

    if (userCertificate.granted_by_product_id) {
      product = await Product.find(this, userCertificate.granted_by_product_id);
    } else if (userCertificate.granted_by_competency_id) {
      competency = await Competency.find(this, userCertificate.granted_by_competency_id);
    }

    await userCertificate.fetchFileData(this);

    return { userCertificate, product, competency, user};
  }



mardi 15 novembre 2022

Ember invoke a component function from another component in same engine parent

my requirement is to use component actions from another component.Need to know whether it is possible to use data-down for this case.

Say,

I'm trying to invoke first-component from here engine/addon/templates/application.hbs like below

engine/addon/templates/application.hbs

    
    <FirstComponent action=actionFromSecondCompo/>
    

From this FirstComponent i want to invoke, second-component function handled in

engine/addon/components/SecondComponent.js

actionFromSecondCompo(){
 console.log("Print Invoked secondcomponent");
}

Note: Both components are in same engine parent
i've tried to use **extend** the firstComponent in secomdCompo js like below.

>>engine/addon/components/SecondComponent.js

import FirstComponent from 'engine/components/FirstComponent'; export default FirstComponent.extend({


But issue here is, its invoking willDestroyElement() function from FirstComponent.Hence i don't need the changes handled inside this destroy function.



dimanche 13 novembre 2022

What is the difference between route and path in EmberJs

What is the difference between route and path in EmberJs

Router.map(function () {
  this.route('about');
  this.route('contact', { path: '/getting-in-touch' });
});



lundi 7 novembre 2022

Ember.js 4.4 classic template syntax

I would like to update a project built in Ember 3.28 without Octane to version 4.4.

I tried using ember-cli-update to change version and now all sorts of errors are thrown, such as template properties that must be used with @ and curly brackets components no longer supported...

I am new to Ember and I haven't understood if it is still possible to use the classic syntax on 4.4, if so, how can I continue to use the classic syntax? Especially on templates.

Thank you!




jeudi 3 novembre 2022

Chromium browser failing in docker container when running acceptance tests(visual regression backstopjs)

I've implemented visual regressions testing into our Ember project and everything has being going fine up until now. I've made about 150 of them and made sure all of them succeed. Now that I'm trying to deploy them I can't get them working in my docker container. I'm currently trying to just make one test run by building the docker container locally. I run this command to make the docker container the same as my local environment. I start the shell and then run ember backstop-remote to start a backstop server(required for working with backstop).

docker  run -it \                                                       
     -v "/home/michael/Documents/Projects/atlas":/var/www \
    -v ~/.ssh:/root/.ssh \
    registry.gitlab.com/getflights/docker-ember \
    /bin/sh -c "
    GITLAB_TOKEN=TOKEN yarn && sh"

After the docker container is running and has an instance of the backstop-remote server running aswell i will run this command: docker exec -it container-name ember test --filter="search" ci --silent --r xunit Here my test should normally succeed but instead i get this output after everything being built.

<testsuite name="Testem Tests" tests="1" skipped="0" failures="1" timestamp="Thu Nov 03 2022 14:15:30 GMT+0000 (Coordinated Universal Time)" time="3.014"><testcase classname="Chrome" name="error" time="0"><error message="Error: Browser exited unexpectedly&#10;Non-zero exit code: 1&#10;Stderr: &#10; Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted&#10;[1103/141529.926012:FATAL:zygote_host_impl_linux.cc(187)] Check failed: ReceiveFixedMessage(fds[0], kZygoteBootMessage, sizeof(kZygoteBootMessage), &amp;boot_pid). &#10;Received signal 6&#10;  r8: 00007ffeaac8f334  r9: 00007f74088d67e0 r10: 0000000000000008 r11: 0000000000000246&#10; r12: 00007ffeaac8fb00 r13: 00007ffeaac8fa3c r14: 00007ffeaac8f898 r15: 00000000000000a0&#10;  di: 0000000000000002  si: 00007ffeaac8f200  bp: 00007ffeaac8f200  bx: 0000000000000000&#10;  dx: 0000000000000000  ax: 0000000000000000  cx: 00007f740d06a9f3  sp: 00007ffeaac8f1f8&#10;  ip: 00007f740d06a9f3 efl: 0000000000000246 cgf: 002b000000000033 erf: 0000000000000000&#10; trp: 0000000000000000 msk: 0000000000000000 cr2: 0000000000000000&#10;[end of stack trace]&#10;Calling _exit(1). Core file will not be generated.&#10;&#10;"/></testcase></testsuite>
Testem finished with non-zero exit code. Tests failed.

The dockerfile for this setup is:

FROM node:14.17.1-alpine

VOLUME /var/www
WORKDIR /var/www

RUN apk update && apk add --no-cache git openssh curl chromium
RUN yarn global add bower
RUN yarn global add ember-cli

COPY install.sh /root/
RUN chmod u+x /root/install.sh

COPY fix-uid.sh /root/
RUN chmod u+x /root/fix-uid.sh && /root/fix-uid.sh
RUN ln -s /usr/bin/chromium-browser /usr/bin/chrome

CMD ember s

Alternatively I've also tried to change my dockerfile to how it's declared in backstopjs for when your tests don't work because the chromium browser exits. I use the same command to run as in the previous setup. This is the error i get:

<testsuite name="Testem Tests" tests="1" skipped="0" failures="1" timestamp="Thu Nov 03 2022 14:25:37 GMT+0000 (Coordinated Universal Time)" time="5.106"><testcase classname="Chrome" name="error" time="0"><error message="Error: Browser exited unexpectedly&#10;Non-zero exit code: 1&#10;Stderr: &#10; [1103/142536.505398:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.&#10;&#10;"/></testcase></testsuite>
Testem finished with non-zero exit code. Tests failed.

I have a different dockerfile setup as previously mentioned. I made it according to this: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md Running on Alpine sections. This is it:

FROM node:14.17.1-alpine

VOLUME /var/www
WORKDIR /var/www

RUN apk update && apk add --no-cache git openssh curl chromium
RUN yarn global add bower
RUN yarn global add ember-cli

COPY install.sh /root/
RUN chmod u+x /root/install.sh

COPY fix-uid.sh /root/
RUN chmod u+x /root/fix-uid.sh && /root/fix-uid.sh
RUN ln -s /usr/bin/chromium-browser /usr/bin/chrome

RUN apk add --no-cache \
    chromium \
    nss \
    freetype \
    harfbuzz \
    ca-certificates \
    ttf-freefont \
    nodejs \
    yarn
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
    PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser

RUN yarn add puppeteer@13.5.0

RUN addgroup -S pptruser && adduser -S -G pptruser pptruser \
    && mkdir -p /home/pptruser/Downloads /app \
    && chown -R pptruser:pptruser /home/pptruser \
    && chown -R pptruser:pptruser /app

USER pptruser

CMD ember s

If anything is missing, please let me know and I'll add it ASAP. Any help is greatly appreciated!




mardi 1 novembre 2022

Should I try an MSAL getTokenSilent() before any request for a protected resource?

I'm integrated the MSAL JS library with an EmberJS SPA. In the current implementation I have a getTokenSilent() call before a user requests a "protected" resource. This means that after a user Authenticates, they collect a new access token before the resource is requested.

Is this intended? Aside from an extra network request I don't see many drawbacks. It should allow for very short-lived access tokens and allow MSAL to check that a user is still in a "valid" state (ie they haven't had their account disabled) since they logged in.

I'm very new to OAUTH and MSAL so some guidance would be great.




lundi 31 octobre 2022

emberjs, how to bind method from controller to service?

I have big emberjs application and I need to start using ember service a little bit more. so I have a method in my controller that I want it to be available as a service in all the modals, and components where I inject the service.

but its not working, and with no error... si is this a good way to do this? why its not wotking?

so my method in the controller is:

openModalPrices () {
        //method in controller
    },

the service has another method:

openModalPricesFromService () {
        //method in service
    },

and in my INIT in the Controller I am binding like this:

init: function() {
   this._super(...arguments);
   this.get('priceService').openModalPricesFromService(this.openModalPrices.bind(this));
}



jeudi 27 octobre 2022

Ember - webpack returned errors to ember-auto-import

I tried switching from NPM to Yarn on a project built with Ember.js version 3.28. All the required dependencies seem installed correctly.

When I try to run or build the app with Ember CLI I get the following error:

Build Error (WebpackBundler)

webpack returned errors to ember-auto-import

Stack Trace and Error Report: /tmp/error.dump.10ee9f3c2877596ebfbf63516378bbee.log

I tried building and running multiple times and reinstalling dependencies.

I'm on macOS Monterey 12.6 M1 Pro.

Node version 18.10.

The same process when the dependencies are installed with NPM works fine.




mercredi 19 octobre 2022

Micro frontend using module federation with EmberJS

We would like to know the feasibility of WebPack module federation build system in Ember JS App for invoking federated code from Ember App to connect with other front end codebase developed in React JS or other SPA.

Basically, we would to implement Micro-frontend using module federation approach where multiple frontends are already developed on Ember js and reactJS. In addition to that, our usecase depends on deeplinking, datasharing between these microfrontends.

Based on our understanding EmberJS by default uses broccoli and doesn't have support for webpack, Which is essential for Module Federation approach to accomplish Micro Frontend.

Looking forward for some pointers here




mardi 18 octobre 2022

Why this.$ is not available in Ember Controller

Ember.$ is available in the controller whereas this.$ is not. But it is available in components. Ember.$(".loading-splash").hide(); is working on controller where as this.$(".loading-splash").hide(); is throwing an exception "this.$() is unavailable"




dimanche 16 octobre 2022

Can I create record in Ember without the record name

My Backend Rails API consumes POST requests in the form of

{
    "name": "Mark White",
    "email" : "mark@xyz.com"
}

Have tried this in Postman and this creates a record successfully.

In my ember frontend, Im using the following code to create a new record, from a form input:

app/routes/addUser.js

import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
        addUser(){
            let formData = {
                "name": this.controller.get('name'),
                "poster_url": this.controller.get('email')
            };

            let newUser = this.store.createRecord('user',formData);
            newUser.save();
       }
  }

});

which generates the request as

{
  "user": {
    "name": "Mark White",
    "email" : "mark@xyz.com"
  }
}

which my backend is not prepared to handle and throws an error.

Any way I can quickly conform to the json format that works for me in Postman.




vendredi 7 octobre 2022

Best practice in integrating JS framework single-page-app into Spring Boot?

I am looking for your thoughts as an experienced Spring Boot engineer that have integrated Vue.js/React/Angular/Ember etc as a Single Page App into Spring Boot.

What is the best way to integrate the SPA to Spring Boot framework?

I have previously implemented this as a single project with a single Spring Thymeleaf template in resource where the bundled js would be linked after NPM builds.

It worked, and it worked well, but there might be more streamlined ways out there. There were a lot of manual setup get it work, and I am wondering if any Maven/Gradle enhancements in this area.




dimanche 2 octobre 2022

How can i dynamically add an Input select element on click of a button in ember

Am creating an ember application where am in need of dynamicaly adding a select element which will have options fetched from a server. so the select elements look like this.enter image description here And instead of having all dropdown boxes predefined i need to add them dynamicaly like on a click of a button like( + add more). and each of those drop down boxes should contain the datas that is fetched from the server. my .hbs for the current drop down page is..

map.hbs

<center><h4>Map</h4></center>
<container class = "cond">

    <select class = "sel">
        
        <option value = ></option>
        
        
    </select><br>

I tried ember-dynamic-fields but its depracted and I couldnt able to use it.. and all other solutions on web or for ember way older versions.. nothing works on ember 4.6 so could anyone helpout?




mardi 27 septembre 2022

Listening to a service property change in an EmberJs Octane Component

I am wondering how on Emberjs Octane to fire a function in a component after a service property changes. Here is an example of how I did it before octane.

child-component.js before Octane

import Component from '@ember/component';
import {inject as service} from '@ember/service';
import {computed, observer} from '@ember/object';
import { isEmpty } from '@ember/utils';
import { on } from '@ember/object/evented';
export default Component.extend({

userAccount: service(),
childNavigation: service(),

whenUserChanges: on('init', observer( 'userAccount.user', 'childNavigation.{activeIgdiMeasure,currentChild}', function () {

        this.getChildItems();
    }))
})

Observers aren't recommended and @tracked isn't working on a service so I am not sure how to convert the whenUserChanges function to Octane.




jeudi 22 septembre 2022

Ember 4.6 Deployment problem -- router not routing

I'm doing my first deployment of an Ember app. I've managed to get the compiled app to load the main page with my navbar, but none of the links (which use the LinkTo builtin component) work.

I thought this might be an Apache problem so I wrote an .htaccess file to redirect all requests to the index.html file. With that, when I directly enter, for example:

http://localhost/myApp/user (user is a route)

I get the user index page. But none of the links on that page work either.

Ember Inspector shows that all of the routes appear to be available but I can't seem to access them using LinkTo.

Thanks for any help!




mardi 20 septembre 2022

Modifying Ember.js Components from Console

My company does A/B testing for clients who have sites built with various CRM/Middleware providers. One them uses a product built on the Ember.js framework. I do not have access to the source code for the site itself. I need to change the value of a selector component upon page load which I am planning on doing with a Javascript one-liner.

Unfortunately, I can't just change the value of the DOM element directly using document.getElementByID('selectorElement) as this won't trigger other events on the page. I tried using document.getElementByID('selectorElement).click() which had no effect on the page at all. I think it has to be done by interfacing with Ember directly, but I'm not very familiar with the framework.

As an example, imagine you were to navigate to https://guides.emberjs.com/release/. An answer to this question would be a script that can be run in the console that would change the version selector from the default to one of the other options.

The HTML for the component in question is below.

<select name="_name_" data-test-selector="_name_" data-test-form-field-input="_name_" aria-invalid="false" id="ember53-input" class="_inlineSelectInput_tuesss _selectInputBase_tuesss _inputBase_tuesss _inlineInputBase_tuesss _inlineSelectInput_tuesss _selectInputBase_tuesss _inputBase_tuesss _inlineInputBase_tuesss ember-view">
          <option disabled="" hidden="" value="">
              Select a type
          </option>
          <option value="Option1">
            Option1
          </option>
          <option value="Option2">
            Option2
          </option>
          <option value="Option3">
            Option3
          </option>
      
</select>



General questions on: Ember DDAU, Glimmer components (this.args), JavaScript getters and encapsulation

I work on an Ember team using ES5, Octane and Glimmer and am generally happy with the tech stack. I've written JavaScript webapps for about 12 years, doing fullstack work before that. I'm reviewing a bunch of code that somehow got merged into our solution (partially my fault because I didn't review the related PRs before they were merged) and am trying to settle an argument with the dev who wrote it.

This dev - who as an experienced dev should know better - built a whole section of our app that repeatedly does the following:

  1. Ember route gets this.model from the API and passes it as @model to a controller
  2. Ember controller passes @model to a child component as @model
  3. Ember component uses a JavaScript getter to create a "mask" or alias for part of the model: get localObject() { return this.args.model.parentObject; } and passes that getter (as this.localObject) to another child component. This getter is really just an alias because it does not apply any logic, it just makes typing the code faster for the dev.
  4. The second (or third or forth) child component receives the "masked" model as this.args.maskedModel, then uses another getter to mask that: get localModel() { return this.args.maskedModel; }, then the "final" child component directly mutates the passed-in property by calling set on it: set(this.localModel, 'someSubProperty', true);

Right now, the dev who used this antipattern ALL OVER the work they wrote is arguing that since this "works" that it's fine and it doesn't need to be refactored. I'm arguing this pattern breaks encapsulation, DDAU, misuses JavaScript getters and somehow forces two-way data binding across them and Glimmer's this.args object.

Personally, I don't even understand how this is working, since JavaScript getters and Glimmer's this.args object are both supposed to only allow one-way data binding. But somehow, when the child component mutates the passed-in objects from the parent (reaching across TWO different getters), the parent magically gets the updated object. Instead of directly mutating the passed-in objects, the child component should call a passed-in closure action from the parent and allow the parent to mutate the data.

I also think it is a misuse of JavaScript getters to use them as an alias to make referring to this.args.model.someObject easier (less typing), without applying any logic in the getter function. Ember has a computed property "alias" for this purpose, though I still think "aliasing" this.args.something in a component is a bad idea because it gives a dev the false notion they can directly mutate the alias, if they don't realize it is referring to a passed-in value from the parent.

I think all this bad code directly breaks Data Down, Actions Up in Ember, as well as the long-standing computer science principle of data encapsulation.

Does anyone know why this is working since ES5 getters and Glimmer's this.args object are supposed to be one-way and immutable? Is it a flaw in Ember/Glimmer? We are on Ember 3.28 now, is this fixed in a newer version? How can I explain to this developer, who is being stubborn on this, that this is a terrible way to write code??




lundi 19 septembre 2022

Sub set of list using Java Script

I am trying to create a sub set of the list from a given list.

For example, I have a list of fields which can be checked and unchecked. I am trying to create a sub list which will only have those items which are checked.

I am unable to create it using Javascript as I am very new to the language. Can someone please help me with it?

this.attributeCategoryOptions.forEach((el) => {
  el.description += ' Required';
});

if (this.args.formData.descriptionDefaultFieldId)
  this.descriptionDefaultFieldSelected = this.descriptionDefaultFieldOptions.find((el) =>
    this.args.formData.descriptionDefaultFieldId === el.id);

if (this.args.formData.iconUrl)
  this.iconUrlSelected = this.iconUrlOptions.find((el) =>
    this.args.formData.iconUrl === el.id);

if (this.args.formData.attributeDescriptionIdOptions != null) {
  this.attributeCategoryOptions.forEach((listItem) => {
    listItem.checked = false;
    this.args.formData.attributeDescriptionIdOptions.forEach((attr) => {
      if (listItem.id === attr.id) {
        listItem.checked = attr.checked;
      }
    });
  })



vendredi 16 septembre 2022

Difference between and in Ember JS

When I use did-update without wrapping using <div>, the action using in did-update fall into infinite loop. After wrapping with <div>, the problem has solved.

Here's an example code: (current is service which shows the current status)

Does not work: (when this.current.locationId changed, this.updateStates be executed infinitly)


Does work:

<div >
</div>

JS file:

@tracked property;

@action
updateStates() {
  //do something with `this.current.locationId`
  //change value of `property`
  //so template re-render cause of `property` changed
  ...
}

I guess the problem happens because of the tracking frame. But I can not exactly see why that kind of problem is happening.




jeudi 15 septembre 2022

Ember 4.6

Am I missing something in the following:

<select
  id=
  name=
  
>
  <option value="null">Select one ... </option>
  

  
  
  
    <option
      value=
      selected=
    ></option>
  
</select>

The selected option is not being identified when the is first loaded. The statements show that one of the records have @curVal and item.id having equal values. Using the and

typeof  get(item.id)

and the same for @curVal shows they are both strings.

I originally used ember-truth-helpers, with


but that never selects anything. So I wrote a local function:

@action
  areEqual(curval, itemId) {
    console.log('typeof curval', typeof curval);
    console.log('typeof itemId', typeof curval);
    return curval == itemId;
} 

but it never seems to be called. What am I doing wrong?




Brocolli Plugin ENOENT no such file auto-import-fastboot.js error

I randomly get the following error message when running the tests on an ember project, it doesn't happen all the time.

  - broccoliBuilderErrorStack: Error: ENOENT: no such file or directory, open '/tmp/broccoli-16293IqYV1TN4ouUv/out-402-bundler/lazy/auto-import-fastboot.js'
    at Object.openSync (fs.js:462:3)
    at Object.writeFileSync (fs.js:1384:35)
    at Bundler.addLazyAssets (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-auto-import/js/bundler.js:119:20)
    at Bundler.<anonymous> (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-auto-import/js/bundler.js:81:22)
    at Generator.next (<anonymous>)
    at fulfilled (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-auto-import/js/bundler.js:11:58)
  - code: [undefined]
  - codeFrame: ENOENT: no such file or directory, open '/tmp/broccoli-16293IqYV1TN4ouUv/out-402-bundler/lazy/auto-import-fastboot.js'
  - errorMessage: ENOENT: no such file or directory, open '/tmp/broccoli-16293IqYV1TN4ouUv/out-402-bundler/lazy/auto-import-fastboot.js'
        at Bundler
-~- created here: -~-
    at new Plugin (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/broccoli-plugin/index.js:7:31)
    at new Bundler (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-auto-import/js/bundler.js:32:9)
    at AutoImport.makeBundler (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-auto-import/js/auto-import.js:62:16)
    at AutoImport.addTo (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-auto-import/js/auto-import.js:72:38)
    at EmberApp.host.addonPostprocessTree (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-auto-import/js/auto-import.js:106:29)
    at EmberApp.toTree (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-cli/lib/broccoli/ember-app.js:1825:17)
    at module.exports (/home/jenkins/agent/workspace/project/embercli/projectName/ember-cli-build.js:113:20)
    at Builder.readBuildFile (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-cli/lib/models/builder.js:52:14)
    at Builder.setupBroccoliBuilder (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-cli/lib/models/builder.js:66:22)
    at new Builder (/home/jenkins/agent/workspace/project/embercli/projectName/node_modules/ember-cli/lib/models/builder.js:32:10)
-~- (end) -~-
  - errorType: Build Error
  - location:
    - column: [undefined]
    - file: [undefined]
    - line: [undefined]
    - treeDir: [undefined]
  - message: ENOENT: no such file or directory, open '/tmp/broccoli-16293IqYV1TN4ouUv/out-402-bundler/lazy/auto-import-fastboot.js'

VERSIONS:

  • ember-cli: 3.14.0
  • broccoli-asset-rev: 3.0.0
  • brotli: 1.0.9
  • node: 12.22.12



mercredi 14 septembre 2022

How to track getter change in other getter without computed - Ember js

I need to track the getter is loaded or not in other getter without @computed property. How can I do?

@computed('current.locationId')
get currentApplications() {
  const query = {
    locationID:     get(this, 'current.locationId')
  };
  
  return this.store.pagedArray(this.store.query('shift-application', query));
}

get applicationsLoaded() {
  return this.currentApplications.isFulfilled
}

I need to track currentApplications.isFulfilled without using @computed('currentApplications.isFulfilled').




fall into infinite loop in ember js

I need to get store data when some properties change. Property value exist in the service, so I re-execute function using . But this action fall into infinite loop when the service property value changes.

This is my code.

  • js file
export default class CurrentApplications extends Component {

  @service store;
  @service current;
  @service permissions;

  @tracked currentApplications = emberA([]);

  constructor() {
    super(...arguments);
    next(()=> {
      this.currentApplications.pushObject(this.loadCurrentApplications.perform());
    });
  }

  @task
  *loadCurrentApplications() {
    const query = {
      page:     this.currentApplications.length + 1,
      per_page: 10,
      from:     moment().subtract(1, 'minutes').format(),
      until:    moment().add(1, 'minutes').format(),
      state:    ["accept", "assigned", "cancelled", "superseded"]
    };

    const locationId = this.current.locationId;
    if (locationId) query.location_id = locationId;

    if (get(this, 'current.user.isStaff')) {
      set(query, 'user_ids', get(this, 'current.user.id'))
    }

    return yield this.store.query('shift-application', query);
  }

  @lastValue('loadCurrentApplications') currentApplicationsCurrentPage;

  @task
  *loadForNewLocation() {
    this.currentApplications.clear();
    this.currentApplications.pushObject(this.loadCurrentApplications.perform());
  }

  get applicationsLoaded() {
    return this.currentApplications.length &&
           !this.currentApplications.lastObject.isRunning;
  }

  get hasMorePages() {
    return this.currentApplications.length &&
           !this.currentApplications.lastObject.isRunning &&
           this.currentApplicationsCurrentPage.meta.page < this.currentApplicationsCurrentPage.meta.pages;
  }

  @action
  nextPage() {
    this.currentApplications.pushObject(this.loadCurrentApplications.perform());
  
}
  • hbs file

<div class="columns is-multiline dashboard__sidebar__row mb-0">
  <div class="column is-12">
  ...
  </div>
</div>

When the this.current.locationId changes, loadForNewLocation fall into loop execute. How should I solve this problem?




vendredi 9 septembre 2022

normalizeResponse must return a valid JSON API document:

Here is my Code:

Inside model:

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

export default class TodoModel extends Model {

@attr('number') userId;

@attr('string') title;

@attr('boolean') completed;

}

Inside Adapter:

import RESTAdapter from '@ember-data/adapter/rest';

export default class TodoAdapter extends RESTAdapter {

host = 'https://ift.tt/JlnM9Eq';

}

Inside Serializer:

import RESTSerializer from '@ember-data/serializer/rest';

export default class TodoSerializer extends RESTSerializer {

normalizeResponse(store, primaryModelClass, payload, id, requestType) {

    payload={
        "todos":payload
    }

    return this._super(...arguments);

}

}

Inside Route:

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

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

export default class HelloRoute extends Route {

@service store;

model() {

return this.store.findRecord('todo',1);

}

}

Error:

Error while processing route: hello Assertion Failed: normalizeResponse must return a valid JSON API document:

  • Top level of a JSON API document must be an object Error: Assertion Failed: normalizeResponse must return a valid JSON API document:

  • Top level of a JSON API document must be an object

(My point of View: The Error is coming while processing the Serializer, how to return a JSON API document from normalizeResponse function.)




The associated data from the list does not come to the content of the Proxy object of the model

I use ember-cli@3.27.0 , ember-data@3.27.1

There is a workshift.js model

import DS from 'ember-data';

export default DS.Model.extend({
  date: DS.attr(),
  timestart: DS.attr(),
  timeend: DS.attr(),

  house: DS.belongsTo('house'),
  responsible: DS.belongsTo('employee'),

  employeeOnWorkshift: DS.hasMany('employee-on-workshift'),
});

There are employee-on-workshift.js model

import DS from 'ember-data';

export default DS.Model.extend({
  workshift: DS.belongsTo('workshift'),
  account: DS.belongsTo('account'),
  employee: DS.belongsTo('employee'),
});

and employee.js model

import DS from 'ember-data';

export default DS.Model.extend({
  fio: DS.attr(),
  age: DS.attr(),
  phone: DS.attr(),
  datebirth: DS.attr(),
  telegram: DS.attr(),

  user: DS.belongsTo('people'),
  employeeOnWorkshift: DS.hasMany('employee-on-workshift'),
});

In route, I unload all the workshift and their associated employeeOnWorkshift data as an array.

import Route from './base-route';
import RSVP from 'rsvp';

export default Route.extend({
  model(params) {
    this.store.findRecord('workshift', params.id);
  },
  afterModel(models) {
    models.get('employeeOnWorkshift').forEach((employeeOnWorkshift) => {
      employeeOnWorkshift.get('employee');
      employeeOnWorkshift.get('employee.user');
    })
  }
});

Yes, I understand that loading additional models for each list item is a bad decision, but my goal is to figure out why the data is not displayed.

In the template, I'm just going through the model list and trying to get an employee.fio, but the data is empty


  

Although in the browser on the network I can see how the data of each employee for the employeeOnWorkshift list has been loaded: Requests to the backend

I checked the model e employee in the console. The Proxy object is returned there, in which, as I understand it, if isPending = false and isSettled = true, the content parameter will be filled with the Model object, but even after receiving the data, this does not happen.

Proxy {isFulfilled: false, isRejected: false, content: null, _belongsToState: {…}, _super: ƒ, …}
[[Handler]]: Object
[[Target]]: Class
  content: null
  isFulfilled: false
  isRejected: false
  _belongsToState: {key: 'employee', store: Store, originatingInternalModel: InternalModel,   modelName: 'employee'}
  _super: ƒ ()
  Symbol(INIT_FACTORY): undefined
  Symbol(OWNER): undefined
  isPending: true
  isSettled: false
  isTruthy: false
  meta: (...)
  promise: (...)
  isDestroyed: (...)
  isDestroying: (...)
  _debugContainerKey: (...)
[[Prototype]]: Class
[[IsRevoked]]: false

Please tell me what I'm doing wrong, why employee is not unloaded without crutches of this format:

    models.get('employeeOnWorkshift').forEach((model) => {
      model.employee.then(function (employee) {
        model.employee = employee;
      });
    });



mercredi 7 septembre 2022

Create progress bar from csv file in Ember.js

I'm new to Ember.js. I need to create single page application to display progress bar or gauge (they want something looks fancy) to show percent progress. The data is in csv file that will be used to display the percent progress. I'm trying to create this progress bar or gauge using Ember.js. I'm not able to find useful tutorials about using ember.js to display progress bars from csv file. I was only able to create new app using Ember-CLI and I installed ember progress-bar addon. I'm not sure how to proceed from here. If anyone can help with useful tutorials with step by step guidance or with any ideas about the best approach to create this SPA in Ember.js please.




how to render html text with as ember html inside a template?

Hi I have computed property that returns an html link with an ember action like this:

externalHtmlLink:

<a  href="#">Click Here</a>

but if I render this inside the template like this:

}

it renders the Action part as text and not as an Ember Html, and the action is never triggered. How should I render the link so the action is rendered by Ember?




lundi 5 septembre 2022

Consume Json api format in emberjs

data: [
       
    expiration-date: "2023-06-01T00:00:00"
    name: "Big Fish"
    id: "12932"
    membership-benefits: [{
            available-quantity: 0
            expiration-days: null
            expired-quantity: 0
            is-expired: false
            is-unlimited: false
            name: "Small Fish"
            status: {id: 2, name: "Active"}
            total-earned-quantity: 1
            used-quantity: 1
           }]

in model

@attr('string') name;
@attr('array') membershipBenefits;
@attr('string') expirationDate;

now when i m accessing the values :

console.log(model.name) /// Big Fish ✔️
console.log(model.expirationDate) /// 2023-06-01T00:00:00✔️
console.log(model.membershipBenefits[0].name) /// small Fish ✔️
console.log(model.membershipBenefits[0].status) ///  {id: 2, name: "Active"} ✔️
console.log(model.membershipBenefits[0].isUnlimited) /// undefined ❌
console.log(model.membershipBenefits[0].isExpired) /// undefined ❌

i am getting undefined value when i m accessing hyphenated properties of membershipBenefit array What is the correct way to access these properties??????




jeudi 1 septembre 2022

Unable to fetch id valuse in Java script

enter image description here

enter image description here

enter image description here

Hi there, I am trying to create two buttons save and update where the difference between them is the save button will save the data navigate to the back page and the update button will save the data and will stay on the same page. I am not sure where I am going wrong but I am unable to fetch the id in the if condition of Java Script. Thanks in advance.




EmberJS: Best way to handle multiple item heights in vertical collection

I am using https://github.com/html-next/vertical-collection in my emberjs project. In one of my lists I have elements with different heights and I was wondering how to handle estimateHeight

I have 3 different heights to account for, eg [100, 200, 300] I have tried estimateHeight with all 3 of these values and the add-on seems to handle everything well but Im trying to find the best way to ensure it is still performant.




mercredi 31 août 2022

html scrollable area define scrolled position

I have the following scrollable area, the html (using ember, so written using hbs) receives the selected div in the scrollable area, and it colors the selected div in gray. (code below).

Here is how the div looks like: enter image description here

here is the html (hbs)

        <div role="listbox" style="overflow-y: auto">
            
                <div class="variable-row  ">
                    
                </div>
            
        </div>

my issue is when the selectedVar isn't seen (for example var under kkkk needs to be scrolled to be seen) is there anyway I can tell the html to scrolled down to the selectedVar? something like

            
                <div >
                    
                </div>
            



mardi 30 août 2022

idpiframe_initialization_failed while using google signin on ember

building an ember app which uses google sign in yet when i added the button it fuc=nctions but it pops the error in console

idpiframe_initialization_failed

with the details You have created a new client application that uses libraries for user authentication or authorization that will soon be deprecated. New clients must use the new libraries instead; existing clients must also migrate before these libraries are deprecated. See the Migration Guide for more information."

my.hbs code


<div class="g-signin2"></div>


my index.html code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Embu</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="google-signin-client_id" content="938293174818-eu6i0913ria6b3v6mre2ad01t0q1cjh2.apps.googleusercontent.com">

    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css" integrity="sha384-xeJqLiuOvjUBq3iGOjvSQSIlwrpqjSHXpduPd6rQpuiM3f5/ijby8pCsnbu5S81n" crossorigin="anonymous">//->client id
    <link integrity="" rel="stylesheet" href="assets/vendor.css">
    <link integrity="" rel="stylesheet" href="assets/embu.css">

    
  </head>
  <body>
    
    <script src="https://apis.google.com/js/platform.js" async defer></script> //--> google api import
    <script src="assets/vendor.js"></script>
    <script src="assets/embu.js"></script>

    
  </body>
</html>




lundi 29 août 2022

"ember is not defined" while using torii authentication

I am building a web app using ember js which includes google oauthand torii for authentication.. without torii being installed everything looks fine yet when i just installed torii(i never used it) the app crashes and it says ember not defined also there are depraction messages which are


See https://deprecations.emberjs.com/v3.x/#toc_ember-global for details.

Usages of the Ember Global may be caused by an outdated ember-cli-babel dependency. The following steps may help:

* Upgrade the following addons to the latest version:
  * torii

### Important ###

In order to avoid repeatedly showing the same deprecation messages, no further deprecation messages will be shown for usages of the Ember Global until ember-cli-babel is upgraded to v7.26.6 or above.

To see all instances of this deprecation message, set the `EMBER_GLOBAL_DEPRECATIONS` environment variable to "all", e.g. `EMBER_GLOBAL_DEPRECATIONS=all ember test`.      

### Details ###

Prior to v7.26.6, ember-cli-babel sometimes transpiled imports into the equivalent Ember Global API, potentially triggering this deprecation message indirectly, even when you did not observe these deprecated usages in your code.

The following outdated versions are found in your project:

* ember-cli-babel@6.18.0, currently used by:
  * torii@0.10.1
    * Depends on ember-cli-babel@^6.11.0

ember version : 4.6.0 torii version : 0.10.1




jeudi 25 août 2022

@computed property with this.args in ember.js

Some of codes contains @computed("args.param") property behind of getters in ember.js. But I can use this.args.param in the getters without @computed("args.param"), and there is no problem in it. What's the differece between @computed("args.param") using and not using?

between

  @computed('args.date')
  get currentMonth() {
    return moment(this.args.date, 'YYYY-MM').startOf('month');
  }

and

  get currentMonth() {
    return moment(this.args.date, 'YYYY-MM').startOf('month');
  }



mardi 23 août 2022

@computed and @tracked in Ember.js

Currently, I am working on Octanify Components in Ember.js. I can't figure out the difference between using @computed and @tracked. It's similar, but sometimes I found a problem.

@computed
get departments() {
  return this.store.query('department', { per_page: 1 });
}

In this case, removing @computed puts you in an infinity cycle. What's the problem?




lundi 22 août 2022

retriving table content data in ember

am creating an ember application which gets data from servlet and print it in a table format.. the table look like this

Capacity Price  RoomType    RoomNo  Action
6        4150   suite         93    Select
2        1579   villa          5    Select
1        1526   villa          1    Select

when i clicked select i need to get the value in the room no. i tried creating a tracked variable and updating the value but got stuck so any idea how can i do it in ember.. i found an article which uses jquery to do the same but dont know how to add jquery in ember.

my handlebar file


  loading data...

<main class="conttainer mt-5 ">

<container class="cond">
<table border="1|0" class = "tab">
  <thead>
    <tr>
      <th><td>Capacity</td></th>
      <th><td>Price</td></th>
      <th><td>RoomType</td></th>
      <th><td>RoomNo</td></th>
      <th><td>Action</td></th>
    </tr>
  </thead>
  <tbody>
   
        
      <tr>
        
          <td></td>
          
        
        <td><button  class = "btn-test" >Select</button></td>//--> wrong decleration yet i dont know how to access the roomno column
        
      </tr>
    
  </tbody>
</table>
</container>
<form>
  <table>
    <tr>
      <td><h5>room number</h5></td>
    </tr>
    <tr><td></td></tr>//---> i have to show the value here
    <tr><td><b>Enter the Start Date</b></td></tr>
    <tr><td><input type = "date" placeholder="yyyy-mm-dd" id = "sdate" value = "2022-07-01" min = "2022-07-01" max = "2022-07-31"></td></tr>
    <tr><td><b>Enter the End Date</b></td></tr>
    <tr><td><input type = "date" placeholder="yyyy-mm-dd" id = "edate" value = "2022-07-01" min = "2022-07-01" max = "2022-07-31"></td></tr>
    <tr><td><button type = "button" >submit</button></td></tr>
  </table>
</form>

</main>

my controller file

class RequestState {
  @tracked value;
  @tracked error;

  get isPending() {
    return !this.error && !this.value;
  }
}

export default class RoomselectController extends Controller {
  @service router;
  @tracked room =0;
  getroomno(value){
    var that = this;
    console.log(value);
    that.room = value;
    console.log(that.room)
  }

  @use request = resource(({ on }) => {
    const state = new RequestState();
    var dis = this;
    $.ajax({
      url: 'http://localhost:8080/hotelres/My',
      method: 'GET',
      dataType: 'json',
      success: function(response){ 
        console.log(response)
        if(response == 0){
          dis.transitionToRoute("error");
        }else{
          state.value = response
        }
      },
      error: (xhr, status, error) =>
        (state.error = `${status}: ${xhr.statusText}`),
    });

    return state;
  });

  get result() {
    return this.request.value || [];
  }

i need to render the room number when the select button is pressed




dimanche 21 août 2022

could not find module 'ember-resources'

am trying to build an web app with ember and in the process of making a request to server and receiving a response and for that i used resources from ember-resource yet it always popping the error module not found ember-resources

the js code

import { use, resource } from 'ember-resources';
import { tracked } from '@glimmer/tracking';

class RequestState {
  @tracked value;
  @tracked error;

  get isPending() {
    return !this.error && !this.value;
  }
}

export default class RoomselectController extends Controller {
    @service router;

    @use request = resource(({ on }) => {
      const mobile = '123123123';
      const state = new RequestState();
    
      $.ajax({
        url: 'My',
        method: 'GET',
        dataType: 'json',
        data: { mobile },
        success: (response) => state.value = response;,
        error: (xhr, status, error) => state.error = `${status}: ${xhr.statusText}`,
      });

      return state;
    });

    get result() {
      return this.request.value || [];
    }

}

i installed ember-resource using ember install ember-resources also done npm install ember-resources

still showing the same module not found errro what to do?




samedi 20 août 2022

couldnt render a json array from servlet in ember js

am trying to render a json array which is sent from a java servlet in ember. the work flow goes like follows

1.sending an ajax request to the servlet which will return the jsonobject

2.i will get the json object and try to render in the handlebar file

the problem is when i consoled the response it came with an indexes

0: {CAPACITY: '4', PRICE: '918', RTYPE: 'basic', ID: '4'}
1: {CAPACITY: '2', PRICE: '885', RTYPE: 'villa', ID: '8'}
2: {CAPACITY: '2', PRICE: '1579', RTYPE: 'villa', ID: '5'}
3: {CAPACITY: '1', PRICE: '1526', RTYPE: 'villa', ID: '1'}

but what the server sent was

{"CAPACITY":"4","PRICE":"918","RTYPE":"basic","ID":"4"}
{"CAPACITY":"2","PRICE":"885","RTYPE":"villa","ID":"8"}
{"CAPACITY":"2","PRICE":"1579","RTYPE":"villa","ID":"5"}
{"CAPACITY":"1","PRICE":"1526","RTYPE":"villa","ID":"1"}

the controller code

export default class RoomselectController extends Controller {
    @service router;
    @tracked obj = null  ;
    @tracked price =0;
    get res(){
        var dis = this;
        const mobile = "123123123";
        $.ajax({
            url:'My',
            method : 'GET',
            dataType:'json',
            data : {mobile:mobile},
            success:function(response){
                console.log(response);
                dis.price = response[0].PRICE;//when rendered this works
                dis.obj = response;//when changed to dis.obj = response[0] it renders the first
                
                return response[0];
            },
            error: function(xhr,status,error){
                var errorMessage = xhr.status + ": " + xhr.statusText;
                alert("error " + errorMessage);
            }
        })
    }

the .hbs code

<table border ="1">
    <tr><td><b>Capacity</b></td><td><b>Price</b></td><td><b>Room Type</b></td><td><b>Room No</b></td></tr>

    
        
    <td></td>
    

    </table>

it is not working but when i use dis.obj = response[0] it works and renders only the first index how to make it render every data?




Ember Octane - How to loop through model records inside a component?

I have an array of strings passed as an argument to a component, inside the component I am using "each" helper to render each string in a text input. I tried the following approach.

I have a model passed as an argument to a component. I'm using #each helper to iterate through that model and this does not work.

Example:

  1. Template
<div>
<Location::LocationList @model=""/>
</div>
  1. LocationList component:
<ul class="location-list">
  
    <li>
      
    </li>
  
</ul>

And if I just do it in this way:

<ul class="location-list">
    
      <li>
        <Location::LocationItem @location=/>
      </li>
    
</ul>

It works as needed. Any suggestions?




dimanche 7 août 2022

How to specify template for Glimmer Component?

I have a typical Glimmer "base" component:

import Component from '@glimmer/component';
export default class BaseComponent extends Component { ... }

It has a template like normally, but the actual implementations of that component are child componenents, that override some of the template getters and parameters so that it works with various different data types.

export default class TypeAComponent extends BaseComponent { ... }
export default class TypeBComponent extends BaseComponent { ... }

etc.

My question is: How do I specify that all the child components should use the parent class template, so I don't have to duplicate the same fairly complex HTML for all child components? Visually the components are supposed to look identical so any changes would have to be replicated across all child component types. Therefore multiple duplicated templates isn't ideal.

In Ember Classic components there was layout and layoutName properties so I could just do:

layoutName: 'components/component-name'

in the base component and all child components did automatically use the defined template.

Now that I'm migrating to Glimmer components I can't seem to figure out how to do this. I have tried:

  • layout property
  • layoutName property
  • template property
  • Using the child components without a template in hope that they would automatically fall back to the parent class template.

Only thing that seems to work is creating Application Initializer like this:

app.register('template:components/child1-component', app.lookup('template:components/base-component'));
app.register('template:components/child2-component', app.lookup('template:components/base-component'));

But that feels so hacky that I decided to ask here first if there is a proper way to do this that I have missed?




samedi 6 août 2022

Bootstrap dropdown menu not scrollable inside ember-perfectscroll

I'm showing a few lists of items under different categories in kanban view. In each item-list, I use ember-perfectscroll to scroll through the items vertically. And in each item-card, I have bs-dropdown to select from a list of sub-categories. Everything works fine until the item-list grows bigger and needs to be scrolled.

When I want to open and scroll inside sub-categories dropdown menu, the item-list is getting scrolled instead. I'm able to scroll sub-categories menu only for the items which are at the end of the item-list.

How can I make the dropdown menu scrollable by suppressing perfect-scroll ?




vendredi 5 août 2022

How can I get my locally running app to see cookies from an app that is in production?

I have an Ember app in production & I have recently created a React application that will eventually replace the Ember app.

The plan is to begin migrating pages over into the React app.

For now, I'm just trying to login to the production app & then grab that cookie from the React app (locally - since it is early stages of dev) The issue that I'm currently struggling with is that I can't access the tokens/cookies from the production app because they are at my-domain.com where as the react app is running at localhost:3000

How do I go about sharing cookies & tokens between production & local?

Thanks in advance!




mardi 2 août 2022

Drop Down List in ember

Hi I am new to ember and trying to create a dropdown list using .

Is there a way where I can access the selected item in drop down list in ember via component? Give me a short example.

Thanks in advance.




Ember Js: Getting Uncaught RangeError when calling Component

I've created a simple route and component. I'm trying to call component from the template. But when i call, component is called recursively and getting the below error

vendor.js:58853 Uncaught RangeError: Maximum call stack size exceeded
    at Class.init (vendor.js:58853:20)
    at Class.superWrapper [as init] (vendor.js:33826:20)
    at Class.superFunction [as _super] (vendor.js:29300:20)
    at Class.init (vendor.js:56183:19)
    at Class.superWrapper (vendor.js:33826:20)
    at Class.superFunction [as _super] (vendor.js:29300:20)
    at Class.init (vendor.js:55450:19)
    at Class.superWrapper (vendor.js:33826:20)
    at Class.superFunction [as _super] (vendor.js:29300:20)
    at Class.init (vendor.js:54600:19)

Template.hbs contains the below


modified the router.js as

this.route('admin-settings', { path: 'admin-configuration/admin-settings'}); ;

I didn't added anything to route.js and component.js




jeudi 28 juillet 2022

Emberjs inside of get computed making request to backend multiple times cause infinite loop

I have a table basically in every row i have get function that makes a backend request with store service. But somehow when there is one row it works expect, but when there is multiple rows it always try to recalculate get function which makes sending infinite request to backend. I am using glimmer component

I cannot use model relation on ember side at this point, there is deep chain on backend side. Thats why i am making backend request.

get <function_name>() {
  return this.store.query('<desired_model_name>', { <dependent1_id>: <dependent1_id_from_args>, <dependent2_id>: <dependent2_id_from_args> });
}

I fixed this problem with using constructor. But do you have any idea why this get function re-calculate all the time? Dependent_ids are constant.

Weird thing is when results are [] empty array it does not re calculate every time. Even the query results are same it still try to recalculate every time and making infinite request to backend.




samedi 23 juillet 2022

How to referer to a page of ember js in web.xml document (for applying jaas authentication)

I'm new to ember js I need to apply Jaas authentication to my app whose front end is built on Ember JS and backend is done using servlets. I build the ember js part and run it on my tomcat server so, technically my application is on tomcat. So i tried to apply security constraints on those ember pages or routes. When I hit the protected URL, the protected page gets loaded instead of the page getting redirected to the login route.

Here is the web.xml file

<security-constraint>
        <web-resource-collection>
             <web-resource-name>admin</web-resource-name>
             <url-pattern>/admin</url-pattern>
        </web-resource-collection>
        <auth-constraint>
             <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
    
    <security-role>
        <role-name>admin</role-name>
    </security-role>
    
    <login-config>
         <auth-method>FORM</auth-method>
         <realm-name>studentDB_ember</realm-name>
         <form-login-config>
              <form-login-page>/login</form-login-page>
             <form-error-page>/error-login</form-error-page>
         </form-login-config>
    </login-config>

I know something is wrong with my xml page. The other parts of my authentication works fine. I can't find the correct way to represent the url of my ember page. Should I mention a path on router.js? I tried, it still doesn't work. Please let me know what am I doing wrong and how I should configure my xml so that the security contraints are applied appropriately and that my authentication works properly.

FYI: I have mentioned the location type as hash'#' in my environment.js file. and my link looks like this http://localhost:8085/test_auth/#/admin. It would direct me to the login page if its not authenticated and to the error page if the user name or password is wrong. If everything goes well we can see the admin page.

Thanks in advance. Let me know If you need more info. Any help is appreciated.




vendredi 22 juillet 2022

How to have multiple routes for retrieving same html content

I have 2 routes /main and /home. Both should show the same HTML content. Is it possible to point both the routes to the same hbs file?




jeudi 21 juillet 2022

Visual Studio Code marks each line of all files red

I am having the latest version of Visual Studio code.

Version: 1.69.2 (user setup)
Commit: 3b889b090b5ad5793f524b5d1d39fda662b96a2a
Date: 2022-07-18T16:12:52.460Z
Electron: 18.3.5
Chromium: 100.0.4896.160
Node.js: 16.13.2
V8: 10.0.139.17-electron.0
OS: Windows_NT x64 10.0.19042

I am using Ember.js projects. Whenever I am opening any file, it is marking each and every line as red.

Native JS classes should be used instead of classic classes eslintember/no-classic-classes

I tried uninstall/ install VS Code (also I completely uninstalled and then installed again) but nothing helpled

Asap I try install my usual extensions it starts giving trouble.




mercredi 20 juillet 2022

Chrome launcher not installed on Jenkins

I have a problem with running ember test on Jenkins, i am currently trying to generate a code coverage report for my app using ember-cli-code-coverage and locally everything works fine with running COVERAGE=true ember test but when i run the same command in Jenkins, i got Launcher Chrome not found. Not installed? i also try to run ember test in ci mode and i got the same error

This is testem.js

module.exports = {
    test_page: 'tests/index.html?hidepassed',
    disable_watching: true,
    launch_in_ci: ['Chrome'],
    launch_in_dev: ['Chrome'],
    browser_start_timeout: 120,
    browser_args: {
        Chrome: {
            ci: [
                // --no-sandbox is needed when running Chrome inside a container
                process.env.CI ? '--no-sandbox' : null,
                '--headless',
                '--disable-gpu',
                '--disable-dev-shm-usage',
                '--mute-audio',
                '--window-size=1440,900',
                '--remote-debugging-port=9222',
                '--remote-debugging-address=0.0.0.0',
                '--no-sandbox',
                '--user-data-dir=/tmp',
            ].filter(Boolean),
        },
    },
};

any idea how i can fix this ?

Screenshot of Jenkins errors

[1]: https://i.stack.imgur.com/HlYKQ.png




using watchman only on specific project

I am running 2 ember applications on my computer.

On one of them I want watchman to run (to solve EMFILE: too many open files, watch),
on the other project I do not want it to run - since it causes an error (TypeError: Invalid Version: 2022.06.27.00)

Is there a way to configure watchman to run/ not run on specific projects?




mardi 19 juillet 2022

Ember Ajax request doesn't wait for the response

Here I'm calling an AJAX request with this "Security.createAuthenticatedAjaxRequest(session, URL)" method and I want to return the response of that request. But, it seems like the response doesn't wait until the request completes. It returns undefined as the response. I think it's because it returns the response before ajax request completes.

function minAndMaxGradeAllowedRequest(session) {   if (Common.isEmpty(minAndMaxGradeAllowed)) {
        Security.createAuthenticatedAjaxRequest(session, URL).then(function(minAndMaxGradeAllowedResponse) {
          minAndMaxGradeAllowed = minAndMaxGradeAllowedResponse;
        }).fail(function(error) {
          LOGGER('Failed to find Shaywitz Min and Max grades information', error.toString());
        });   }   return minAndMaxGradeAllowed; }





createAuthenticatedAjaxRequest: function(session, url, config){
        if(Common.isEmpty(config)) {
          config = {};
        }
      return this.createAuthenticatedAjaxRequestWithAcceptHeaderParam(session, url, config, true);
    },
    createAuthenticatedAjaxRequestWithAcceptHeaderParam: function(session, url, config, isAcceptRequired){
        if(Common.isEmpty(config)) {
            config = {};
        }

        if(Common.isEmpty(config.headers)) {
            config.headers = {};
        }

        config.headers['Authorization'] = 'Bearer ' + session.get('data.authenticated.access_token');
        if(!Common.isEmpty(isAcceptRequired) &&  isAcceptRequired  === true) {
          config.headers['Accept'] = 'application/json';
        }

        if(Common.isNotEmpty(session.get('data.authenticated.supportuser'))){
          config.headers['supportuser'] = session.get('data.authenticated.supportuser');
        }

        return Ember.$.ajax(url, config);
    },

Below is the code where it uses the response of the function minAndMaxGradeAllowedRequest(session).

let minAndMaxGradeAllowed = ShaywitzGradesAllowed.getMinAndMaxGradeAllowed(this.get('session'));

I don't have much experience with Ember js. Can someone please help me to solve this problem?




mercredi 6 juillet 2022

Ember js, in heroku production, live reload fails to load and time out and loading spinner keeps spinning

I just deployed a simple side project using ember and rails. Evenything is good but when first enter the webpage, the browser loading spinner keeps spinning.

I checked on the console and it has an error saying fetching ember cli live reload has timed out.

This does not happen on local and live reload works fine on local. How can I fix this?

Thanks!

spinner

error message




vendredi 1 juillet 2022

Ember-table shows index on the header

I am using ember-table but have a weird behavior. It automatically adds index next to my header title.

image

But after I click one of the header to sort the table, the index will disappear as I want. How do I get rid of the index in the first place. Plus, without the sorting function, the table was normal.

After I click anyone of the header to sort the column, the index will go away.

image

Here is my sort object

sorts = [
  { valuePath: 'username' },
  { valuePath: 'total_assignment_count' },
  { valuePath: 'accepted_assignment_count' },
  { valuePath: 'accepted_rate' },
  { valuePath: 'acl_name' },
  { valuePath: 'repo_name'}
];

template

<EmberTable as |t|>
  <t.head
    @columns=
    @sorts=
    @onUpdateSorts=
  />
  <t.body @rows= />
</EmberTable>




dimanche 19 juin 2022

Documentation in ember.js repo

I want to contribute to ember.js and want to make a PR for these two issues.

https://github.com/emberjs/ember.js/issues/20102 https://github.com/emberjs/ember.js/issues/19896

However, I am not able to find the documentation in the repo. My assumption is that the documentation is built from the source files. Could anyone please guide me on what should I be looking into?




vendredi 17 juin 2022

Ember.js change tracked variable in child component

I am new to ember.js and wanna know what's the best way to alter @tracked variable in child component.

Assume this structure:

Parent
  --- Component1
  • Parent controller

    @tracked
    number = 1
    
  • Parent.hbs

    <Component1 @number= />
     
    
  • Component1.hbs

    <button > Add </button>
    
  • Component1.js

    @tracked
    number = this.args.number
    
    @action
    addNumber(){
        this.number += 1;
        console.log(this.number)
    }
    

The number did addon in the Component1 and print the number every time I clicked the Add button, however, it didn't reflect to Parent level.




mardi 14 juin 2022

What features of EmberJS should be considered when switching to it from React? [closed]

Can you please tell me what features of the EmberJS framework should be considered when switching to it from React?




lundi 13 juin 2022

How to show the quantity we have added instead of showing the item quantity from the database in Ember js?

I have been working on an e-Commerce project. I tried to implement a cart feature in which the data of the product is fetched from the backend. But when I try to display the items in the cart, the quantity of the products from the database are displayed.

I use ember-local-stoage addon to store the id of the product, then with the help of the computed property I fetch the product-details from the database. But I'm unable to store the quantity of the in the inside the local storage as array of hash: [{id: 2, quantity: 3}, {id: 4, quantity: 1}]. But if I try this I'm unable retrieve the id from the array of hash. Due to which the remove method also fails to work. Please someone help me with this issue.

shopping-cart service code:

// app/service/shopping-cart.js

import Service from '@ember/service';
import { computed } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { storageFor } from 'ember-local-storage';
const { service } = Ember.inject;
export default Service.extend({
    session: service('session'),
    store: service('store'),
    currentUser: service('currentUser'),
    itemsIds: storageFor('cart'),

    items:computed("itemsIds.[]", function(){
        const itemsIds = this.itemsIds;
        if(this.get("itemsIds.length") === 0){
            return [];
        }
        else{
            const items = this.store.query('product', {id: this.get("itemsIds.content")});
            return items
        }
    }),
    addItem(itemId){
        console.log(itemId);
        this.get('itemsIds').addObject(parseInt(itemId));
    },
    remove(itemId){
        this.itemsIds.removeObject(parseInt(itemId));
    },
    productPrice: computed.mapBy('items', 'price'),
    totalPrice: computed.sum('productPrice'),

    clear(){
        this.get('itemsIds').clear();
    }

});

cart.hbs template:

<div class="container mt-5">
    <h2>Shopping Cart <i class="fa-solid fa-cart-shopping"></i></h2>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"> Home</li>
            <li class="breadcrumb-item active" aria-current="page">Shopping Cart</li>
        </ol>
    </nav>

    
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col">
                        <img class="product-image" src="/assests/images/.jpeg" alt="">
                    </div>
                    <div class="col">
                        <h3></h3>
                        <h4><span>Price: </span>Rs </h4>
                        <p>Qty: </p>
                        <button class="btn btn-danger" >Remove Item</button>
                    </div>
                </div>
            </div>
        </div>
        
    

    <section class="w-50 ml-auto mb-5 mt-4">
        <div class="row">
            <span class="col price-title">Total</span>
            <span class="col price-amount">Rs. </span>
        </div>
    </section>
    <button type="button" class="btn btn-success"> Checkout</button>
    <button class="btn btn-warning" >Clear Cart</button>
</div>

products controller(ember) code:

// app/controllers/product.js

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

const { service } = Ember.inject;
export default Controller.extend({
    session: service('session'),
    currentUser: service('currentUser'),
    shoppingCart: service('shoppingCart'),
    quantity: 1,
    price: 0,
    dialogBox: false,
    actions:{
        addToItem(model){
            const id = model.id;
            const quantity = this.quantity;
            this.shoppingCart.addItem(id);
        },

        order(){
            var self = this;
            function setPrice(){
                self.set('price', (self.model.price * self.quantity));
            }
            this.set('dialogBox', true);
            const user_id = this.currentUser.user;
            let date = new Date();
            date.setDate(date.getDate() + 2);
            const orders = this.store.createRecord('order',{
                deliveryDate: date,
                processing: true,
                user_id: user_id
            });
            orders.save().then(setPrice());
        },

        orderItem(){
            this.set('dialogBox', false);
            console.log(this.model.id);
            const orderItems = this.store.createRecord('order-item', {
               quantity: this.quantity,
               product_id: this.model,
               price: this.quantity * this.model.price

           })
           orderItems.save().then(function(response){
               alert("Order has been placed successfully!!");
           });
        },

        showDialog(){
            this.set('dialogBox', true);
        },

        hideDialog(){
            this.set('dialogBox', false);
        },
        cancel(){
            
        }
    }
});

products controller(ruby on rails):

class ProductsController < ApplicationController
    def index
        if params[:id]
            render json: Product.find(params[:id]) 
        else
            render json: Product.all 
        end
        
    end

    def show
        render json: Product.find(params[:id])
    end
    def create
        title = params[:product][:title]
        description = params[:product][:description]
        price = params[:product][:price]
        quantity = params[:product][:quantity]

        Product.create!(
            title: title,
            description: description,
            price: price,
            quantity: quantity,
        )

    end
end

product.hbs


<div class="container mt-5">
    <div class="row">
        <div class="col">
             <i class="fa-solid fa-arrow-left fa-2x"></i>
        </div>
        <div class="col">
            <h1>Product details</h1>
        </div>
        <div class="col">
            
                <i class="fa-solid fa-cart-shopping fa-2x">
                
                    <span class="cart-items-count-product d-inline-flex justify-content-center align-items-center">
                        
                    </span>
                
            </i>
        </div>
    </div>
    <hr>
    <div class="container">
        <div class="row">
            <div class="col-sm-6">
                <img class="product-image" src="/assests/images/.jpeg" alt="">
            </div>

            <div class="col-sm-6">
                <h1></h1>
                
                <button class="btn btn-success"  >
                    <i class="fa-solid fa-cart-shopping"></i>
                    <span>Add to Cart</span>
                </button>
                <label class="quantity-label" for="quantity">Quantity Selector:</label>
                "> --}}
                
            </div>
        </div>
    </div> 
    <hr> 
    <h4> Description</h4>
    <div class="container">
        
            <p></p>
        
        <ul>
        
        </ul>
    </div>
    <button class="btn btn-success" >Order now</button>

</div>

<div class="dialog-container ">
    <div class="dialog">
        <h5></h5>
        <h5>The price is </h5>
        <h5 class="confirmation">Are you sure, you wanna place this order?</h5>
        <h5>Quantity: </h5>
        <div class="dialog-buttons">
            <button  class="btn btn-success">
                <i class="fa-solid fa-badge-check"></i>Yes
            </button>
            <button  class="btn btn-danger">Cancel</button>
        </div>
    </div>
</div>



Add Intl.Locale polyfill only when needed (How to block script tag with async functions)

I am trying to add Intl polyfill to an ember app, but have run into the issue that I need to add a script tag that executes async functions before evaluating other script tags.

In ember I can add a new <script> tag to index.html, that is placed before the emberjs tags:

<body>
  <script src="assets/polyfills.js"></script>   
  <script src="assets/vendor.js"></script> <-- this throws an exception if polyfill is not loaded for iOS < 14
</body>

Everything works fine when assets/polyfills.js looks like this:

import '@formatjs/intl-locale/polyfill';

However, the issue then is that the polyfill is loaded for all devices - no matter if needed or not. But according to the docs there is way to check wether the polyfill is actually needed https://formatjs.io/docs/polyfills/intl-locale/:

import {shouldPolyfill} from '@formatjs/intl-locale/should-polyfill'
async function polyfill() {
  // This platform already supports Intl.Locale
  if (shouldPolyfill()) {
    await import('@formatjs/intl-locale/polyfill')
  }
}

The problem now is, that I am dealing with an async function and I can't find a way to load the polyfill before any other js code is executed.

I have tried to modify polyfills.js to use top level awaits and enabled the experimental webpack feature topLevelAwait: true, but subsequent code is executed before the polyfill is loaded:

await import('@formatjs/intl-getcanonicallocales/polyfill');

I also tried to wrap it in a function, but that also didn't change anything:

async function load() {
  await import('@formatjs/intl-locale/polyfill');
};
await load();

I also tried things like this, which had exactly the same effect:

(async () => {
  await import('@formatjs/intl-locale/polyfill');
})();

Pretty much the thing that I need would look like this:

if (shouldPolyfill) {
  import '@formatjs/intl-locale/polyfill';
}

However, that is not valid and leads to this error: An import declaration can only be used at the top level of a module.

How do I solve that issue?




vendredi 10 juin 2022

How to implement add to cart functionality in ember app

I have been working on e-commerce project. As a part of this project I have to implement a add to cart feature. My frontend is ember and backend is rails-api. I have used computed property to implement this, but all data from database get displayed in the cart page. How to implement a proper cart using ember?

Ember version is 3.4.4 Rails version is 7.0.2.3

// app/services/shopping-cart.js
import Service from '@ember/service';
import { computed } from '@ember/object';
const { service } = Ember.inject;
export default Service.extend({
    session: service('session'),
    store: service('store'),
    currentUser: service('currentUser'),
    itemsIds: [],
    items:computed("itemsIds.[]", function(){
        const itemsIds = this.itemsIds;
        return this.store.query('product', {id: itemsIds.id});
    }),
    addItem(itemId){
        this.itemsIds.addObject(itemId);
    },
    removeItem(itemId){
        this.itemsIds.removeObject(parseInt(itemId));
    }

});
// app/routes/product.js
import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
const { service } = Ember.inject;

export default Route.extend(AuthenticatedRouteMixin, {
    session: service('session'),
    currentUser: service('currentUser'),
    
    model(params){
        return this.store.findRecord('product', params.product_id);
    }
    
});
// app/controllers/product.js
import Controller from '@ember/controller';

const { service } = Ember.inject;
export default Controller.extend({
    session: service('session'),
    currentUser: service('currentUser'),
    shoppingCart: service('shoppingCart'),
    quantity: 1,
    price: 0,
    dialogBox: false,
    actions:{
        addToItem(model){
            const id = model.id;
            this.shoppingCart.addItem(id);
        },

        order(){
            var self = this;
            function setPrice(){
                self.set('price', (self.model.price * self.quantity));
            }
            this.set('dialogBox', true);
            const user_id = this.currentUser.user;
            let date = new Date();
            date.setDate(date.getDate() + 2);
            const orders = this.store.createRecord('order',{
                deliveryDate: date,
                processing: true,
                user_id: user_id
            });
            orders.save().then(setPrice());
        },

        orderItem(){
            this.set('dialogBox', false);
            console.log(this.model.id);
            const orderItems = this.store.createRecord('order-item', {
               quantity: this.quantity,
               product_id: this.model,
               price: this.quantity * this.model.price

           })
           orderItems.save().then(function(response){
               alert("Order has been placed successfully!!");
           });
        },

        showDialog(){
            this.set('dialogBox', true);
        },

        hideDialog(){
            this.set('dialogBox', false);
        },
        cancel(){
            
        }
    }
});

<div class="container mt-5">
    <div class="row">
        <div class="col">
             <i class="fa-solid fa-arrow-left fa-2x"></i>
        </div>
        <div class="col">
            <h1>Product details</h1>
        </div>
        <div class="col">
            <i class="fa-solid fa-cart-shopping fa-2x"></i>
        </div>
    </div>
    <hr>
    <div class="container">
        <div class="row">
            <div class="col-sm-6">
                <img class="product-image" src="/assests/images/.jpeg" alt="">
            </div>

            <div class="col-sm-6">
                <h1></h1>
                
                <button class="btn btn-success"  >
                    <i class="fa-solid fa-cart-shopping"></i>
                    <span>Add to Cart</span>
                </button>
                <label class="quantity-label" for="quantity">Quantity Selector:</label>
                "> --}}
                
            </div>
        </div>
    </div> 
    <hr> 
    <h4> Description</h4>
    <div class="container">
        
            <p></p>
        
        <ul>
        
        </ul>
    </div>
    <button class="btn btn-success" >Order now</button>

</div>

<div class="dialog-container ">
    <div class="dialog">
        <h5></h5>
        <h5>The price is </h5>
        <h5 class="confirmation">Are you sure, you wanna place this order?</h5>
        <h5>Quantity: </h5>
        <div class="dialog-buttons">
            <button  class="btn btn-success">
                <i class="fa-solid fa-badge-check"></i>Yes
            </button>
            <button  class="btn btn-danger">Cancel</button>
        </div>
    </div>
</div>
// app/controller/cart.js
import Controller from '@ember/controller';

const { service } = Ember.inject;

export default Controller.extend({
    session: service('session'),
    currentUser: service('currentUser'),
    shoppingCart: service('shopping-cart'),
});
class ProductsController < ApplicationController
    def index
        if params[:id]
            render json: Product.find(params[:id]) 
        else
            render json: Product.all 
        end
        
    end

    def show
        render json: Product.find(params[:id])
    end
    def create
        title = params[:product][:title]
        description = params[:product][:description]
        price = params[:product][:price]
        quantity = params[:product][:quantity]

        Product.create!(
            title: title,
            description: description,
            price: price,
            quantity: quantity,
        )

    end

    def update
    end
end



samedi 4 juin 2022

I cant ember serve

I am not able to ember serve on git bash. I am not sure what the conflict is. Any ideas? Below is the error message that pops up.

Hailey@DESKTOP-5FJ8TB1 MINGW64 ~/OneDrive/desktop/myproject/project-brownie (feature/sunshinne24|MERGING) $ ember serve Cannot find module 'C:\Users\Hailey\OneDrive\desktop\myproject\project-brownie\node_modules@babel\helper-environment-visitor\node_modules@babel\types\lib\index.js'. Please verify that the package.json has a valid "main" entry

Stack Trace and Error Report: C:\Users\Hailey\AppData\Local\Temp/error.dump.a61b5896249cc6fe897d1bcbceaf1816.log




vendredi 3 juin 2022

Special characters fonts not converting fine after wrapper upgrade to 3.5.49

I have recently upgraded my servers wrapper version to 3.5.49 and my fonts in the html ui has disrupted. I see the below warnings in the console -

OTS parsing error: Failed to convert WOFF 2.0 font to SFN

When i revert back to 3.5.15 wrapper version, everything works well.




lundi 30 mai 2022

Using Auth0 with ember-simple-auth

I'm currently adding Auth0 to an Ember Application that previously used ember-simple-auth to authorize it's users. I was hoping to plug auth0 into ember-simple-auth to avoid having to refactor too much. I found the following library provided by Auth0, but it appears to be deprecated: https://www.npmjs.com/package/ember-simple-auth-auth0

Is there any simple way to still accomplish this? The new instructions seem to be for if you're just using Auth0 and no ember-simple-auth.




ember-native-class-codemods TypeError: Cannot read property 'process' of undefined

My test app is using ember-cli and ember is 3.28. When I tried to use ember-native-class-codemods to convert my test appli cation it throws below error,

TypeError: Cannot read property 'process' of undefined
    at bLZ (C:\Users\AS0002\AppData\Local\Volta\tools\image\packages\ember-native-class-codemod\node_modules\ember-native-class-codemod\node_modules\flow-parser\/flow_parser.js:565:79)
    at C:\Users\AS0002\AppData\Local\Volta\tools\image\packages\ember-native-class-codemod\node_modules\ember-native-class-codemod\node_modules\flow-parser\/flow_parser.js:566:4
    at Object.<anonymous> (C:\Users\AS0002\AppData\Local\Volta\tools\image\packages\ember-native-class-codemod\node_modules\ember-native-class-codemod\node_modules\flow-parser\/flow_parser.js:2:2)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Module._compile (C:\Users\AS0002\AppData\Local\Volta\tools\image\packages\ember-native-class-codemod\node_modules\ember-native-class-codemod\node_modules\pirates\lib\index.js:136:24)
    at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Object.newLoader [as .js] (C:\Users\AS0002\AppData\Local\Volta\tools\image\packages\ember-native-class-codemod\node_modules\ember-native-class-codemod\node_modules\pirates\lib\index.js:141:7)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)

It was already reported in github issue but no solutions mentioned https://github.com/ember-codemods/ember-native-class-codemod/issues/392

I have installed ember install ember-classic-decorator and ember install ember-decorators and my project is running while running the npx command. Below is my versions, ember-cli: 3.28.5 node: 14.19.3 os: win32 x64