mardi 31 mars 2020

Self closing void tags with Ember Glimmer components

I am in the process of upgrading an Ember app to the latest version (3.17) and have run into an issue with the new Glimmer components. Not having to specify a tag name is great, but I'm not sure how to handle self closing void elements such as an

<img> 

tag. It's obvious that you can wrap your component in a closing tag element

<div><MyComponent @name="test"/></div> 

but I've not come across any examples which use a self closing tag.

Many thanks in advance.




Enable Babel plugins in ember-auto-import for transpilation of imported library

I want to move some of utility functions and classes from my Ember app into a separate NPM library and import it with ember-auto-import. I don't want to transpile the library code before publication but publish in authoring format. This shouldn't be an issue as ember-auto-import transpiles the code automatically at build time depending on app's configuration.

But this code is experimental decorators feature as many Ember code these days does. Babel used by ember-auto-import throws an error that the decorators-legacy feature is not enabled:

Support for the experimental syntax 'decorators-legacy' isn't currently enabled

How can I enable it in the configuration of ember-auto-import? I only see an option to disable transpilation per dependency and custom webpack configuration in ember-auto-import's documentation. I don't have much experience with Webpack. Is babel controlled through Webpack configuration?




Rendering x3d indexedfacset with ember.js

I using x3d in an ember cli framework. In an older version of the ember framework everything runs well. I updated ember.js lately. After the ember.js update it is no problem to display idexedfaceset or indexedlineset in the x3d scene from the start of the ember application. But now there is a problem to add idexedfaceset or indexedlineset to the scene after the application is completely loaded. For example see the code below. If the display value is set to true by clicking a button the application throw an error:
Uncaught TypeError: Cannot read property 'getPoints' of null at x3dom.registerNodeType.defineClass.nodeChanged.nodeChanged (x3dom-full.js:4596)

I understand the error indicates that the coordinate tag is missing in this moment where x3d detect a node is added and try to render it. Afterwards I check the html code and the coordinate tag is where it should be. But the element isn't displayed in the x3d scene. It seems there is a short delay by adding the coordinate tag.
I know it is possible to display the element by using a jquery commad like $("#scene").append("..."). But I would like to use the ember behavior because i do a lot more like calculating positions and dimensions. I would be happy if someone could help to solve the problem. Thanks a lot.

