jeudi 27 février 2020

Replace deprecated `this.$()` in Ember 3

this.$() has been deprecated in Ember.js and will be removed in Ember 4. It should be replaced with native Javascript. Still, the migration could be hard to do in one shot.

Is this the right way to replace previous this.$() while continuing using JQuery?

// BEFORE
this.$().on('transitionend', () => this.doSomething());

// AFTER
import $ from 'jquery';

$(this.element).on('transitionend', () => this.doSomething());

Or is there another approach?




How to fire a get request between rails and ember

I am new to frontend development,I am using rails and ember to built a sample app .

in rails , i have a function as below

def get_id 
      first_id = User.first.id
     render json: { id: first_id , type: "master"} 
end 

I want to fire a GET request from ember side to call the get_id in ember side which will return the required response . thanks .




vendredi 21 février 2020

Pass list of integers as parameters to Ember transitionTo()?

I'm trying to pass a list of integers (of the form [1,5]) as params in transitionTo in Ember 3.14. I've verified that the list can be read within this function:

  afterModel() {
    this.transitionTo('newRoute', this.modelFor('lastLevel').list);
  },

But I always get this error:

Cannot read property '0' of undefined TypeError: Cannot read property '0' of undefined

How should I transform the list so it will pass into transitionTo()?




Passing values to ember.js components when they are passed as an argument to addin (eg ember-bootstrap-modals-manager)

I have a question about the addon ember-bootstrap-modals-manager but it's possible the issue I'm describing may occur with other Ember addons.

Using ember-bootstrap-modals-manager you can display an alert dialog with a custom body. Here's a screen dump of an example.

enter image description here

To do this you create an Ember component, the template of which contains your custom body markup, for example ...

<p class="alert alert-info">
  Custom Alert Body Component
</p>

... you can then specify that the body of the alert should use that markup by specifying the name of the component when invoking the alert dialog, like this (assuming the component created is called custom-alert-body) ...

showCustomAlertModal() {
    const options = {
      bodyComponent: 'custom-alert-body',
    };
    set(this, 'options', options);
    get(this, 'modalsManager')
      .alert(options);
 }

... that's fine as it stands but if you want to inject values into the component template, for instance like this ...

<p class="alert alert-info">
  Custom Alert Body Component. The alert msg is : 
</p>

... it's not obvious how you can do that because unlike with 'normal' component usage you're not invoking the component in question within a template but just specifying the name in your code .

So my question is (if you're familiar with ember-bootstrap-modals-manager) how can you have a custom body which accepts a value at runtime or (if you're not familiar with it) have you ever seen components used like this in a different context and if so how did they accept a runtime value ?




Is it possible to ignore a cucumber hook if a specific tag is being used

Is it possible to ignore a hook if a specific tag is being used?

If @someTag is used then I need the beforeAll to refer to an import with the alias, 's2'.
Otherwise I need the beforeAll to refer to scope without the alias, 's'.

If I run a test with @someTag, then I would expect to only see 'In BeforeAll @someTag - hooks.js' printed in the console - but instead, they both run.

import s from "../location1/s";
import * as s2 from "../location2/s";

BeforeAll("not @someTag", async () => {
  console.log("In BeforeAll - hooks.js");
  s.driver = puppeteer;
})
BeforeAll("@someTag", async () => {
  console.log("In BeforeAll @someTag - hooks.js");
  s2.driver = puppeteer;
});



Ember dynamic router redirect

I have the blow route in my route.js file

this.route('view', {path: 'view/:id'}, function() {
  this.route('page');
  this.route('detail');
});

When I call this from my index.js route file it's not working.

this.transitionTo('/view/123/page');

It stops in the browser like /view/123 and the 'page' is not loaded. Can you anyone help me to resolve this.




jeudi 20 février 2020

ember-paper checkbox ripple effect stuck

We have an ember app (v.3.4) with a list of checkboxes and icon buttons in ember-paper, and half of the time, when you click on a checkbox or icon button, the ripple effect gets stuck and leads to nothing else is clickable anymore. The checkbox/buttons are pretty close to each other due to space constraints. One can only reload it to get everything back to normal. I have done some research but have not gained much insight as to what is happening.

  1. Is it the ripple effect causing the problem? If so, how can I disable it in ember-paper?
  2. Is the proximity of these controls causing the problem?



Uncaught TypeError: scope.observeChanges is not a function

Hi I am using Ember Javascript Library, I am getting the following error:

Uncaught TypeError: scope.observeChanges is not a function

My Code is as below:

   didInsertElement: function () {
        var scope = this;

        setTimeout(function () {
            var value = Ember.get(scope, 'value');
            var element = $(scope.element);
            var change = function () { Ember.set(scope, 'value', element.val()); }
            element.val(Ember.get(scope, 'value'));
            element.attr('type', 'text');
            element.change(change);
            // element.keypress(change);
            Ember.set(scope, 'loaded', true);
            scope.observeChanges();
            element.inputmask({
                mask: Ember.get(scope, 'mask')
            });

            element.attr('input-format', Ember.get(scope, 'input-format'));
            element.attr('input-filter', Ember.get(scope, 'input-filter'));
            element.attr('input-filter-message', Ember.get(scope, 'input-filter-message'));

        }, 250);
    }

Its not giving me any issues for running the application - but when I use Debugger, I am getting the above mentioned error - what can I do to fix this issue - thank you.