//application.hbs

  <transform>
    <shape def="" ispickable="0" bboxsize="-1,-1,-1" bboxcenter="0,0,0" render="true">
      <appearance sorttype="auto" alphaclipthreshold="0.1">
        <material specularcolor="0,0,0" shininess="0.2" emissivecolor="0,0,0" ambientintensity="0.2" transparency="0.5" diffusecolor="0 0 1">
        </material>
      </appearance>
      <indexedfaceset ccw="true" colorpervertex="false" colorindex=" 0 0 0 0" coordindex="0 3 2 1 0" solid="true" usegeocache="true" lit="true" normalpervertex="true" normalupdatemode="fast" convex="true" >

        <coordinate point="-1 0 0, -1 1 0, 1 1 0, 1 0 0"></coordinate>

        <color color="0 0 1"></color>
      </indexedfaceset>
    </shape>
  </transform>
 ```




lundi 30 mars 2020

How are Ember Octane Glimmer component @actions called?

This question is related to Ember Octane Upgrade How to pass values from component to controller

I was struggling to receive and assign values from an HBS form into a component and then pass it to the controller. The working answer showed that I had to create an @action function for each form field. For example:

@action
changeNewPassword(ev) {
    this.newPassword = ev.target.value;
}

But, I do not understand where or how those functions are called and so I do not understand why they work. Does anyone know how these functions are called?

Template Component HBS

<div class="middle-box text-center loginscreen animated fadeInDown">
    <div>
        <h3>Change Password</h3>
        <form class="m-t" role="form" >
            
                <div class="error-alert"></div>
            
            <div class="form-group">
                <Input @type="password" class="form-control" placeholder="Old Password" @value= required="true" />
            </div>
            <div class="form-group">
                <Input @type="password" class="form-control" placeholder="New Password" @value= required="true" />
            </div>
            <div class="form-group">
                <Input @type="password" class="form-control" placeholder="Confirm Password" @value= required="true" />
            </div>
            <div>
                <button type="submit" class="btn btn-primary block full-width m-b">Submit</button>
            </div>
        </form>
    </div>
</div>

Template HBS

<Clients::ChangePasswordForm @chgpwd= @changePassword= @errors= />

Template Component JS

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ChangePasswordForm extends Component {

    @tracked oldPassword;
    @tracked newPassword;
    @tracked confirmPassword;
    @tracked errors = [];

    @action
    changeOldPassword(ev) {
        this.oldPassword = ev.target.value;
    }
    @action
    changeNewPassword(ev) {
        this.newPassword = ev.target.value;
    }
    @action
    changeConfirmPassword(ev) {
        this.confirmPassword = ev.target.value;
    }

    @action
    changePassword(ev) {

        ev.preventDefault();

        this.args.changePassword({
            oldPassword: this.oldPassword,
            newPassword: this.newPassword,
            confirmPassword: this.confirmPassword
        });
    }
}



Ember passing an action closure through an outlet

I am building a simple Ember app, but I have run into difficulty passing an action closure to a child component when that component is rendered in the of a navigable container.

For context, here is a quick look at the aesthetically-astonishing app I have been building:

I have a roles/role path that displays a component (the yellow section above) with the following markup. Note that the model for this component is an instance of a Role:

// file: app/components/role.hbs

<p></p>

<div>
  
  <div class='route-content'></div>
</div>

(Where "sel" stands for "someone else's library".)

Into that outlet will be rendered the appropriate list component, either users or privileges.

The users list is rendered by the following component. Note that the model is the list of User instances associated with the Role from its parent:

// file: app/components/role/user-list.hbs

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

and when the button is clicked it calls an action defined in the RoleUserListComponent class:

// file: app/components/role/user-list.js

import Component from '@glimmer/component';
import { action } from "@ember/object";

export default class RoleUserListComponent extends Component {

  @action removeUser(user) {
     // remove the user model from the role... but which role?
  }
}

The catch is that the relationship between users and roles is many-to-many, so I can't simply unset the user's owner and let Ember Data take care of things. The obvious answer seemed like passing an action closure from the role component to its child user-list component.

Except, there seems to be no way to pass the action closure through the . What I was hoping for was something like:


which would pass the closure to any component that was rendered there. I tried instead to use in the child to let the parent render the delete button and give it the appropriate action, but that also hit the outlet wall.

I also tried to use controllers, which aren't documented that well, probably since their role seems to have been evolving dramatically over Ember's maturation. But while this brief explanation does mention passing down actions, it doesn't go into details, and the few up-to-date examples I found all seem to break when an outlet joins the party.

I'm suspecting that just plain isn't closure-friendly.

While defining a service would probably work, that doesn't seem to be what services are intended for, and I'd be cluttering up my global space to solve a local problem.

What is the best practice (or, really, any practice) for dealing with getting messages through outlets? I looked for ways to query the earlier parts of the path, but I didn't find any that were defined in the relevant classes.




Ember - What data types can I pass as arguments into a Glimmer Component?

From another template, I can pass arguments to a component, such as:

<MyComponent @arg1="String" />

I know I could also pass another named object from the template's JS file, but I don't mean to ask about this.

My question is, what different data types can be passed in from the template, as a String was in the line above. Can I pass in booleans? What about an array of strings? And any special syntax for doing so?

Could I for example use to loop through an array argument? I guess the alternative's would be either to process through JS, or perhaps work with . Thanks.




dimanche 29 mars 2020

Ember Octane How to Get Error Messages to be Displayed

This question is related to Ember Octane Upgrade How to pass values from component to controller

How do I get Ember Octane to display on the webpage? For instance, if the old password and new password are the same we want that error to display on the page.

Ember-Twiddle here

Code example:

User Input Form

ChangePasswordForm.hbs

<div class="middle-box text-center loginscreen animated fadeInDown">
    <div>
        <h3>Change Password</h3>
        <form class="m-t" role="form" >
            
                <div class="error-alert"></div>
            
            <div class="form-group">
            
            </div>
            <div class="form-group">
                
            </div>
            <div class="form-group">
                
            </div>
            <div>
                <button type="submit" class="btn btn-primary block full-width m-b">Submit</button>
            </div>
        </form>
    </div>
</div>

Template Component

ChangePassword.hbs

<Clients::ChangePasswordForm @chgpwd=  @errors= />

Component

ChangePasswordForm.js

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ChangePasswordForm extends Component {

    @tracked oldPassword;
    @tracked newPassword;
    @tracked confirmPassword;
    @tracked errors = [];

    @action
    changePassword(ev) {

        // Prevent the form's default action.
        ev.preventDefault();

        this.oldPassword = ev.oldPassword;
        this.newPassword = ev.newPassword;
        this.confirmPassword = ev.confirmPassword;

        // Call the form's onsubmit method and pass in the component's values.

        this.onsubmit({
            oldPassword: this.oldPassword,
            newPassword: this.newPassword,
            confirmPassword: this.confirmPassword
        });
    }
}

Controller

ChangePassword.js

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';

export default class ChangePassword extends Controller {

    @service ajax 
    @service session

    @action
    changePassword(attrs) { 

        if(attrs.newPassword == attrs.oldPassword)
        {
            this.set('errors', [{
                detail: "The old password and new password are the same.  The password was not changed.",
                status: 1003,
                title: 'Change Password Failed'
            }]);
        }
        else if(attrs.newPassword != attrs.confirmPassword)
        {
            this.set('errors', [{
                detail: "The new password and confirm password must be the same value.  The password was not changed.",
                status: 1003,
                title: 'Change Password Failed'
            }]);
        }
        else
        {
            let token = this.get('session.data.authenticated.token');

            this.ajax.request(this.store.adapterFor('application').get('host') + "/clients/change-password", {
                method: 'POST',
                data: JSON.stringify({ 
                    data: {
                        attributes: {
                            "old-password" : attrs.oldPassword,
                            "new-password" : attrs.newPassword,
                            "confirm-password" : attrs.confirmPassword
                        },
                        type: 'change-passwords'
                    }
                }),
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/vnd.api+json',
                    'Accept': 'application/vnd.api+json'
                }
            })
            .then(() => {

                // Transistion to the change-password-success route.
                this.transitionToRoute('clients.change-password-success');
            })
            .catch((ex) => {

                // Set the errors property to the errors held in the ex.payload.errors.  This will allow the errors to be shown in the UI.
                this.set('errors', ex.payload.errors);
            });
        }
    }
}

Model

ChangePassword.js

import Route from '@ember/routing/route';
import AbcAuthenticatedRouteMixin from '../../mixins/abc-authenticated-route-mixin';

export default Route.extend(AbcAuthenticatedRouteMixin, {
//export default class ChangePasswordRoute extends Route(AbcAuthenticatedRouteMixin, {

    model() {

        return {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
        };
    },
})



Assertion Error : App Version has already been registered

Im using ember to develop a project. Please help me with this error. Im unable to run my project on local. After hitting ember server the build is successful. But on hitting the http://localhost:4200 Loads empty page with console error.

Uncaught Error: Assertion Failed: The initializer 'App Version' has already been registered
    at assert (index.js:172)
    at Function.initializer (index.js:420)
    at registerInitializers (index.js:27)
    at loadInitializers (index.js:68)
    at Module.callback (app.js:25)
    at Module.exports (loader.js:106)
    at requireModule (loader.js:27)
    at app-boot.js:3

Unable to understand what to do. Any help regarding this would be appreciated.




jeudi 26 mars 2020

Ember Octane upgrade: how to handle eslint error no-action

This is related to: Ember Octane Upgrade How to pass values from component to controller

In the ../templates/change-password.hbs file, I am receiving the following eslint error:

Do not use action as . Instead, use the on modifier and fn helper. no-action

Code:

<Clients::ChangePasswordForm @chgpwd= @changePassword= @errors= />

The accepted answer instructed me to use that syntax. Is there a different way I should be handling this or should I ignore the error?




Integration test not rendering after click when observing ember data record

I can't seem to figure out why a very simple integration test is not passing

Given an ember data model setting.js

export default class SettingModel extends Model {
  @attr('string') name;
  @attr('number') value;
}

I am rendering this model with a component

<MyComponent @setting=
             @name=
             @value=
             @values=
             @saveSetting= />

The component renders all the possible values (@values) and applies an active class on the one which equals the current value


  <div class="btn " >
    
  </div>

I wanted to write a simple test where clicking another button updates the active class, but the last assertion always fails. The active class is never updated. In this example, I have used ember-cli mirage

test('renders correctly', async function(assert) {
    this.server.get('/settings/:id', () => ({ settings: { id: 1, name: "settingName", value: 1 }}), 200);
    let setting = await this.owner.lookup('service:store').findRecord('setting', 1);
    this.set('setting', setting);
    this.set('name', setting.get('name'));
    this.set('value', setting.get('value'));
    this.set('values', [0, 1, 2]);
    this.set('saveSettingFn', () => {});

    await render(hbs`<MyComponent @setting=
                                  @name=
                                  @value=
                                  @values=
                                  @saveSetting= />`);



    // middle option active
    assert.ok(this.element.querySelectorAll('.btn')[1].getAttribute('class').includes('active'), 'second button active');
    // click the first button
    await click('.btn');
    // first option active
    assert.ok(this.element.querySelectorAll('.btn')[0].getAttribute('class').includes('active'), 'first button active');
  });

I've created an example project here with a failing test https://github.com/spicalous/component-test-example/blob/master/tests/integration/components/my-component-test.js#L55

  1. It looks like the value on the model has been saved
  2. I have tried using waitFor test helper
  3. I have tried await settled();

Any help is appreciated! Thank you!




mercredi 25 mars 2020

"Error : Cannot start a build if one is already running" on using ember server

I'm just setting up a project in Ember and I ran into this issue. Its not going away. I checked a lot of forums.

I'm getting this error while running ember server

Cannot start a build if one is already running


Stack Trace and Error Report: /var/folders/gg/_8df84q97d9bv3hvcky3sj1c0000gn/T/error.dump.9aec39b1e1cb7d4551398e66431a9697.log

Build successful (5256ms) – Serving on http://localhost:4200/



Slowest Nodes (totalTime => 5% )              | Total (avg)         
----------------------------------------------+---------------------
BroccoliRollup (6)                            | 1152ms (192 ms)     
SassCompiler (1)                              | 1086ms              
Babel: @ember/test-helpers (2)                | 550ms (275 ms)      
Package /assets/vendor.js (1)                 | 391ms               
ember-auto-import-analyzer (3)                | 382ms (127 ms)      
broccoli-persistent-filter:EslintValid... (2) | 285ms (142 ms)      

(node:5414) UnhandledPromiseRejectionWarning: Error: Cannot start a build if one is already running
    at Builder.build (/Users/freakyspeedster/Documents/cash-n/cashn-wallet/node_modules/broccoli/dist/builder.js:100:19)
    at /Users/freakyspeedster/Documents/cash-n/cashn-wallet/node_modules/ember-cli/lib/models/builder.js:220:32
    at tryCatcher (/Users/freakyspeedster/Documents/cash-n/cashn-wallet/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:326:21)
    at invokeCallback (/Users/freakyspeedster/Documents/cash-n/cashn-wallet/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:498:33)
    at publish (/Users/freakyspeedster/Documents/cash-n/cashn-wallet/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:484:9)
    at flush (/Users/freakyspeedster/Documents/cash-n/cashn-wallet/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:2441:7)
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
    at runNextTicks (internal/process/task_queues.js:62:3)
    at processTimers (internal/timers.js:472:9)



Does Ember Octane Route class support using mixins?

I am upgrading to Ember Octane and I understand that mixins have been deprecated. I will continue to use them until I figure out how to replace them. In the meantime, I would like to switch my route over to using the new class syntax, as opposed to Route.extend. Does the new route class syntax support route mixins? If yes, how?

This is related to Ember Octane Upgrade How to pass values from component to controller

Pre-ember Octane:

import Route from '@ember/routing/route';
import AbcAuthenticatedRouteMixin from '../../mixins/abc-authenticated-route-mixin';

export default Route.extend(AbcAuthenticatedRouteMixin, {

    model() {

        return {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
        };
    },
})

Post-ember Octane:

import Route from '@ember/routing/route';
import AbcAuthenticatedRouteMixin from '../../mixins/abc-authenticated-route-mixin';

export default class ChangePasswordRoute extends Route(AbcAuthenticatedRouteMixin, {

    model() {

        return {
            oldPassword: '',
            newPassword: '',
            confirmPassword: ''
        };
    },
}) // I get an error here that says: '{' expected



mardi 24 mars 2020

EmberJS and .NET Core Export as PDF feature

I have a backend running with .NET Core (which shoots api/..) in JSON and our front-end is using EmberJS for the rendering. How and what should I use if I want to export my object as a PDF with a template?




Javascript design patterns in context of SPAs

While there are tons of design patterns which can be used, I wanted to understand some of the important ones in the context of Single Page applications e.g. EmberJS, Angular

Just to give a simple example, Services are based on singleton pattern (both in Ember/Angular) So, I am looking at similar patterns for SPAs.

Also to add, are patterns like Module pattern which seem like integrated as part of the framework itself, but do they make any sense apart from that in a SPA context ?




lundi 23 mars 2020

How to refresh the value of a property in Ember automatically

First off I think that the subject question may not contain the correct context in what I am looking for, but I will try to explain myself.

I am fairly new to Ember, and I am looking for a way to take a property and refresh the value of it, periodically instead of based on the view refreshing, action, or a template element causing the property to change.

This is kind of a generic example, but it closely relates to what I am doing:

  • I have a utility that calculates the size of objects or in specific to what I am doing it will calculate the size of the localStorage.
  • I store the value of that calculation in a property and use it in a "service" and other places throughout the app.

    • Everyplace where I use this property is just a static view, and the user will have no interaction in doing something that will cause an action to update that property.

    any suggestions?




dimanche 22 mars 2020

Use of Ember evented in a service for publishing/subscribing to events

I am using an event-bus service in my app as below;

import Evented from '@ember/object/evented';
import Service from '@ember/service';

export default Service.extend(Evented, {
publish: function(){
return this.trigger.apply(this, arguments);
},
subscribe: function(){
this.on.apply(this, arguments);
},
unsubscribe: function(){
this.off.apply(this, arguments);
}
})

Now I consume this from my app as below. I have an event-mixin which is kind of like a wrapper as below;

export default Mixin.create({
events: service('event-bus'),
subscribe: function(eventName, callback){
this.get('events').on(eventName, this, callback);
},
unsubscribe: function(eventName, callback){
this.get('events').off(eventName, this, callback);
}    
})

Also, to actually use this in a component, I have;

import events from '../mixins/event-mixin';
export default Component.extend (events, {

eventsToListen: function(){
return [{
eventName: "enableBtn",
callBack: $..proxy(this.enableBtn, this);
}]
}
}

I have showed few parts of the relevant code here. While I understand the Observer pattern, the actual code has me a bit confused.

Specifically, in my event-mixin, I have code like

this.get('events').on(eventName, this, callback);

However, if I look at my event-bus which is like a common f/w service which I consume, it has

subscribe: function(){
    this.on.apply(this, arguments);
    },

I am confused as to there is no call made from my app directly to publish/subscribe/unsubscribe methods defined in event-bus (instead I have this.get('events').on(....))

How does it work ?




vendredi 20 mars 2020

stub performance.now() using Sinon.js

I am writing unit tests in Ember-qunit. I want to set a custom value on performance.now.

I tried sinon.stub(performance,'now', 60000); but this didn't work. I get TypeError: stub(obj, 'meth', fn) has been removed.

how do i stub performance.now() using sinon.js?

Thanks




jeudi 19 mars 2020

Upgrade handlebars.js to version 4.7.3

My goal is to upgrade handlebars from version 1.1.2. to 4.7.3. I have downloaded version 4.7.3. and added it to index.html. I also changed handlebars version in package.json file and run npm install handlebars -g. But when I try to open the application everything crashes, I get this error: "Unknown template object: function". I debugged this issue and figured out that templateSpec.main is undefined. I am new to this, so I would be grateful if someone can provide me detailed answer how to fix this issue. I found already similar topic, but I didn't understand what to do if the problem is in precompiling. P.S. The application is in old Ember version 1.7.1. (I am not allowed to change Ember version btw).




EmberJS - Reset fields and their validation errors

I want to reset every field's content by settting '' or null, but that leaves me with validation errors like This field can't be blank. Getting into the isNew state would help a lot, because it would reset the validations errors.

enter image description here

resetButton() {
      if (!this.model) {
        return;
      }

      this.model.eachAttribute(function(property) {
        this.model.set(property, '');
      });
      this.model.set('related', '');
      this.parentModel.send('becomeDirty');
    }

Visibility, if this field and comparator are succesfully reseted, but the tricky one is This value

I am using ember-cp-validations and ember-paper.




mercredi 18 mars 2020

Error: You attempted to overwrite the built-in helper "array". Where is this coming from?

How do I track down where this error is coming from? I searched my own codebase, and could not find anywhere that I was using the helper. It happens during an acceptance test.

You attempted to overwrite the built-in helper "array" which is not allowed. Please rename the helper.

I am attempting to update some of my Ember dependencies, which surfaced this problem.




getting data from js promise

I am doing an api call that returns a promise. The call works fine but I want to do treat data contained within the promise. Here is My call:

  let promiseArray = this.get('store').query('member', {query: term, option: this.get('option')});
  promiseArray.then(members  => {console.log(members);
  });

  let var= members;
  console.log(var);

My problem is that this doesn't return an array of my model i.e members, also the second display of members display undefined , it return an object containing a lot of meta data, also the array but inside some meta data.

How could I get simply the array ?




Ember-unit test for setInterval function --Ember

i am a noob, who started working on a feature in Ember JS and am currently in process of writing unit tests for the following but not sure how.. The basic functionality here is certain properties are set based on the inactivity time and this check runs every two seconds. How do i write unit tests using sinon or whichever to fake the warning times(4 and 5min)

    firstWarning: 240000;//4min
     secondWarning: 300000;//5min

  start() {
    this.set(
      "timer",
      setInterval(() => {

        //inactive time is the difference between session start time which is
        //calculated by performance.now and lastRefresh(time when user has last refreshed the page)
        let inactivityValue = performance.now() - this.get("lastRefresh");
        let firstWarning = this.get("firstWarnTime");
        let secondWarning = this.get("secondWarnTime");

        if (inactivityValue < firstWarning) {
          this.set("firstPopup", false);
          this.set("secondPopup", false);
        } else if (inactivityValue >= firstWarning && inactivityValue < secondWarning) {
          this.set("firstPopup", true);
          this.set("secondPopup", false);
        } else if (inactivityValue >= secondWarning) {
          this.set("firstPopup", false);
          this.set("secondPopup", true);
        }
      }, 2000)
    );
  }



Emberfire configuration with ember project

I want to configure firebase with my ember project. So I create a new ember project. The project was working correctly. But after installing ‘emberfire’ using “ember install emberfire” I facing this error "Uncaught Error: Could not find module ember imported from emberfire/initializers/emberfire". Please give me the solution for solving this error. Thank you.




lundi 16 mars 2020

How to get a file from the backend withou getting it JSON-parsed

I’m able to get an xlsx file from my rails backend with a GET-Request to “/companies/export_xslx”, now I’m facing the problem of getting the file passed the JSON parser. For every request the console shows “JSON.parse: unexpected character at line 1 column 1 of the JSON data”.

This is my setup:

//company model ...
exportXlsx: function() {
  const adapter = this.store.adapterFor('company');
  return adapter.exportXlsx();
}

//adapters/company.js
import DS from 'ember-data';
import TokenAuthorizerMixin from 'ember-simple-auth-token/mixins/token-authorizer';

export default DS.JSONAPIAdapter.extend(TokenAuthorizerMixin, {

  exportXlsx() {
    const url = 'companies/export_xlsx';
    return this.ajax(url, 'GET',
      { dataType: 'text',
         accepts: { xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
       } });
  }
});

I’ll try to alter the default accept header but the requests gets sent with “Accept: application/vnd.api+json”.

I already tried different approaches with “ember-custom-actions” or “ember-cli-file-saver”, they all failed with the JSON.parse… response.




How to deploy Ember CLI fastboot app for production?

I prepared an ember-cli project that gets api from express server. Then I added fastboot to using the command:

ember install ember-cli-fastboot

After that, all the links began to be rendered on the server. Tell me, how do I run this in production? If I run ember build and load the project from the dist folder (via express route), the application opens like a usual SPA, and the child pages do not reload, and are not accessible for curl. That is, it behaves like a usual SPA. Please tell me how to run it? Should I run it in production as it is, withowt build, i.e. from ember-cli folder, using ember serve? Thanks for any help.




Ember js - Filters are not working when routing from home page

I am new to Ember js, my project is using v2.14. my problem is when going to a page for the first time it is loading the data and filters are working correctly. but next time it's appending the old data in modal to the new data. showing all the data. I don't know how to clear the modal data without affecting full modal data.




Changes in Ember data does not show the live changes in HTML

In my ember application as shown below when user clicks send the action in component will send the api post request and receive the successful data, can be see in ember inspector data tab, But I need to refresh the page to see newly added item, I tried some example shown in ember guide, nothing helps

My action code is

actions:{
    send(Text_Message){
        if(Text_Message != null){
            console.log(this.chatid);
            var data = {
                    "Message" : Text_Message,
                    "ChatId" : this.chatid
            }
            var store = this.get('store').createRecord('message',data)
            store.save().then((response)=>{
            })
        }else{
            alert("Type something to send")
        }
    }

}

handle bar template is


        <div>
        
            <div class= > 
                
             </div>
           
        </div>
        
        <div class = "groupmessage-no-Msg">
            <div class="groupmessage-msg-content"> No Messages </div>     
        </div>
        
        <div class = "groupmessage-msg-control">
            
            <div  class="groupmessage-sendbutton groupmessage-sendbutton1" >Send</div>
        </div>



dimanche 15 mars 2020

Ember Octane Upgrade How to pass values from controller to component

Upgrade from Ember < 3.15 to >= 3.15. How do I pass form values from a controller into a component?

I cannot begin to explain the number of diagnostic combinations attempted and their corresponding errors received. So, I figure it best to ask how it should be done correctly? Is Glimmer involved?

A simple example: pass a change password from old password to both a new and confirm password via a component to a controller. In the Component, I keep getting onsubmit() is not a function errors.

Code example:

Component

import Component from '@ember/component';
import { A } from '@ember/array';

export default Component.extend({

    didReceiveAttrs() {

        this._super(... arguments);

        this.setProperties({
            oldPassword: this.get('chgpwd.oldPassword'),
            newPassword: this.get('chgpwd.newPassword'),
            confirmPassword: this.get('chgpwd.confirmPassword')
        });
    },

    init() {
        this._super(... arguments);
        this.set('errors', A([]));
    },

    actions: {

        changePassword(ev) {

            ev.preventDefault();

            this.onsubmit({
                oldPassword: this.oldPassword,
                newPassword: this.newPassword,
                confirmPassword: this.confirmPassword
            });
        },
    },
});

Controller

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

export default Controller.extend({

    ajax: service('ajax'),
    session: service('session'),

    actions: {

        changePassword(attrs) { 

            if(attrs.newPassword == attrs.oldPassword)
            {
                this.set('errors', [{
                    detail: "The old password and new password are the same.  The password was not changed.",
                    status: 1003,
                    title: 'Change Password Failed'
                }]);
            }
            else if(attrs.newPassword != attrs.confirmPassword)
            {
                this.set('errors', [{
                    detail: "The new password and confirm password must be the same value.  The password was not changed.",
                    status: 1003,
                    title: 'Change Password Failed'
                }]);
            }
            else
            {                   
                let token = this.get('session.data.authenticated.token');

                this.get("ajax").request(this.get('store').adapterFor('application').get('host') + "/clients/change-password", {
                    method: 'POST',
                    data: JSON.stringify({ 
                            data: {
                                attributes: {
                                    "old-password" : attrs.oldPassword,
                                    "new-password" : attrs.newPassword,
                                    "confirm-password" : attrs.confirmPassword
                                },
                                type: 'change-passwords'
                            }
                        }),
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/vnd.api+json',
                        'Accept': 'application/vnd.api+json'
                    }
                })
                .then(() => {
                    this.transitionToRoute('clients.change-password-success');
                })
                .catch((ex) => {
                    this.set('errors', ex.payload.errors);
                });
            }
        },
    },
});



Import scss from node_modules within ember addon

I'm developing an ember addon which imports sass from it's dependencies. To use it I have the following in my addon -

# my-addon/package.json
...
"dependencies": {
  "lib1": "^1.5.3",
  "lib2": "1.2.3",
  "ember-cli-sass": "^10.0.1",
  "sass": "^1.23.3"
}
...
# my-addon/addon/styles/addon.scss

@import "lib1/assets/stylesheets/styles";
@import "lib2/assets/stylesheets/styles";
# my-addon/ember-cli-build.js

let app = new EmberAddon(defaults, {
  // Add options here
  sassOptions: {
    includePaths: [
      'node_modules'
    ]
  }
});

This way, the dummy app at tests/dummy can resolve the imports. But when I use the addon in my host app, I get

Error: Can't find stylesheet to import.
  ╷
1 │ @import "lib1/assets/stylesheets/styles";
  │         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I can modify my host app's ember-cli-build.js to

let app = new EmberAddon(defaults, {
  // Add options here
  sassOptions: {
    includePaths: [
      'node_modules/my-addon/node_modules'
    ]
  }
});

and ideally it should work but sass runs out of memory because it tries to import everything in node_modules of my host app. How do I make this work for both the dummy app and the host app still be able to import namespaced lib scss?




samedi 14 mars 2020

How to import global variable in Ember?

I am new to Ember, and am trying to use a global variable in the config / environment file to then import it into several adapters and models. I need this to change the variable in one place, instead of editing each file. In this case, the global variable is a string with the address of the api server. The variable is named apiRoot. I tried to use the following configuration, but it does not work. Please tell me what needs to be done, if this is possible in the Ember, or maybe there is another way? Thanks for any help!

Environment File:

'use strict';

module.exports = function(environment) {
  let ENV = {
    modulePrefix: 'front',
    environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
      },
      EXTEND_PROTOTYPES: {
        Date: false
      }
    },

    APP: {
    }
  };

  if (environment === 'development') {
  }

  if (environment === 'test') {
    ENV.locationType = 'none';
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.autoboot = false;
  }

  if (environment === 'production') {
  }

  ENV.apiRoot = 'http://localhost:5555/api';

  return ENV;
};

Adapter:

import RESTAdapter from '@ember-data/adapter/rest';
import ENV from '../../config/environment';

export default RESTAdapter.extend({
  host: ENV.apiRoot,
  pathForType() {
    return "posts";
  }
});



jeudi 12 mars 2020

ember-addon - afterInstall hook does not update my ember app package.json

Im trying to create an Ember Addon that uses the blueprint afterInstall hook.

I have read https://cli.emberjs.com/release/writing-addons/addon-blueprints/

My addon is called hello-world.

I generated my addon blueprint by ember generate blueprint hello-world.

I have now a blueprint/hello-world/index.js file.

'use strict';

module.exports = {
  description: 'This is my blueprint',
  afterInstall(options) {
    console.log('hello');

    return this.addPackagesToProject([
      { name: 'lodash' }
    ]);
  }
};

How could I test the the afterInstall hook is called?

My Ember Addon is in development (and has not been published), I have tried using npm link in my Ember Addon directory and npm link hello-world in my Ember app. This creates a symlink in my Ember App node_modules to point to my hello-world Ember Addon but it does not trigger the afterInstall hook.

My Ember App package.json does not get an entry for lodash in dependencies or devDependencies.

Part of my Ember App package.json

"devDependencies": {
    ...
    "hello-world": "*"
    ...
  }

Running npm install --offline does not seem to trigger the blueprint hook.




mercredi 11 mars 2020

./watch is compiling the JS library files mostly but one file it is always caching - need some urgent help please

Hi All I am using Ember even though I am making changes but when I run the ./watch its not producing the JavaScript file with new code - its annoying - I am making the manual change but that's not correct solution right? I made the change to the file even by opening in folder and manually updated the code on ember file - still its writing the old code in app.js file. What could be the reason I don't know. I am using Web Pack to run ./watch and generate the app.js file Here is my Ember js code:

export default () => { IMS.registerController("case.details.assignedinspector.edit", {

caseDetails: Ember.inject.controller('caseDetails'),
caseId: Ember.computed.alias('caseDetails.model.imscase.id'),
clearForm: function () {
    $('.modal').modal('hide');
},
actions: {
    close: function (id) {
        $('.modal').modal('hide');
        this.transitionToRoute('case.details');
    },

    async save() {
        var scope = this;

        //validating form
        if ($("#edit-assignedinspector-form").validate()) {
            var data = {                    
                AssignedToInvestigators: Ember.get(scope, 'model.imscase.assignedToInvestigators'), //AssignedToInspectorId: $("#assignedInspectorSelect").chosen().val(),
                CaseId: this.get('caseId')
            };
            try {
                let response = await this.api('Case/UpdateAssignedInvestigators').post(data);
                $('.modal').modal('hide');
                toastr.success("Assigned Inspector Edit Saved.");
                scope.transitionToRoute("case.details");
                scope.get('caseDetails').refreshData();
                scope.clearForm();
            } catch (ex) {
                toastr.error("Error saving Assigned Inspector.");
            }
        }
        else {
            toastr.warning("Please fix the form", "Validation failed");
        }
    },
    didInsert: function () {
        $('#edit-assignedinspector-modal').modal();
    }
}

}); }

Here is how its generating the old code in app.js file - any help please?

  save: function () {
    var _save = _asyncToGenerator(
    /*#__PURE__*/
    regeneratorRuntime.mark(function _callee() {
      var scope, data, response;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              scope = this; //validating form

              if (!$("#edit-assignedinspector-form").validate()) {
                _context.next = 19;
                break;
              }

              data = {
                AssignedToInspectorId: $("#assignedInspectorSelect").chosen().val(),
                CaseId: this.get('caseId')
              };
              _context.prev = 3;
              _context.next = 6;
              return this.api('Case/UpdateAssignedInspector').post(data);

            case 6:
              response = _context.sent;
              $('.modal').modal('hide');
              toastr.success("Assigned Inspector Edit Saved.");
              scope.transitionToRoute("case.details");
              scope.get('caseDetails').refreshData();
              scope.clearForm();
              _context.next = 17;
              break;

            case 14:
              _context.prev = 14;
              _context.t0 = _context["catch"](3);
              toastr.error("Error saving Assigned Inspector.");

            case 17:
              _context.next = 20;
              break;

            case 19:
              toastr.warning("Please fix the form", "Validation failed");

            case 20:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, this, [[3, 14]]);
    }));

    function save() {
      return _save.apply(this, arguments);
    }

    return save;
  }()

It is supposed to call Case/UpdateAssignedInvestigators instead its still calling the Case/UpdateAssignedInspector, which is incorrect. Any help would be very very helpful - a link, a suggestion or even a code snippet anything helps thanks in advance.




mardi 10 mars 2020

Ember-Template-Lint How to fix block-indentation errors on hbs files?

I am able to run esling on *.js files. However, it does not seem to support handlebar files.

I did some searching online and found Ember-Template-Lint. But, I am unable to figure out how to change automatically fix block indentations. Is it possible to automatically fix all block indentation errors on Ember handle bar files?

1.) What rule do I use in .template-lintrc.js 2.) What command do I run from the terminal to fix any/all *.hbs files?

https://github.com/ember-template-lint/ember-template-lint

'use strict';

module.exports = {
    extends: 'recommended',

    rules: {
        'no-html-comments': false,
        'no-bare-strings': false
    }
};



EmberJS transitionTo() not taking me to the destination

router.js:

  this.route('404', { path: '/*path' });

application/route.js:

import Route from '@ember/routing/route';
import DS from 'ember-data';

const { NotFoundError } = DS;

export default Route.extend(
    actions: {
      error(error) {
        if (error instanceof NotFoundError) {
          //this.transitionTo('404') not working
          this.intermediateTransitionTo('404', {});

          return;
        }
        throw error;
      }
    }
  }
);

If I do this.transitionTo('index'), it works, but not with 404. Why is this.intermediateTransitionTo('404', {}); working? Is it because of the path argument in this.route('404', { path: '/*path' });?




Json call on unauthorized url returns Unexpected token < in JSON at position

let json = this._super(url, type, options); Making ajax call on return it will return login page(HTML code) since url is unauthorized the json returned is

SyntaxError: Unexpected token < in JSON at position 2

at JSON.parse ()

at jQuery.parseJSON (jquery.js:8520)

at ajaxConvert (jquery.js:8846)

at done (jquery.js:9264)

at XMLHttpRequest.callback (jquery.js:9718)

Errors occured: ember-metal.js:3992 TypeError: Cannot read property ‘get’ of undefined

at adapter.js:28

at tryCatcher (rsvp.js:215)

at invokeCallback (rsvp.js:393)

at publish (rsvp.js:379)

at publishRejection (rsvp.js:314)

at rsvp.js:14

ember-metal.js:3992 SyntaxError: Unexpected token < in JSON at position 2

at JSON.parse ()

at jQuery.parseJSON (jquery.js:8520)

at ajaxConvert (jquery.js:8846)

at done (jquery.js:9264)

at XMLHttpRequest.callback (jquery.js:9718)

What may be the reason ?




lundi 9 mars 2020

How may a defined function be undefined?

Got a mysterious error trapped when running a javascript program in the browser. I did not expect this would be possible.

  1. This is the Firefox console message when the execution was interrupted. Tne triggering code line is indicated:
TypeError: saveOrderFunc(...) is undefinedmish-project-9e3368b0606d05c921e4bcce069c6187.js:6233:24 (<***)
    doFindText http://localhost:3000/assets/mish-project-9e3368b0606d05c921e4bcce069c6187.js:6233
    invoke http://localhost:3000/assets/vendor-2ec1510f3a7e6a9956d317f82db731b5.js:66502
    flush http://localhost:3000/assets/vendor-2ec1510f3a7e6a9956d317f82db731b5.js:66392
    flush http://localhost:3000/assets/vendor-2ec1510f3a7e6a9956d317f82db731b5.js:66601
    _end http://localhost:3000/assets/vendor-2ec1510f3a7e6a9956d317f82db731b5.js:67177
    end http://localhost:3000/assets/vendor-2ec1510f3a7e6a9956d317f82db731b5.js:66863
    _runExpiredTimers http://localhost:3000/assets/vendor-2ec1510f3a7e6a9956d317f82db731b5.js:67314
    _runExpiredTimers self-hosted:874
  1. Here is the program code as presented by the Firefox code debug listing with the triggering code line indicated, when the execution was interrupted:
...
var saveOrderFunc = function saveOrderFunc(namelist) {
  return new Ember.RSVP.Promise(function (resolve, reject) {
    (0, _jquery.default)("#sortOrder").text(namelist);
    var IMDB_DIR = (0, _jquery.default)('#imdbDir').text();
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'saveorder/' + IMDB_DIR);
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        userLog("SAVE");
        resolve(true);
      } else {
        userLog("SAVE error");
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.send(namelist);
  }).catch(function (error) {
    console.error(error.message);
  });
};
Ember.run.later(function () {
  saveOrderFunc(nameOrder.trim()).then(function () {   //  (<***)
    if (n && n <= 100 && loginStatus === "guest") {
      Ember.run.later(function () {
        (0, _jquery.default)("div[aria-describedby='dialog'] button#yesBut").click();
      }, 20);
    }

  });
}, 400);
...

May this be an Ember system bug, or what's up?

$ ember -v ember-cli: 3.11.0 node: 8.17.0 os: linux x64

Why so old Ember? Have to upgrade Node first. Why so old Node? Several dependent packages are still lagging; postponed the next upgrade a few months.




dimanche 8 mars 2020

Getting error after migrating to Ember octane

I am using Ember 3.16.3 and i am getting this error on the following code :

Error: Assertion Failed: You must pass a function as the second argument to the on modifier

//login.hbs

 <form >
       <Input type="email" placeholder="email" @value= />
      <button type="submit">login</button>
 </form>

.

//login.js

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

import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class LoginRoute extends Route {

   @tracked email = '';

   @action
   login(event) {
     event.preventDefault();

     // do some operations ...
  }
}



vendredi 6 mars 2020

Handle incorrect path in an EmberJS route

If an invalid customer_id is entered, I'd like the user to be redirected to 404. I cannot handle it in the route.js, since the adapter error is breaking the application even before the model() {} is visited.

router.js:

this.route('profile_details', { path: '/profile_details/:customer_id' });

route.js:

import AuthenticatedRoute from 'employer/mixins/authenticated-route';
import ApplicationRoute from 'employer/application/route';
import { inject as service } from '@ember/service';

export default ApplicationRoute.extend(AuthenticatedRoute, {
  router: service(),

  model() {
    const { customer_id } = this.paramsFor('profile-details');
    return this.store.findRecord('customer', customer_id).catch(()=> {
      this.router.transitionTo('404');
    });
  },
});

Is there a way I could handle that in the application.js adapter?

import DS from 'ember-data';
import ApplicationAdapterMixin from 'common/mixins/application-adapter';

const { RESTAdapter } = DS;

export default RESTAdapter.extend(ApplicationAdapterMixin, {
  handleResponse(status, headers, payload, requestData) {
    if(status === 404) {
      //Can I use the router service inside an adapter to transition?
    }
  }
});



In Ember.js, ID of the sub-array elements are not passed within ajax put

I do a put call in ember.js and I am passing an object which contains an array. The element's id in this array are never passed to the backend, yet they do exist in the object.

I do a put call using

this.ajax.put('path', { data: object }.then();

The object that I am passing as the data has an array (example of the DTO).

object = {
  "array": [
    {
      "id": 0,
      "prop1",
      "prop2",
      "etc..."
    }
  ],
  "prop1",
  "prop2",
  "etc..."
}

The way that I construct each object from the array is by using

let objectArray = get(object, 'array');
let elementInObjectArray = //ajax call to get the element to add;
objectArray.pushObject(store.createRecord('element-in-object-array', { 
   id: elementInObjectArray.id,
   prop1: elementInObjectArray.prop1,
   etc...
})

Just before my put call, I log the id of the object.array.element.id, and they are defined and accessible (as string). (See image)

enter image description here

Yet, this id is never passed to the backend, and then I get a 404 from the server because the id is the primarykey. (See image of my put request payload)

enter image description here

I know that ember always return a string as an id when creating a record, but I don't think this is the reason why it fails since I would probably get more like a 400 for bad formatting. Right now, the id is just never passed.

How can I make sure that the id of the array element is passed in the call?




mercredi 4 mars 2020

Adding a custom variable to EmberRouter and then using it in another file

I recently tried extended the EmberRouter to include the following piece of information.

router.js

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

const Router = EmberRouter.extend({
  lastVisitedURL: null,

  init() {
    this._super(...arguments);
    this.on('routeWillChange', () => {
      this._super(...arguments);
      this.lastVisitedURL = this.currentURL;
    });
  }

  // Router.map code (not important)
})

I would now like to extract lastVisitedURL from a controller file. However, I'm not sure how to do it. Some of the things I've tried include importing the EmberRouter directly (I.E.):

import Router from '../router';

export default Controller.extend({
   someFunction() {
     console.log(Router.lastVisitedURL); // returns undefined
   }
});

I'm not perfectly sure what the problem is with this approach, but it appears to be returning me some sort of other object or function that doesn't truly contain the state of the router.

So the next approach, that seems to be a little more accepted, was to try to use the RouterService object that I believe is meant to provide an API to the EmberRouter.

import Router from '../router';

export default Controller.extend({
   router: service(),

   someFunction() {
     console.log(this.router.currentURL) // returns undefined
   }
});

The problem I encountered with this solution though is that even though the routerService can store the state of the EmberRouter, it doesn't store my specific new variable. So I now need a way to add this specific pice of data to the RouterService as well as the EmberRouter.

I'm not really sure how to do this or if there is a better approach to the problem I'm trying to solve. Any thoughts appreciated!




mardi 3 mars 2020

What is the difference between memberAction and collectionAction in ember-api-actions

I am new the ember , what is the difference between memberAction and collectionAction in ember-api-actions.

i know these are used to get response data from backend . thanks .




lundi 2 mars 2020

How to handle right-click "open in new tab" in EmberJs action?

I have a link which calls an action on click like below. I haven't populated the href because I want this handled in the action and I don't want to trigger a page reload.

HBS

<a class="cursor-pointer" >Next</a>

JS

@action
goToPage(pageName) {
  this.args.pageUpdated('page', pageName.toString());
  // scroll to top of search results
  document.querySelector('.search-summary-title').scrollIntoView();
}

Is there a way to direct the user to the right page if they right-click and choose "open in new tab"?




Transform data between ember-changeset property and Input @value

I have an ember-data model, with some non-string properties.

I have an edit form, where I am using emberjs's Input helper to allow the user to edit it, and then I am using ember-changeset-validations to only update the underlying model if the user input is valid.

What I am confused about at the moment, is how can I transform the data coming from the Input helper (which comes back as a string) into the proper type for my ember-changeset-validations to work properly?

I feel like I need another helper in-between that does the serialization/deserialization between the raw data type and a string. But I'm not sure if this is possible.

Another option I can think of is create new components that inherit the Input helper component, one for each specific data type that I have...but that seems like overkill.




dimanche 1 mars 2020

.NET Core 3.1 CORS not working on Ember (3.12) web UI

I have followed the Microsoft migration instructions and placed the call to the CORS middleware between UseRouting and UseEnpoints. However, I am still getting CORS errors.

In the ConfigureServices method, I have: Services.AddCors(); In the Configure method, I have:

app.UseRouting();

app.UseCors(options => options
        .AllowAnyOrigin()
        .AllowAnyHeader()
    );

app.UseAuthentication();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

The console error is:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/users/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/users/login. (Reason: CORS request did not succeed).

Any idea what is causing the problem?




How to implement conditional operator in hbs for ember app

I have implemented a check on hbs for styling a page

I have two style class

open-gl
open-tx

with below code , I can apply a style to a div tag

but how to implement a else function here

it is like

thanks , i tried it but it is not working