mercredi 19 février 2020

Ember Simple Auth Change Default Store

I'm new to ember and ember-simple-auth. My app uses Pods mode. Currently I'm building a login page and want to use SessionStorageStore to store user information, so that the info stored in session storage will be cleaned after closing the browser. Ember-simple-auth uses local storage by default. How can I change the default store? The method mentioned in the API doc seems not work for me. The info is still stored in the local storage. Any ideas how to change the default store?My Project Layout




Ember.js : Make country Code attribute of phone number and ultimately stored with phone number input field

I am trying to implement country dialing code dropdown for a input field which is currently set as type="text". Here is the current code .

I came up with the follwing solution ,

        <div class="ui left action input">
          
            <i class="dropdown icon"></i>
            <div class="default text"></div>
            <div class="menu">
              
                <div class="item">
                  <i class=" flag"></i>
                  
                </div>
              
            </div>
          
          
        </div>

but the problem is that country code is not being saved.

How can I implement it with ember.js????

I got hint from a developer , he said

Code should be a attribute of phone number and ultimately will be stored with phone number.

how to implement the above line?




Ember data - use property other than id for hasMany relationship

I have a many-to-many relationship defined between my tag and payment models as shown below.

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

export default Model.extend({
  name: attr('string'),
  backgroundColour: attr('string'),
  textColour: attr('string'),
  payments: hasMany('payment')
});
// models/payment.js
import Model, { attr, hasMany } from '@ember-data/model';

export default Model.extend({
  date: attr('date'),
  amount: attr('number'),
  paymentId: attr('string'),
  tags: hasMany('tag'),
});

By default, when I add tags to payments, the id of the payment is used as the key for the relationship. My aim is for Ember data to use the paymentId property as the key for this relationship instead.

The snippet below shows the structure of the data I'm loading, where a tag references payments by the paymentId property.

    // Example tag
    {
      "id": "25",
      "name": "Groceries",
      "backgroundColour": "31b04b",
      "textColour": "ffffff",
      "payments": ["20190121201902210"] // References paymentId rather than id
    },
    
    // Example payment
    {
      "id": "1"
      "date": "2019-01-27T22:00:00.000Z",
      "amount": 1644.44,
      "paymentId": "20190121201902210",
      "tags": ["25"]
    }

I've tried to customise the payment serializer as below,

// serializers/payment.js

import ApplicationSerializer from './application';

export default ApplicationSerializer.extend({
  keyForRelationship(key, _relationship) {
    if (key === 'payments') {
      return 'paymentId';
    }
  },
});

However, when the models are loaded I get this error: Assertion Failed: All elements of a hasMany relationship must be instances of Model, you passed [ "20190121201902210" ].

How can I make Ember data use paymentId rather than id when looking up related payments?




lundi 17 février 2020

Ember 3.16 Octane - Component not displaying in Application.hbs

I used ember generate to create a header component for a youtube video I am following. I have a few questions -

  1. When I ran ember generate component header, the terminal responded with creating the header.hbs file in app>components, but then skips header.js in app/components. I manually created a header.js file in that directory and if I do an alert() in the js file it works.

  2. I have the following code in my header.hbs file.

<h1>Hello There!</h1>


In my application.hbs file :

<Header/>



thoughts, suggestions? Thank you for any help in advance!




dimanche 16 février 2020

Problems with Ember, PostCSS, SASS and @apply

I'm trying to use TailwindCSS in my ember app and I ended up using this add-on to do this. But unfortunately some other add-ons require to include their 'scss' files to app styles. So I tried to add 'postcss-sass' to make it work. But it doesn't want to work with "@apply" command. Is it possible to use postcss and sass and @apply command at the moment?

My ember-cli-build.js:

postcssOptions: {
      compile: {
        extension: 'scss',
        enabled: true,
        parser: require('postcss-scss'),
        plugins: [
          {
            module: require('@csstools/postcss-sass'),
            options: {
              includePaths: ['node_modules']
            }
          },
          require('tailwindcss')('./app/tailwind/config.js'),
          ...isProduction ? [purgeCSS] : []
        ]
      }
    }

And I'm getting an error: UnhandledPromiseRejectionWarning: Error: Invalid mapping: {"generated":{"line":53,"column":-1},"source":"../../out-338-broccoli_merge_trees_full_application/app/styles/app.scss","original":{"line":52,"column":25},"name":null}

This is precisely where @apply appeared the first time.




samedi 15 février 2020

How to set initial state of glimmer component based on argument?

I am struggling to figure out how to implement data down, actions up in a glimmer component hierarchy (using Ember Octane, v3.15).

I have a parent component with a list of items. When the user clicks on a button within the Parent component, I want to populate an Editor component with the data from the relevant item; when the user clicks "Save" within the Editor component, populate the changes back to the parent. Here's what happens instead:

GIF of my app

How can I make the text box be populated with "Hello", and have changes persisted back to the list above when I click "Save"?

Code


<ul>

    <li> <button >Edit</button></li>

</ul>

<Editor @currentModel= @save= />
// app/components/parent.js
import Component from '@glimmer/component';
export default class ParentComponent extends Component {
    @tracked models = [
        { id: 1, text: 'Hello'},
        { id: 2, text: 'World'}
    ]
    @tracked currentModel = null;

    @action
    edit(model) {
        this.currentModel = model;
    }

    @action
    save(model) {
        // persist data
        this.models = models.map( (m) => m.id == model.id ? model : m )
    }
}


<small>Editing ID: </small>

<Input @value= />
<button >Save</button>
// app/components/editor.hbs
import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";

export default class EditorComponent extends Component {
    @tracked text;
    @tracked id;

    constructor() {
        super(...arguments)
        if (this.args.currentModel) {
            this.text = this.args.currentModel.text;
            this.id = this.args.currentModel.id;
        }

    }

    @action
    save() {
        // persist the updated model back to the parent
        this.args.save({ id: this.id, text: this.text })
    }
}

Rationale/Problem

I decided to implement Editor as a stateful component, because that seemed like the most idiomatic way to get form data out of the <Input /> component. I set the initial state using args. Since this.currentModel is @tracked in ParentComponent and I would expect re-assignment of that property to update the @currentModel argument passed to Editor.

Indeed that seems to be the case, since clicking "Edit" next to one of the items in ParentComponent makes <small>Editing ID: </small> appear. However, neither the value of the <Input /> element nor the id are populated.

I understand that this.text and this.id are not being updated because the constructor of EditorComponent is not being re-run when currentModel changes in the parent... but I'm stuck on what to do instead.


What I've tried

As I was trying to figure this out, I came across this example (code), which has pretty much the same interaction between BlogAuthorComponent (hbs) and BlogAuthorEditComponent (hbs, js). Their solution, as applied to my problem, would be to write EditorComponent like this:



<small>Editing ID: </small>
<Input @value= />
<button >Save</button>

// app/components/editor.hbs
import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";

export default class EditorComponent extends Component {
    get isEditing() {
        return !!this.args.currentModel
    }

    @action
    save() {
        // persist the updated model back to the parent
        this.args.save({ id: this.id, text: this.text })
    }
}

enter image description here

It works! But I don't like this solution, for a few reasons: - Modifying a property of something passed to the child component as an arg seems... spooky... I'm honestly not sure why it works at all (since while ParentComponent#models is @tracked, I wouldn't expect properties of POJOs within that array to be followed...) - This updates the text in ParentComponent as you type which, while neat, isn't what I want---I want the changes to be persisted only when the user clicks "Save" (which in this case does nothing) - In my real app, when the user is not "editing" an existing item, I'd like the form to be an "Add Item" form, where clicking the "Save" button adds a new item. I'm not sure how to do this without duplicating the form and/or doing some hairly logic as to what goes in <Input @value...

I also came across this question, but it seems to refer to an old version of glimmer.

Thank you for reading this far---I would appreciate any advice!




How to deploy Ember.js/Node.js/MongoDB application to Heroku?

I've just finished my application which uses Ember.js as a frontend framework, Node.js for my REST API and MongoDB as the default database. I'm trying to deploy the application to Heroku, but it doesn't seem to work properly. I have my Ember code in the folder ember-store and my API in ember-store/store-api. The app is deployed, but not functional when I open it up, Heroku gives me the following error: "An error occurred in the application and your page could not be served."

My node.js code looks like this:

const http = require('http'); // Import http package
const app = require('./app'); // Import app.js file from current directory

const port = process.env.PORT || 3000;

const server = http.createServer(app);

server.listen(port);

In my Ember application, I have the following adapters:

adapters/application.js

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

export default RESTAdapter.extend({
  namespace: 'api',
  host: 'http://localhost:3000'
});

adapters/order.js

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

export default RESTAdapter.extend({
  host: "http://localhost:3000",
});

adapters/product.js

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

export default RESTAdapter.extend({
  urlForFindAll() {
    return 'http://localhost:3000/products';
  },
});

I'm assuming I need to replace 'localhost:3000' in my adapters, but I don't think it's gonna resolve the issue. Is there a guide on how can I deploy it to Heroku(or anywhere else)? Any help would be greatly appreciated!




vendredi 14 février 2020

How do I render the values returned from a computed property in Ember.js?

I have the following code in the template of my component:

      <th scope="row"></th>
      <td>Name: 
      </td>
      <td>Delivery address: 
          Products in order: 
          Items: 
      <td>$</td>
</tr>

And I have my computed property which should return and render each product name in the array of objects returned from the database:

items: computed('order.products', function() {
        let products = this.get('order.products');
        products.forEach(product => {
            for(let i=0; i<products.length; i++){
                return console.log(products[i].name);
            }
        });
    }),

And when I run the following everything works okay and the names are displayed in the console like this:

Cheese on toast
3 Pizza
2 Macaroons bowl

But when I try to remove console.log and just return products[i].name, nothing seems to be returned. Am I missing something or trying to render it on my page incorrectly?




jeudi 13 février 2020

Is it possible to use ember-cli-addon-docs with an in-repo addon?

I have an ember.js in-repo addon and would like to add documentation using ember-cli-addon-docs. Is this possible?

I installed the addon at application level and in my ember-cli-build.js I added:

'ember-cli-addon-docs': {
    documentingAddonAt: 'lib/my-addon',
},

but this does not work and I keep getting an error in my terminal: Cannot read property 'url' of undefined

Was anyone successful with a simmilar setup




Using EmberJS and Oauth2, how can I modify the default route after invalidation?

My goal is to send the user to a different page/route other than the oauth default after invalidation. Currently the default is my root login page. How can I change this?

I have this logout code in app/controller/protected.js. Specifically the .invalidate(); method is what I'm trying to modify.

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

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

    actions: {
        invalidateSession() {
      this.get('session').invalidate();

        }
  }
});

This is my code in app/routes/protected.js

import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Route.extend(AuthenticatedRouteMixin, {
});

Any help is much appreciated!




How do I import a scss npm module into Ember

How do I correctly import a non-plugin npm module into Ember?

I'm trying to use the sass version of flag-icon-css with ember-cli so that the sass is being built during deploy with the rest of ember-cli-sass, but I can't figure out how to do it in an automated fashion (e.g. without manually copying files over to public).

Using ember-auto-import seems like a good place to start but it is more tailored towards javascript imports.

I have read this documentation, but it doesn't specify something more complicated than a single file.




How can I update record with Ember Data using NodeJS backend?

I have the following logic in my application: on the main page I have a list of products that I'm getting from my MongoDB database, each product has a quantity. When a user clicks on the button 'add to cart' next to the product, this product is saved in the local storage when the user adds more of a specific product, the available quantity is reduced (example: "product": "apple", "quantity": "10", when in cart: "quantity": 5 (user added 5 apples)).

I'm sending the list of added products as an order which is being saved on the backend in the database. My goal is to update the number of products on the main page, if user ordered 5 of 10 apples, there should be 5 apples left when I go to the home page. I'm not sure how to update it on the frontend. My Ember code looks like this:

cart.hbs:

<form onsubmit=>

controllers/cart.js:

        createOrder(event){
            event.preventDefault();              
            let order = this.store.createRecord('order', {
                customer_name: this.name,
                customer_phone: this.phonenumber,
                products: this.get('cart.items'), // getting the array of products
            });
            order.save();
        },

My node.js code looks like this:

routes/orders.js POST Requst

router.post('/', (req, res, next) => {
    const order = new Order({
        _id: new mongoose.Types.ObjectId(),
        customer_name: req.body.order.customer_name,
        total_price: req.body.order.total_price,
        products: req.body.order.products,
    });
    order
    .save()
    .then(result => {
    .... 
    }

routes/products.js PATCH Request

    const id = req.params.productId;
    const updateOps = {};
    for(const ops of req.body){
        updateOps[ops.propName] = ops.value;
    }
    Product.update({ _id: id }, { $set: updateOps})
    .exec()
    .then(...)

All I need to do is get the available quantity of each product in the order and update it in my database with products with a PATCH request, the request should look like this:

   "propName": "available_quantity",
   "value": "" - the available quantity from the order
 }]

I've been trying to figure it out for a couple of days and still no success. I think I just got lost in my own code logic.




mercredi 12 février 2020

How to use ember sass in ember addon and correctly implement it into ember project

The following problem needs to be solved: I try to create a component within an ember addon, that's using sass. Within my addon I don't want to compile that scss files, that should be done within my project using ember-cli-sass and ember-css-modules-sass. The component I'm creating in my addon is also using sass modules, but I didn't install the ember packages for this, because I do that in my project.

I run into the problem, that when I try to serve my ember application from my project directory, I get the error that within my addon an imported scss file is unreadable or not there.

What am I doing wrong? Thank you very much!




mardi 11 février 2020

how to exclude image files within public folder

In the public folder, I have two folder hk and sg, they have different image files.
What I want is if I build hk package, I only copy images from hk folder.
How to exclude the sg folder in ember-cli?




Azure AD Auth Ember JS v3.15

I'm a noob with JS in general, but I've put together a simple app for work that embeds a Tableau dashboard using Ember.JS. I'm starting to think Ember just isn't right, but I have zero familiarity with anything else.

I have an index route with a short message to users, and a login with Microsoft button. I'd like to use Azure AD only to authenticate business users when they click the button. The return URL would be the embedded route, and the application route just has some header and footer info.

I tried picking apart the sample [https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-single-page-app?tabs=applications], and I'm not getting anywhere. I don't even know what errors would be meaningful, since I'm not even sure this can work.

I've placed this in my index.html file ..

<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.2.1/js/msal.js" integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>
<script type="text/javascript">
    if(typeof Msal === 'undefined')document.write(unescape("%3Cscript src='https://alcdn.msftauth.net/lib/1.2.1/js/msal.js' type='text/javascript' integrity='sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP' crossorigin='anonymous'%3E%3C/script%3E"));
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" class="pre"></script>

I have the buttons in my index.hbs file ..

<button onclick="signIn()" type="submit" id="ms-login" />
<button type="button" class="hide" onclick="callApi()">Call Web API</button>

Now I'm trying to figure out what to do with this ..

<pre class="response"></pre>

<script class="pre">

  // The current application coordinates were pre-registered in a B2C tenant.
  var appConfig = {
    b2cScopes: [?],
    webApi: "?"
  };

</script>

<script>
  "use strict";

  // configuration to initialize msal
  const msalConfig = {
      auth: {
          clientId: "{Application (client) ID}", //This is your client ID
          authority: "?", //This is your tenant info
          validateAuthority: false
      },
      cache: {
          cacheLocation: "localStorage",
          storeAuthStateInCookie: true
      }
  };

  // instantiate MSAL
  const myMSALObj = new Msal.UserAgentApplication(msalConfig);

  // request to signin - returns an idToken
  const loginRequest = {
      scopes: appConfig.b2cScopes
  };

  // request to acquire a token for resource access
  const tokenRequest = {
      scopes: appConfig.b2cScopes
  };

  // signin and acquire a token silently with POPUP flow. Fall back in case of failure with silent acquisition to popup
  function signIn() {
      myMSALObj.loginPopup(loginRequest).then(function (loginResponse) {
          getToken(tokenRequest).then(updateUI);
      }).catch(function (error) {
          logMessage(error);
      });
  }

  //acquire a token silently
  function getToken(tokenRequest) {
      return myMSALObj.acquireTokenSilent(tokenRequest).catch(function(error) {
        console.log("aquire token popup");
        // fallback to interaction when silent call fails
        return myMSALObj.acquireTokenPopup(tokenRequest).then(function (tokenResponse) {
        }).catch(function(error){
          logMessage("Failed token acquisition", error);
      });
    });
  }

  // updates the UI post login/token acqusition
  function updateUI() {
    const userName = myMSALObj.getAccount().name;
    console.log(myMSALObj.getAccount());
    logMessage("User '" + userName + "' logged-in");

    // add the logout button
    const authButton = document.getElementById('auth');
    authButton.innerHTML = 'logout';
    authButton.setAttribute('onclick', 'logout();');

    // greet the user - specifying login
    const label = document.getElementById('label');
    label.innerText = "Hello " + userName;

    // add the callWebApi button
    const callWebApiButton = document.getElementById('callApiButton');
    callWebApiButton.setAttribute('class', 'visible');
  }

  // calls the resource API with the token
  function callApi() {
    getToken(tokenRequest).then(function(tokenResponse) {
      callApiWithAccessToken(tokenResponse.accessToken);
    });
  }

  // helper function to access the resource with the token
  function callApiWithAccessToken(accessToken) {
    // Call the Web API with the AccessToken
    $.ajax({
      type: "GET",
      url: appConfig.webApi,
      headers: {
        'Authorization': 'Bearer ' + accessToken,
      },
    }).done(function (data) {
      logMessage("Web APi returned:\n" + JSON.stringify(data));
    })
      .fail(function (jqXHR, textStatus) {
        logMessage("Error calling the Web api:\n" + textStatus);
      })
  }

  // signout the user
  function logout() {
    // Removes all sessions, need to call AAD endpoint to do full logout
    myMSALObj.logout();
  }

  // debug helper
  function logMessage(s) {
    document.body.querySelector('.response').appendChild(document.createTextNode('\n' + s));
  }

</script>

Then, if this is possible in Ember, I'm unsure what to put for b2cScopes and webApi here ..

<script class="pre">

  // The current application coordinates were pre-registered in a B2C tenant.
  var appConfig = {
    b2cScopes: [?],
    webApi: "?"
  };

</script>

Also, what goes in the Authority here? The example has a tenant url, but once I created the App Registration, I was only provided a Directory (tenant) ID GUID.

const msalConfig = {
    auth: {
        clientId: "{Application (client) ID}", //This is your client ID
        authority: "?", //This is your tenant info
        validateAuthority: false
    },
    cache: {
        cacheLocation: "localStorage",
        storeAuthStateInCookie: true
    }
};

Thank you for looking at this, and I'm sorry if I haven't provided enough info to solve. Python and SQL are easy peezy lol, but JS won't stop kicking me while I'm down!




lundi 10 février 2020

I get error in console after install ember-cli-content-policy

vendor-suffix.js:1 [Report Only] Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'nonce-abcdefg' localhost:4200 0.0.0.0:4200".

i installed ember-cli-content-policy and i m trying to override default configuration by adding

ENV.contentSecuityPolicy in environment.js

but i cannot the configuration still default and i get the error when ever i ran the app




How can I prevent the application.hbs from appearing in its routes

I have an Ember application that has several routes. I however don't want the content from application.hbs in appearing in its routes. I have tried: renderTemplate: function () { this.render("another_outlet"); } but it shows content from "another_outlet.hbs' alongside content from "application.hbs" in the route




dimanche 9 février 2020

Ember Web Application with Form based Authentication in Tomcat

I am new to Ember. I have created an Ember application which uses Tomcat Form based authentication. When I hit the protected URL, the protected page gets loaded instead of the page getting redirected to the login route.




vendredi 7 février 2020

Integrate monaco editor into ember octane

I try to integrate the monaco code editor into my ember octane application. Currently I'm using the ESM import style and confirming to the manual, I installed the webpack loader plugin and integrated it into my ember-cli-build.js

const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    autoImport: {
      webpack: {
        plugins: [
          new MonacoWebpackPlugin()
        ]
      }
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};

But when building my application, I always get the error messages:

Module parse failed: Unexpected token (8:0) You may need an appropriate loader to handle this file type.

And

(node:7993) UnhandledPromiseRejectionWarning: Error: webpack returned errors to ember-auto-import

Can anyone help me and tell me how to integrate monaco correctly into my ember application? Thank you very much!




how to do a store.query or AJAX call in a helper (ember.js)

I'm building a profile web using ember.js and CodeIgniter (PHP) as the backend framework, I'd like to make a helper to get my web configurations stored in Back-end database in key-value manner.

enter image description here

I have the API ready in the backend to get the configuration (localhost/api/get_config) an ajax call to

localhost/api/get_config&key=phone will return a string of "123123123"

and a call to

localhost/api/get_config&key=address will return a string of "Testing ave 102"

How to make a helper to get the values based on the key provided. for example will return 123123123.

If possible, I would also like to use the namespace and host configuration in application's adapter to do the query or make the ajax call. now my adapter config are

export default JSONAPIAdapter.extend({
    host: "http://localhost",
    namespace: 'api'
});



ember-data and json-patch requests

Can ember-data send json-patch PATCH on model.save() call? (with media type application/json-patch+json RFC6902)

The documentation says yes but with no details:

https://guides.emberjs.com/release/models/creating-updating-and-deleting-records/#toc_persisting-records

Testing it shows PUT requests with the entire model in the request.




jeudi 6 février 2020

Ember Super Rentals Tutorial 3.15 - Working with data

I was following the ember Super Rental 3.15 tutorial, when I got to the working with data section, I updated the route index file with model hooks, the page stopped working. Also I am finding ember tutorials to be incomplete.

error says property of map is undefined code in routes index.js file:

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

const COMMUNITY_CATEGORIES = [
  'Condo',
  'Townhouse',
  'Apartment'
];

export default class IndexRoute extends Route {
  async model() {
    let response = await fetch('/api/rentals.json');
    let { data } = await response.json();

    return data.map(model => {
      let { attributes } = model;
      let type;

      if (COMMUNITY_CATEGORIES.includes(attributes.category)) {
        type = 'Community';
      } else {
        type = 'Standalone';
      }

      return { type, ...attributes };
    });
  }
}

image if error message:enter image description here




mercredi 5 février 2020

EmberJS: Computed property awareness of dependent keys

Let's suppose I have an object that has this structure: { filters: [{ params: { value: ["abc"] }] }.

How can I write a computed property that is aware of changes to the value property? For example, let's say we take one of the filters and do set(filter, 'params.value', ["abc", "123"]). I've been trying with computed('filters.@each.params.value.[]', ...) but it isn't working




mardi 4 février 2020

EmberJS 3.15 - How to pass data from child to parent

what is the correct approach to pass data from child component to parent?

( for example, you have a simple input-like component. You can pass data into the component from parents easily. User will change an input value and now you need to pass data from the component to its parent for some reasons )

how you can pass data from child to parent ? Thank you




Why is this Ember component created twice?

So really I'm just trying to decipher how Ember works here.

So I have ComponentOne. Which has propertyA (boolean) and property2 (array). If propertyA === true, the template will render and instance ComponentTwo for each member of propertyB:


  
    
  

While working with this we discovered an issue where an event handler in ComponentTwo was not running, even though we could verify the event was firing. This was happening in a situation where propertyA === true and propertyB.length === 1.

Through some judicious breakpoints and logging to the console, I was able to determine that this was happening in this sequence:

  1. an instance of ComponentTwo is created
  2. A second instance of ComponentTwo is created, using the same object for data.
  3. The first instance created in step 1 is destroyed.

The theory is that this is messing up the event handler because that handler was set in ComponentTwo.init() and removed in ComponentTwo.willDestroy(). Eventer being a singleton, it removes it for both instances of the component.

So my question is why would Ember create two instance at all? There's only one member of the array it's iterating.




EmberJS Octane set focus on element

I have component that contains a number of text areas and a button to add another text area. When the user clicks the button, a new text area is added. I want the focus to move to this new text area.

I saw this answer but it's for an older version and we are not using jQuery with Ember.

How do I set the focus to a specific text area using Ember glimmer objects with the new Ember Octane framework.




navigator.mediaDevices.ondevicechange not working while using audio jack

I'm trying to change the device change events using MediaDevice API as below

_trackDeviceChange: function () {
        var e = this
        navigator.mediaDevices.ondevicechange = function () {
          navigator.mediaDevices.enumerateDevices().then(function (n) {
            e.get('allVideoSourceDevices').clear(),
            e.get('allAudioSourceDevices').clear(),
            e.get('allVideoSourceDevices').pushObjects(t.default.filter(n, [
              'kind',
              'videoinput'
            ])), e.get('allAudioSourceDevices').pushObjects(t.default.filter(n, [
              'kind',
              'audioinput'
            ])), e.get('videoSourceDevice') && !t.default.find(n, {
              deviceId: e.get('videoSourceDevice.deviceId'),
              kind: 'videoinput',
              label: e.get('videoSourceDevice.label')
            }) ? e.set('deviceNotFound', 'camera')  : e.get('audioSourceDevice') && !t.default.find(n, {
              deviceId: e.get('audioSourceDevice.deviceId'),
              kind: 'audioinput',
              label: e.get('audioSourceDevice.label')
            }) && e.set('deviceNotFound', 'microphone')
          })
        }
      }

It is working only for USB devices not working for 3.5m jacks




The value of object's property is not being changed in the Local Storage in Ember

I'm building a shop in Ember with the list of products that are being added to Local Storage when the user clicks on the 'add to cart' button. Each product is an object that has a property called 'ordered_quantity', I'm trying to change this property's value when the user tries to remove the product from the cart. (example: 'ordered quantity: 8', when the button is clicked it should be 7). I have the following code in my service file:

  remove(item) {
    let new_arr = this.get('items');
    let elementIndex = new_arr.findIndex(obj => {
      return obj.id === item.id;
    });

    if (elementIndex !== -1) {
      new_arr[elementIndex].ordered_quantity = new_arr[elementIndex].ordered_quantity - 1;
    } 
    this.set('cart.items', new_arr);
  }

I'm using Local Storage add-on (https://github.com/funkensturm/ember-local-storage#methods)

and I have the following action:

  actions: {
  removeFromCart(){
  this.get('cart').remove(this.product);
}}

When I try to run the following code I get an error: Uncaught Error: Assertion Failed: You attempted to update [object Object].ordered_quantity to "7", but it is being tracked by a tracking context, such as a template, computed property, or observer. In order to make sure the context updates properly, you must invalidate the property when updating it. You can mark the property as @tracked, or use @ember/object#set to do this.

I tried using the set function like this:

let updated = item.ordered_quantity - 1;
set(item, 'ordered_quantity', updated);

https://api.emberjs.com/ember/release/functions/@ember%2Fobject/set and the code worked with no errors as expected, but the value of my property 'ordered_quantity' was not updated in the Local Storage.




lundi 3 février 2020

Url Mapping in Ember js

I have two separate routes parking and Car (not a nested route).

Parking route has dynamic segment like parking id /parking/21 and Car has car name and id /car/ford/12

Router.js:

Router.map( function() {
   this.route("parking", { path: "/parking/:parkingId"})
   this.route("car", { path: "/car/:carName/:carId" })
});

when transition from parking route to car route, i need a url like (/parking/21/ford/12)




Ember 3.6.1 inject an unknown injection: 'service:-document' after upgrade

So I'm currently trying to update my EmberJS application which was originally on version 3.0.2. Firstly I've got the app running on 3.2. I then upgraded further and was greeted with Error: Assertion Failed: Attempting to inject an unknown injection: 'service:-document' in my browser console.

The app builds successfully using ember serve but I only get a white screen next to this error, the stacktrace is also absolutely useless. The only mention of such an error is a github issue on ember-wormhole on a way older ember version and I don't even use this addon in my app. I've also realized that the app dies somewhere after app.js was executed but none of my initializers get called.

package.json:

"devDependencies": {
    "@babel/plugin-transform-block-scoping": "^7.8.3",
    "@sentry/browser": "^5.6.3",
    "@sentry/integrations": "^5.6.1",
    "broccoli-asset-rev": "^2.7.0",
    "ember-ajax": "^3.1.0",
    "ember-array-contains-helper": "^2.0.0",
    "ember-auto-import": "1.3.0",
    "ember-bootstrap": "^3.1.1",
    "ember-bootstrap-datepicker": "^2.0.1",
    "ember-changeset": "^2.2.4",
    "ember-changeset-validations": "^2.2.1",
    "ember-cli": "~3.6.1",
    "ember-cli-active-link-wrapper": "^0.5.0",
    "ember-cli-app-version": "^3.2.0",
    "ember-cli-babel": "^7.1.2",
    "ember-cli-code-coverage": "^0.4.1",
    "ember-cli-dependency-checker": "^3.0.0",
    "ember-cli-dependency-lint": "^1.0.2",
    "ember-cli-eslint": "^4.2.3",
    "ember-cli-htmlbars": "^4.2.2",
    "ember-cli-icon-rating": "^2.0.1",
    "ember-cli-inject-live-reload": "^1.8.2",
    "ember-cli-page-object": "^1.11.0",
    "ember-cli-sass": "^7.0.0",
    "ember-cli-sticky": "^0.6.4",
    "ember-cli-string-helpers": "^2.0.0",
    "ember-cli-template-lint": "^1.0.0-beta.1",
    "ember-cli-uglify": "^2.1.0",
    "ember-collapsible-panel": "^3.2.1",
    "ember-composable-helpers": "^2.0.1",
    "ember-confirm-dialog": "^1.3.0",
    "ember-countries": "^2.0.2",
    "ember-data": "~3.6.0",
    "ember-form-for-intl": "^1.0.6",
    "ember-i18n-iso-countries": "^1.5.0",
    "ember-keyboard": "^4.0.0",
    "ember-keycloak-auth": "~0.3.0",
    "ember-load-initializers": "^2.1.1",
    "ember-moment": "8.0.0",
    "ember-notify": "^5.2.0",
    "ember-pikaday": "2.4.1",
    "ember-power-select-with-create": "^0.6.0",
    "ember-qunit": "^3.4.1",
    "ember-resolver": "~5.3.0",
    "ember-route-action-helper": "^2.0.3",
    "ember-source": "~3.6.0",
    "ember-toggle": "^5.3.2",
    "eslint-config-prettier": "^4.3.0",
    "eslint-plugin-ember": "^5.2.0",
    "eslint-plugin-prettier": "^3.1.0",
    "husky": "^2.3.0",
    "keycloak-js": "^8.0.1",
    "lint-staged": "^8.1.7",
    "loader.js": "^4.7.0",
    "prettier": "1.17.1",
    "qunit-dom": "^0.8.0",
    "ui-ember-slider": "github:ifad/ui-slider",
    "watchman": "^1.0.0"
  },
  "engines": {
    "node": "6.* || 8.* || >= 10.*"
  },
  "dependencies": {
    "@babel/core": "7.8.4",
    "bootstrap": "^4.3.1",
    "bootstrap-slider": "^10.6.1",
    "ember-cli-update": "^0.27.1",
    "ember-intl": "^4.2.3",
    "global": "^4.4.0",
    "jquery": "^3.4.1",
    "npm": "^5.7.1",
    "popper.js": "^1.16.0",
    "to": "^0.2.9",
    "update": "^0.7.4"
  }

app.js:

import Application from "@ember/application";
import RSVP from "rsvp";
import Resolver from "./resolver";
import loadInitializers from "ember-load-initializers";
import config from "./config/environment";
import $ from "jquery";

window.Promise = RSVP.Promise;

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

$.getJSON("/api/env_settings", function(envSettings) {
  config.sentryDsn = envSettings.sentry;
  config.keycloak.url = envSettings.keycloak.url;
  config.keycloak.realm = envSettings.keycloak.realm;
  config.keycloak.clientId = envSettings.keycloak.clientId;
  config.keycloak.secret = envSettings.keycloak.secret;
  config.helplink = envSettings.helplink;
  config.keycloak.disable = envSettings.keycloak.disable;
});

loadInitializers(App, config.modulePrefix);
export default App;

Any ideas where the cause of this problem lies?




dimanche 2 février 2020

Ember Bootstrap 4.4.1 form input appearing below image

I have a component where the input box renders as an inline element so the form is split between the right of an image and below it, see image at the bottom. The outer div is a form group but it is not being enforced, the split is between the label and input type.

The breakpoints are implemented using ember-responsive

The Template


  <div class="image-left">
    <img src="assets/images/dreamstime_xxl_metallic_silver_tablet_q8.jpg" alt="taylor-swift-metallic-silver-tablet">
  </div>
  <div class="detail-right">
      <h2 class="no-padding-margin">FINDING TAYLOR SWIFT</h2>
    
      Jumbo view!
    
    
      Desktop view!
    
    
      Tablet view!
    
    
      Mobile view!
    
    <UserAction/>
  </div>



<h2>FINDING TAYLOR SWIFT</h2>
<div class="mobile-image">
  <img src="assets/images/dreamstime_xxl_metallic_silver_mobile_q8.jpg" alt="taylor-swift-metallic-silver-mobile">
</div>
<UserAction/>

The Component

<form class="outline-box">
  <div class="form-group">
    <h3 class=" white-outline form-heading">
      How it works
    </h3>
    <p class="white-outline form-text">
      Upload a photo of to find Taylor Swift or your best party outfit to find out how swiftie you are.
    </p>
    <label for="exampleInputEmail1" class="white-outline form-heading">Email</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
    <p id="emailHelp" class="white-outline form-text">We'll never share your email with anyone else.</p>
  </div>
  <div class="input-group mb-3">
    <div class="custom-file">
      <input type="file" class="custom-file-input" id="inputGroupFile02">
      <label class="custom-file-label" for="inputGroupFile02" aria-describedby="inputGroupFileAddon02">Choose file</label>
    </div>
    <div class="input-group-append">
      <span class="input-group-text" id="inputGroupFileAddon02">Upload</span>
    </div>
  </div>
  <div class="form-check">
    <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1" value="option1" checked>
    <label class="form-check-label white-outline form-text" for="exampleRadios1">
      Find Taylor Swift
    </label>
  </div>
  <div class="form-check padding-bottom">
    <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios2" value="option2">
    <label class="form-check-label white-outline form-text" for="exampleRadios2">
      Find Out How Swiftie You Are
    </label>
  </div>
  <button type="submit" class="btn btn-outline-light white-outline form-heading">Submit</button>
</form>

The CSS

@font-face {
  font-family:"Free Sans";
  src:url("/assets/fonts/FreeSans.eot?") format("eot"),url("/assets/fonts/FreeSans.woff") format("woff"),url("/assets/fonts/FreeSans.ttf") format("truetype"),url("/assets/fonts/FreeSans.svg#FreeSans") format("svg");
  font-weight:normal;font-style:normal;
}

@font-face {
  font-family:"Free Sans Bold";
  src:url('/assets/fonts/FreeSansBold.eot?') format("eot"), url('/assets/fonts/FreeSansBold.woff') format('woff'),url('/assets/fonts/FreeSansBold.ttf') format('truetype'),url('/assets/fonts/FreeSansBold.svg#FreeSansBold') format('svg');
  font-weight:normal;font-style:normal;
}

img {
  width: 100%;
}

body {
  height: 100%;
  background-color: #ffaaed;
  margin: 0;
}

.image-left {
  width: 50%;
  height: 100vh;
  float: left;
  overflow: hidden;
}

.detail-right {
  margin-left: 15%;
  height: 100vh;
  padding-top: 20px;
}

.left-image {
  width: 100%;
}

h2 {
  font-family: 'Free Sans Bold';
  color: white;
  text-align: center;
  font-size: 4vw;
}

h3 {
  font-family: 'Free Sans';
  color: white;
  text-align: center;
  font-size: 1em;
}

.no-padding-margin {
  margin: 0;
  padding: 0;
}

.mobile-image {
  max-height: 30vh;
  overflow: hidden;
}

.form-heading {
  font-family: 'Free Sans Bold';
}

.form-text {
  font-family: 'Free Sans';
}

.white-outline {
  color: white;
}

.outline-box {
border: 0px;
border-style: solid;
border-color: white;
padding: 10px;
}

.padding-bottom {
  padding-bottom: 10px;
}

.btn-outline-light:hover {
  color: #ffaaed;
}

Tablet rendering

enter image description here

enter image description here