samedi 29 août 2020

How to maintain unknown/wildcard queryParams through a transition?

I have a route (route-a) that transitions to another route (route-b) and I am trying to find a way for the destination URL to maintain the all query parameters, even if route-b does not know about them in advance.

For example, if a user visits https://example.com/route-a/?var1=x&var2=y, and the transition to route-b happens like this:

afterModel(model, transition) {
  this.transitionTo('route-b', model, {queryParams: transition.to.queryParams}) // transition route-a to route-b
}

...the ultimate URL will be https://example.com/route-b/without the query params.

Now, I realize the "Ember way" is to define the queryParams on route-b's controller in advance, but in this particular use-case, I do not know the queryParams in advance. Route B consumes any and all query params provided to it, which means they would be impossible to enumerate in advance.

How can I transition to a new route without dropping query parameters that are not specifically enumerated on the destination route's controller?

Is there a way to handle unknown queryParams, or is there the notion of a wildcard for queryParams (similar to *path routes)?




vendredi 28 août 2020

How do I refresh data and/or redraw chart in highcharts?

I'm implementing a highchart in an ember component in the following way

/controllers/mycontroller.js

  export default Controller.extend({
  chartData:
    [{
      name: 'Impact',
      borderWidth: 2,
      borderColor: '#FFFFFF',
      data: [],
      keys: ['x', 'y', 'v','f', 'i', 'm', 'c', 'g', 'p'],
      dataLabels: {
        enabled: true,
        color: '#000000',
        style:{
          fontSize: 14,
          fontFamily: 'arial',
          textOutline: false
        },
        formatter: function(){
          return this.point.options.feature;
        }
      }
    }],
  chartOptions: computed(function() {
    return {
      chart: {
        renderTo: 'container',
        type: 'mymap',
        events: {
          load: requestData,        -----> function that makes an api call and formats data
          redraw: true
        }

I've enabled the redraw option, but it does not redraw because the load data happens only when the component first loads (land on URL), I think?

So my question is how do I load/redraw data automatically every 60 seconds when the data is being fetched through a function call?




Installing Ember.js on MacOS

I have tried to install Ember.js through npm, but it throws an error.

npm install -g ember-cli

Is there a way to do it without Homebrew ?




jeudi 27 août 2020

emberjs + gojs integration

Hey guys I am trying out emberjs and want to integrate goJS to it. I did an npm install of the package https://www.npmjs.com/package/gojs But I can't find any good documentation on this.. so if anyone can point out my error that will be great

import Component from "@glimmer/component";
import go from "gojs";
import { action } from "@ember/object";
import { tracked } from "@glimmer/tracking";

export default class GraphComponent extends Component {
  @tracked iconName = "check-circle";

  $ = go.GraphObject.make;
  myDiagram = $(go.Diagram, "myDiagramDiv");



  @action
  changeIcon() {
    if (this.iconName == "check-circle") {
      this.iconName = "sync-alt";
    } else {
      this.iconName = "check-circle";
    }
  }
}

This is my ember component graph.js and In graph.hbs I have the corresponding div but some how nothing shows up on the screen. am I missing something ?

And would also appreciate any links to a goJS with emberJS docs.TY




Multiple youtube videos causes w.getDuration and postMessage errors

We are building an Ember webapp where users can add multiple Youtube videos to a page. The videos are Ember components 'wrapping' a Youtube iframe embed.

In order to comply with Youtube terms of service, we are trying to pause all other videos on a page whenever one starts playing, so that only one video can ever play at a time.
To do this, we have started using the YouTube Player API on the iframe embeds we were already using, following the documentation here: https://developers.google.com/youtube/iframe_api_reference

Having implemented that, we now listen for the onStateChange event in order to determine whenever a video starts playing and then use the postMessage method on all other YouTube iframes, in order to pause them. This works, except that since loading the Player API, we have been getting the following errors at seemingly random intervals:

Uncaught TypeError: w.getDuration is not a function
    at z (gtm.js?id=GTM-P9HMXHK:formatted:7573)
    at Object.onStateChange (gtm.js?id=GTM-P9HMXHK:formatted:7667)
    at gtm.js?id=GTM-P9HMXHK:formatted:7534
    at O.q.P (www-widgetapi.js:296)
    at Z.q.I (www-widgetapi.js:569)
    at Z.q.aa (www-widgetapi.js:593)
    at Qe.i (www-widgetapi.js:368)
    at Ce.g (www-widgetapi.js:352)

and

www-widgetapi.js:577 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin

When they do occur (which is not always), these errors break the functionality we built for pausing other videos.
The Ember components are instantiated independently of each other and each one checks for the existence of the YT script, loads it if necessary and makes a call to onYouTubeIframeAPIReady if it was called before, in order to create the player object for its own iframe. They are loosely based on this: https://github.com/oskarrough/ember-youtube/blob/master/addon/components/ember-youtube.js

Has anyone encountered these errors before in this context and is there a fix for them?




mardi 25 août 2020

Ember app has been blocked by CORS policy

I was trying to use my api and I have a function on ember app to login but when the login action is trigerred I receive a message below. What is the reason I am receiving this error?

login:1 Access to fetch at 'https://app-dev.some-url.com.au/api/login' from origin
'http://localhost:4099' has been blocked by CORS policy: Response to preflight request doesn't
pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch 
the resource with CORS disabled.



lundi 24 août 2020

EmberJS from less to sass with bootstrap convert

I am doing step by step according to

https://bushbaby.nl/emberjs-sass-bootstrap/

but i am ending up with error

martinko5mb@debian:~/Projects/XXX$ ember install ember-bootstrap
WARNING: Node v12.18.3 is not tested against Ember CLI on your platform. We recommend that you use the most-recent "Active LTS" version of Node.js. See https://git.io/v7S5n for details.
WARNING: Ember CLI is using the global npm, but your npm version has not yet been verified to work with the current Ember CLI release.
npm: Installed ember-bootstrap
installing ember-bootstrap
Installing for Bootstrap 4 using preprocessor sass
  uninstall bower package bootstrap-sass
  install package bootstrap
WARNING: Ember CLI is using the global npm, but your npm version has not yet been verified to work with the current Ember CLI release.
npm: Installed bootstrap@^4.3.1
Added import statement to app/styles/app.scss
Added ember-bootstrap configuration to ember-cli-build.js
Installed addon package.
martinko5mb@debian:~/Projects/XXX$ ember s
WARNING: Node v12.18.3 is not tested against Ember CLI on your platform. We recommend that you use the most-recent "Active LTS" version of Node.js. See https://git.io/v7S5n for details.
Could not start watchman
Visit https://ember-cli.com/user-guide/#watchman for more info.
Template Compiler Error (broccoli-persistent-filter:TemplateCompiler) in ember-popper/templates/components/ember-popper-targeting-parent.hbs

Assertion Failed: '@id' is not a valid path. ('ember-popper/templates/components/ember-popper-targeting-parent.hbs' @ L10:C12) 


Stack Trace and Error Report: /tmp/error.dump.4d09eefb1bc452f18a3bd776af5c84b0.log

And the error.dump.4d09eefb1bc452f18a3bd776af5c84b0.log looks like:

=================================================================================
ENV Summary:

  TIME: Mon Aug 24 2020 14:36:17 GMT+0200 (Central European Summer Time)
  TITLE: ember
  ARGV:
  - /usr/bin/node
  - /usr/bin/ember
  - s
  EXEC_PATH: /usr/bin/node
  TMPDIR: /tmp
  SHELL: /bin/bash
  PATH:
  - /home/martinko5mb/.ebcli-virtual-env/executables
  - /home/martinko5mb/.pyenv/versions/3.7.2/bin
  - /home/martinko5mb/.rvm/gems/ruby-2.7.0/bin
  - /home/martinko5mb/.rvm/gems/ruby-2.7.0@global/bin
  - /home/martinko5mb/.rvm/rubies/ruby-2.7.0/bin
  - /usr/local/bin
  - /usr/bin
  - /bin
  - /usr/local/games
  - /usr/games
  - /home/martinko5mb/.rvm/bin
  - /home/martinko5mb/.rvm/bin
  - /home/martinko5mb/.rvm/bin
  PLATFORM: linux x64
  FREEMEM: 170614784
  TOTALMEM: 16747925504
  UPTIME: 24726
  LOADAVG: 1.99853515625,1.36474609375,1.068359375
  CPUS:
  - AMD Ryzen 5 2600 Six-Core Processor - 1686
  - AMD Ryzen 5 2600 Six-Core Processor - 2341
  - AMD Ryzen 5 2600 Six-Core Processor - 3788
  - AMD Ryzen 5 2600 Six-Core Processor - 3432
  - AMD Ryzen 5 2600 Six-Core Processor - 3782
  - AMD Ryzen 5 2600 Six-Core Processor - 3045
  - AMD Ryzen 5 2600 Six-Core Processor - 1839
  - AMD Ryzen 5 2600 Six-Core Processor - 2269
  - AMD Ryzen 5 2600 Six-Core Processor - 3784
  - AMD Ryzen 5 2600 Six-Core Processor - 3124
  - AMD Ryzen 5 2600 Six-Core Processor - 3782
  - AMD Ryzen 5 2600 Six-Core Processor - 3777
  ENDIANNESS: LE
  VERSIONS:
  - ares: 1.16.0
  - brotli: 1.0.7
  - cldr: 37.0
  - http_parser: 2.9.3
  - icu: 67.1
  - llhttp: 2.0.4
  - modules: 72
  - napi: 6
  - nghttp2: 1.41.0
  - node: 12.18.3
  - openssl: 1.1.1g
  - tz: 2019c
  - unicode: 13.0
  - uv: 1.38.0
  - v8: 7.8.279.23-node.39
  - zlib: 1.2.11

ERROR Summary:

  - broccoliBuilderErrorStack: Error: Assertion Failed: '@id' is not a valid path. ('ember-popper/templates/components/ember-popper-targeting-parent.hbs' @ L10:C12) 
    at new EmberError (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:6939:25)
    at /home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:7187:13
    at PathExpression (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:15381:54)
    at visitNode (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3197:39)
    at visitKey (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3237:23)
    at visitNode (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3212:17)
    at visitKey (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3237:23)
    at visitNode (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3212:17)
    at visitArray (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3254:22)
    at visitKey (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3235:13)
  - code: [undefined]
  - codeFrame: Assertion Failed: '@id' is not a valid path. ('ember-popper/templates/components/ember-popper-targeting-parent.hbs' @ L10:C12) 
  - errorMessage: Build Canceled: Broccoli Builder ran into an error with `broccoli-persistent-filter:TemplateCompiler` plugin. 💥
Assertion Failed: '@id' is not a valid path. ('ember-popper/templates/components/ember-popper-targeting-parent.hbs' @ L10:C12) 
  - errorType: Template Compiler Error
  - location:
    - column: [undefined]
    - file: ember-popper/templates/components/ember-popper-targeting-parent.hbs
    - line: [undefined]
    - treeDir: /home/martinko5mb/Projects/XXX/tmp/broccoli_persistent_filtertemplate_compiler-input_base_path-XzGXowua.tmp
  - message: Build Canceled: Broccoli Builder ran into an error with `broccoli-persistent-filter:TemplateCompiler` plugin. 💥
Assertion Failed: '@id' is not a valid path. ('ember-popper/templates/components/ember-popper-targeting-parent.hbs' @ L10:C12) 
  - name: Error
  - nodeAnnotation: broccoli-persistent-filter:TemplateCompiler
  - nodeName: broccoli-persistent-filter:TemplateCompiler
  - originalErrorMessage: Assertion Failed: '@id' is not a valid path. ('ember-popper/templates/components/ember-popper-targeting-parent.hbs' @ L10:C12) 
  - stack: Error: Assertion Failed: '@id' is not a valid path. ('ember-popper/templates/components/ember-popper-targeting-parent.hbs' @ L10:C12) 
    at new EmberError (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:6939:25)
    at /home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:7187:13
    at PathExpression (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:15381:54)
    at visitNode (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3197:39)
    at visitKey (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3237:23)
    at visitNode (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3212:17)
    at visitKey (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3237:23)
    at visitNode (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3212:17)
    at visitArray (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3254:22)
    at visitKey (/home/martinko5mb/Projects/XXX/node_modules/ember-source/dist/ember-template-compiler.js:3235:13)

=================================================================================

I am fairly new to the EmberJS, and trying to update the thing in existing project (currently at ember-cli 2.18 succesfuly) I use bootstrap on rails projects, which converted to sass in the past few years. That is why i am doing this.

Anyway, what am i missing ?




samedi 22 août 2020

How to pass dynamic routes params in ember link-to

I have two routes in my router.js

'user/:id' -> will move to user show page 
'user-answer/:id/answers' -> will move to user answer page 

currently i am using a if condition to change the link as shown in below code ,

sidePanel.hbs



    
      
    
  
    
      
    


I use the sidePanel component in other two components as



it is working fine , but is there a way to use link-to one time , instead of a conditional check , like passing dynamic route parameters ?

something like

 
        
          
        
    



vendredi 21 août 2020

Ember.JS force computed property to recalculate

So I have a computed property in my Ember application. Declared as myComProp: computed('itemTrait', function () {...}). myComProp belongs to an item model. In a separate component (listItem) I have a property that is an alias of myComProp: myAlias: alias('itemModel.myComProp'). Now listItems are a member of an array of listItems, with its properties being rendered in the web app.

Now by the property being an alias, is there a way to force the computed property to recompute?

I have tried making the alias a tracked property but doing so returns the call stack as a string, not the actual result of the computed function.




mercredi 19 août 2020

Ember - Polymorphic relationship - POST request not triggered

I'm facing an issue right now. Here's the scenario.

owner belongsTo pet

pet belongsTo owner

pet relationship can have 2 different types which are the dog and cat

The problem I'm facing right now is, the POST request doesn't triggered

const owner = this.get('owner');
const petDog = this.get('dog');

owner.set('pet', petDog);
owner.save(); // The POST request doesn't trigger



Using puppeteers to get iframe when given the iframe id

So, I've got a bit of code in the Chrome Dev Tools like this:

<div class="ember-view" id="ember123">
    <iframe src="http://yaddayaddayadda" id="sso-frame" class="sso-iframe">
    .
    .
    other elements I will loop around and get
    .
    .
    </iframe>
</div>

I'm trying to get the iframe using Puppeteerjs. I can't use id="ember123" since ember id's dynamic. Is there some way to get the element handle via the id?




Ember Data peek 'x' amount of records from store

So I'm working with Ember Data and have a component where I want to render so many records from the store, let's say 10. I also have a live feed of these records that I want to make sure show up in this component, but I still want no more than 10. Now if I had a static array of objects I'd just say 'hey, remove the last as the new data comes in', however I need this component reflecting a live recordset so that my live feed can pour into it.

For now I query the store to get the base set of records loaded from the backend

this.store.query('recordName', {
    numberOfRecords: 10
});

Then the list of records that I render is assigned recordList = this.store.peekAll('recordName'); Now this will update whenever new records are created (they are created client-side). My downsides are that new records are automatically appended to the bottom of the list rather than the top (which is a separate bug) and I can just keep loading infinite records into this list.

Is there an elegant way with Ember Store to limit the live record set returned or is it going to have to result in some operating on the list with custom javascript?




Ember build error . How do I run it on gitlab runner?

While running ./node_modules/ember-cli/bin/ember build --environment=production on my local machine it works fine . But on gitlab runner it is giving me this error :

Cannot read property 'length' of undefined
ENV Summary:
  TIME: Tue Aug 18 2020 08:01:19 GMT+0000 (Coordinated Universal Time)
  TITLE: ember
  ARGV:
  - /usr/local/bin/node
  - build
  - --environment=production
  EXEC_PATH: /usr/local/bin/node
  TMPDIR: /tmp
  SHELL: /bin/bash
  PATH:
  - /usr/local/sbin
  - /usr/local/bin
  - /usr/sbin
  - /usr/bin
  - /sbin
  - /bin
  PLATFORM: linux x64
  FREEMEM: 1133453312
  TOTALMEM: 7833886720
  UPTIME: 339452
  LOADAVG: 1.95654296875,1.080078125,2.80615234375
  CPUS:
  - Intel(R) Xeon(R) CPU E5-2666 v3 @ 2.90GHz - 2900
  - Intel(R) Xeon(R) CPU E5-2666 v3 @ 2.90GHz - 2900
  - Intel(R) Xeon(R) CPU E5-2666 v3 @ 2.90GHz - 2900
  - Intel(R) Xeon(R) CPU E5-2666 v3 @ 2.90GHz - 2900
  ENDIANNESS: LE
  VERSIONS:
  - ares: 1.15.0
  - brotli: 1.0.7
  - cldr: 35.1
  - http_parser: 2.9.3
  - icu: 64.2
  - modules: 64
  - napi: 6
  - nghttp2: 1.41.0
  - node: 10.22.0
  - openssl: 1.1.1g
  - tz: 2019c
  - unicode: 12.1
  - uv: 1.34.2
  - v8: 6.8.275.32-node.58
  - zlib: 1.2.11
ERROR Summary:
  - broccoliBuilderErrorStack: TypeError: Cannot read property 'length' of undefined
    at isMultipartPath (/builds/mosaic-apps/omnivise/aurora/pa-aurora-
  - code: [undefined]
  - codeFrame: Cannot read property 'length' of undefined
  - errorMessage: Build Canceled: Broccoli Builder ran into an error with `broccoli-persistent-filter:TemplateCompiler` plugin. 💥
Cannot read property 'length' of undefined
  - errorType: Template Compiler Error
  - location:
    - column: [undefined]
    - file: siemens-addon-help-desk/templates/components/issue-create.hbs
    - line: [undefined]
  - message: Build Canceled: Broccoli Builder ran into an error with `broccoli-persistent-filter:TemplateCompiler` plugin. 💥
Cannot read property 'length' of undefined
  - name: Error
  - nodeAnnotation: broccoli-persistent-filter:TemplateCompiler
  - nodeName: broccoli-persistent-filter:TemplateCompiler
  - originalErrorMessage: Cannot read property 'length' of undefined
  - stack: TypeError: Cannot read property 'length' of undefined
=================================================================================
ERROR: Job failed: exit code 1 

My ember version :

"ember-cli": "^2.16.2"

"ember-cli-uglify": "^2.0.0-beta.1"

"broccoli-asset-rev": "2.6.0"

Tried to change the version of ember-cli , doesn't seem to be working . Also , cannot find the solution anywhere online . What could be the problem here?




lundi 17 août 2020

Lazy import of external js file in ember.js

I am trying to import external js file in one of my application routes.

@(task(function* () {
  yield import('jquery/dist/jquery').then(module => module.default);
  yield import('jquery-ui/ui/widget.js').then(module => module.default);
  yield import('jquery-ui/ui/widgets/mouse.js').then(module => module.default);
  yield import('jquery-ui/ui/data.js').then(module => module.default);
  yield import('jquery-ui/ui/ie.js').then(module => module.default);
  yield import('jquery-ui/ui/scroll-parent.js').then(module => module.default);
  yield import('jquery-ui/ui/version.js').then(module => module.default);
  yield import('jquery-ui/ui/widgets/sortable.js').then(module => module.default);
  yield import('jquery-ui/ui/position.js').then(module => module.default);    
  yield import('pivottable/dist/pivot.js').then(module => module.default);
})) pivotTableRunner;

afterModel(){
  this.get('pivotTableRunner').perform();
}

Currently I’ve been importing that library in my pivotTableRunner, but it turned out, that I have had to make some modifications of that library imported from node_modules. I copied it’s content to another file, and placed it in vendor folder. Is there any way to import it lazily after pivotTableRunner task?




Error: Compile Error: bootstrap-datepicker is not a helper

I am using

https://www.npmjs.com/package/ember-cli-bootstrap-datepicker

package.json in devDependencies:

"ember-cli-bootstrap-datepicker": "0.6.1",

in hbs:


error after ember test:

actual: >
        null
    stack: >
        Error: Compile Error: bootstrap-datepicker is not a helper
            at http://localhost:7357/assets/vendor.js:21757:19
            at Compilers.compile (http://localhost:7357/assets/vendor.js:21369:13)
            at expr (http://localhost:7357/assets/vendor.js:21720:25)
            at http://localhost:7357/assets/vendor.js:21458:17
            at Compilers.compile (http://localhost:7357/assets/vendor.js:21369:13)
            at compileStatement (http://localhost:7357/assets/vendor.js:22127:20)
            at compileStatements (http://localhost:7357/assets/vendor.js:22132:13)
            at CompilableTemplate.compileStatic (http://localhost:7357/assets/vendor.js:22157:31)
            at http://localhost:7357/assets/vendor.js:18256:30
            at AppendOpcodes.evaluate (http://localhost:7357/assets/vendor.js:17481:13)
    message: >
        Died on test #1     at Module.callback (http://localhost:7357/assets/tests.js:1333:24)
            at Module.exports (http://localhost:7357/assets/vendor.js:119:32)
            at requireModule (http://localhost:7357/assets/vendor.js:34:18)
            at TestLoader.<anonymous> (http://localhost:7357/assets/test-support.js:10892:11)
            at TestLoader.require (http://localhost:7357/assets/test-support.js:10882:27)
            at TestLoader.loadModules (http://localhost:7357/assets/test-support.js:10874:16)
            at loadTests (http://localhost:7357/assets/test-support.js:12321:22): Compile Error: bootstrap-datepicker is not a helper
    negative: >
        false
    browser log: |
...

funny fact, if i remove format="dd.mm.yy" from , then it won't throw error. What am i supposed to add or what am i missing to test to work ? package's doc doesn't say anything

edit: i have seen this, ember Error: Compile Error: is not a helper, it seems i have everything right




Can we force the controller value change to immediately reflect into the html drop down element manually without reloading the page in ember JS?

I have a situation in which I have to get the hours and minutes as input.I have used two select box element for getting hours and minutes.The Condition is that i will have a minute minutes below which the value should not exceed.For this I have used the inbuilt view in ember.I have two controller variable in my program one is bound to produce option field in the hours element, another one is for minutes.There is an observer function listening to the changes in the hours value and sets the options in the minutes element accordingly so that the resulting minutes is larger than the minimum minutes given. sample Hours option-["0","1","2",......."23"] sample minutes option-["0","5","10","15",......,"55"] For example if the minimum minutes is 30 minutes, 01.If the value in the hour element is 0 , then the minutes option should not show 0,5,10,....,25 as the result in a value smaller than 30 mins. 02.If the value in the hour element is greater than 0 , then the criteria greater than 30 mins is achieved so minutes options can be anything that is it should show every option from 0 to 55

Controller observer function to set minutes options:

AllMinuteOption=[["0","1","2",......."23"],
updateMinuteOption: Ember.observer("HourValueSelected", function() {
    var MinimumMinutes = this.get("MinimumMinutes");//minimum minute criteria
    var currentHourValueSelected= this.get("currentHourValueSelected");//The current value in selected in hour select element
    if ((currentHourValueSelected* 60) > MinimumMinutes) {
        console.log("opt" + this.get("minutesoption"));
        this.set("MinuteOption", this.get("AllMinuteOption"));
        return;
    }
    var MinimumHrs = Math.floor(MinimumMinutes / 60);
    var residualMinutes = MinimumMinutes - (crntEventFetchHour * 60);
    var sliceIndex = Math.floor(residualMinutes / 5);
    if (residualMinutes % 5 != 0) {
        sliceIndex++;
    }

    var temp = this.get("AllMinuteOption").slice(sliceIndex);
    this.set("MinuteOption", temp);
}),

This method set the minute option corresponding to the hour value selected but the change is not getting updated to the nearby minute option dynamically but eventually after selecting some other option in the minute option the values in the minute element the options is getting changed. Can someone tell me how to force the controller variable change manually to get reflected in the template?? Thanks in advance




dimanche 16 août 2020

EmberJs EmberUploader uploading multiple files problem

I have an ember component uploading multiple File, this is my component:

export default EmberUploader.FileField.extend({
  multiple: true,
  method: 'POST',
  success: Ember.K,
  failure: Ember.K,
  updateLabel: Ember.K,
  start: false,
  
  change(event) {
    this.set('_files',event.target.files);
  }
  
    startUpload: Ember.observer('_files.[]', 'start', function() {
    if (!Ember.isEmpty(this.get('_files')) && this.get('start')) {
      const uploader = EmberUploader.Uploader.create({
        url: this.get('url'),
        method: this.get('method')
      });

      let args = this.get('files');

      let data = this.get('data');
      if (data) {
        args.push({data: data});
      }

      uploader.upload(this.get('_files')).then(data => {
        this.$().val('');
        this.get('success')(data);
      }, error => {
        this.$().val('');
        this.get('failure')(error);
      });
    }
  })
});

I am getting an empty file at the backend. I am cheking that '_files' is not empty. Actually console.log('this.get('files')) show a FileList. Could someone help me with this ?




vendredi 14 août 2020

Sort JavaScript Object by key and value

I need to sort JavaScript Object in Ember.js by key and value.

input:

{
  'Super': 'Man',
  'New': 'Test',
  'New': 'Apple'
}

output:

{
  'New': 'Apple',
  'New': 'Test',
  'Super': 'Man'
}

There is a function called sortBy in Ember.js which can be used to sort key, but I am not sure how to sort value when keeping sorting key alphabetically.




Spring boot backend receiving empty Files array from EmberJs component EmberUploader When upload multiple files

I have an ember component responsible of uploading multiple File, this is my component:

export default EmberUploader.FileField.extend({
  multiple: true,
  method: 'POST',
  success: Ember.K,
  failure: Ember.K,
  updateLabel: Ember.K,
  start: false,
  
  change(event) {
    this.set('_files',event.target.files);
  }
  
    startUpload: Ember.observer('_files.[]', 'start', function() {
    if (!Ember.isEmpty(this.get('_files')) && this.get('start')) {
      const uploader = EmberUploader.Uploader.create({
        url: this.get('url'),
        method: this.get('method')
      });

      let args = this.get('files');

      let data = this.get('data');
      if (data) {
        args.push({data: data});
      }

      uploader.upload(this.get('_files')).then(data => {
        this.$().val('');
        this.get('success')(data);
      }, error => {
        this.$().val('');
        this.get('failure')(error);
      });
    }
  })
});

This is my spring boot controller :

public List<FileData> upload(@RequestPart("data") MemberData memberData, @RequestParam("files") MultipartFile[] uploadedFiles) throws SizeLimitExceededException {
    ...
}

My problem is that I am getting an empty array of uploadedFiles. This works fine with on file, when using MultipartFile instead of MultipartFile[] and putting this.get('files')[0] withing args.

Why this is not working for multiple files? Could someone help with this ?




How to configure RubyMine, so I can go to the component declaration?

While working with emberjs there are two ways to invoke a component in a template: classic invocation syntax


and the angle bracket invocation syntax

<MyConmonent />

You can go to the component declaration by simply pressing command + left click. But this doesn't work for the angle bracket syntax

Is there a way to configure the RubyMine or install some plugin to get it working?

BTW, using the EmberJs plugin written by Tobias Bieniek doesn't resolve this issue




mercredi 12 août 2020

When do multi-level nested components have a negative impact on performance?

I am trying to figure out a good standard for creating components. I am working with Emberjs but ideally this could work for any similar JS framework.

I like the idea of a clean template with lots of components rather than blocks of HTML. I'm sure there is an impact on performance but at what number does this become an issue. I've read that modern browsers are able to handle this well but I'd love to hear more on this.

If there is a coding standard I can read regarding components that will help too.




Ember.js - Error when running ember --version command

I am trying to run an ember.js app on my laptop but after installing the ember-cli and trying to run ember --version command I get an error.

To install ember-cli I used the following command - npm install -g ember-cli

Node.js version - 8.11.3

This is the error that I get:

ember --version

/Users/user/go/src/github.com/apps/app/node_modules/ember-cli/node_modules/fs-extra/lib/mkdirs/make-dir.js:85
      } catch {
              ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/user/go/src/github.com/apps/app/node_modules/ember-cli/node_modules/fs-extra/lib/mkdirs/index.js:3:44)



mardi 11 août 2020

Transition Aborted for Failed FindRecord

So in my route I have the following code and it works just fine when running the app. But when I run my tests, the test fails with transition aborted instead of doing what it does when I run the app.

Model(params) {
  Return this.store.findRecord(service, 999);  
}

What am I missing here? I would of thought it would hit afterModel and just do what I expect.




Ember Data creates duplicate record on model save() | ember-cli v3.19

Ember duplicates models on save. I have two models

**bill**

export default class BillModel extends Model {
    @attr("string", { defaultValue: "", uppercase: true })
    vehicleNumber;

    @attr("string", { defaultValue: "" })
    customerName;

    @attr("number", { defaultValue: "" })
    customerMobileNumber;

    @attr("date")
    createdOn;

    @hasMany("bill-item")
    billItems;

    @attr("number", { defaultValue: 0 })
    total;

    @computed(
        "billItems.@each.cost"
    )
    get computedTotal() {
        let total = 0;
        this.billItems.forEach((item) => {
            if (item.cost)
                total += parseFloat(item.cost);
        });
        return parseFloat(total);
    }
}


**bill-item**

export default class BillItemModel extends Model {
    @attr("string", { defaultValue: "" })
    itemName;

    @attr("number", { defaultValue: null })
    cost;
}

Then I create a new record of the "bill" model and create a "bill-item" record and add that in the billItems property of the bill model.

let bill = this.store.createRecord("bill");
bill.billItems.addObject(this.store.createRecord("bill-item"));

then when I use the save() the "bill" model, I now have two records in the billItems property. One with id returned from the server response and one with But I should have only one. Below is the server response.

{
  "vehicleNumber": "1231",
  "customerName": "123",
  "customerMobileNumber": 1231232312,
  "createdOn": null,
  "total": 23123,
  "billItems": [
    {
      "itemName": "1231",
      "cost": 23123,
      "id": "9510"
    }
  ],
  "id": 467
}

Why does the ember store now have 2 records of "bill-item" model when I tried to save only one? The adapter used for the models are RESTAdapter and serializer is JSONSerializer.

Ember inspector attachment for reference




how to know if an embedded ember application is ready

i have a simple static html page with an ember application implemented via a <script> tag. On this page I also have a loading animation in a div with the class loader that I want to hide once the ember application is started or ready.

Since I don't know Ember.js, and the code of the application is minimized, I hope that someone can tell me an default event from Ember.js or something like that I can wait for and then use JS to hide the animation.




lundi 10 août 2020

Conversion to Glimmer components – dynamic property in service

I am trying to build a Glimmer component that reacts to changes to properties in a service, see below where I am trying to make the component to update the get playing in response to changes in the audioPlayer url and status – which are changed when the play button is pressed in the play action below.... This is not working, and I haven’t been able to find any documentation to support this type of behaviour.

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

export default class ShowAudioEpisodeComponent extends Component {
  
  @service audioPlayer;
  
  get playing() {
    return this.audioPlayer.url == this.args.epi.audioUrl && this.audioPlayer.status == "playing";
  }

  @action
  play() {
    if (this.playing) {
      this.audioPlayer.pause(this.args.epi);
    } else {
      this.audioPlayer.playEpisode(this.args.epi);
    }
  }

}



Is there a difference between `ember serve` and `npm start`?

What is the difference between the commands ember serve and npm start?




samedi 8 août 2020

Uncaught Error: Could not find module `ember-resolver` imported from `appName/resolver'

I am using

ember-cli: 3.4.3 ,
node js:10.16.3,
ember-resolver: 5.2.1

ember-serve work perfectly and give

Build successful (25929ms) – Serving on http://localhost:4232/

but on browser console the following error comes and unable to process further

Uncaught Error: Could not find module `ember-resolver` imported from `appName/resolver'

I tried deleting package-lock.json ,node-modules, clearing cache & reinstalling still the same

Can any one help on this please




Uncaught Error: Could not find module ember-meta/lib/meta at missingModule (vendor.js:18453)

I am using ember-cli: 3.4.3 , node js:10.16.3.

ember-serve work perfectly and give Build successful (25929ms) – Serving on http://localhost:4232/

but on browser console the following error comes and unable to process further Uncaught Error: Could not find module ember-meta/lib/meta at missingModule (vendor.js:18453)

I tried deleting package-lock.json ,node-modules, clearing cache & reinstalling still the same

Can any one help on this please




vendredi 7 août 2020

How can I write tests for non-web code in EmberJS app?

I have ember addon, which introduces new commands.

Ember commands are not web javascript, it's Node.

I want to write tests for this logic (at least, unit), but can't find how to do it from the docs. All testing documentation seem to be related to testing web logic




component unit testing in Glimmer

For classic component unit tests, how would we migrate this to Glimmer? This component unit test is testing a local prop that is not exposed to the user.

const component = this.owner
  .factoryFor('component:some-component')
  .create({
    someModel: { foo: 'bar' }
  });

assert.equal(component.get('someLocalProp'), false);



How to write modules in vendor ember folder?

I'm trying to write modules in vendor folder.

// vendor/my-tool/index.js
import { a } from './animations.js'
alert(1);
// vendor/my-tool/animations.js
export const a = 1;

Then import them like this:

app.import('vendor/my-tool/index.js');

But I get these errors:

Uncaught SyntaxError: import declarations may only appear at top level of a module Uncaught 
ReferenceError: define is not defined

I've all trying to fix them. Maybe, applying babel to vendor files could make it work, but I did not find the way. How can I do it?




Share service variable between controllers

I have a variable in a service that I want two share between two controllers. As I know, Ember services are singleton.

I created a service file: app/services/data-manipulation.js:

import Ember from "ember";

export default Ember.Service.extend({
  init() {
     console.log('initService');
  },
  shouldManipulate: false
});

In first controller that is called one screen before the second controller:

dataManipulation: Ember.inject.service(),
init() {
   this.updateManipulate();
},
updateManipulate: function() {
   this.set("dataManipulation.shouldManipulate", true);
   var currentValue = this.get("dataManipulation.shouldManipulate");
   console.log(currentValue); // log true as expected
}

In second controller:

dataManipulation: Ember.inject.service(),
init() {
  // it inits the service again so 'initService' is logged again.
  var currentValue = this.get("dataManipulation.shouldManipulate");
  console.log(currentValue); // log undefined
}

What is the problem and how can I make it works?




mercredi 5 août 2020

Question about the Ember tutorial, why the link http://localhost:4200/rentals/grand-old-mansion does not work

I am learning ember now. I follow the tutorial to build a web app.

In part 2 of the tutorial, the Route Params section the URL as follow:

https://guides.emberjs.com/release/tutorial/part-2/route-params/

I found something strange.

The test case for the below link does not pass.

http://localhost:4200/rentals/grand-old-mansion

I found that if I click the link from the root (i.e. /), it can shows the rental correctly.

And then, if I refresh the page, it does not work. The error message as below:

Uncaught (in promise) Error: No model was found for 'rental' and no schema handles the type

I checked all files that do not have typo error. What is the problem?




Ember component constructor args is Proxy {}

In a fresh Ember 3.20 project (also same in 3.19), after adding a new component.

application.hbs:

<Test @foo="hello" />

components/test.js:

import Component from '@glimmer/component';

export default class TestComponent extends Component {
    constructor(){
        super(...arguments)
        console.log(this.args)
    }
}

Console: Proxy {}

How can I access this.args within the constructor?




bootstrap4 on ember.js: how do I build this exact top navbar and left side navbar

what I would like to do in RED BOX

hello. obviously I am new and very much a beginner.

I am using ember.js for my application frontend and bootstrap to ease the styling process. I want to build a top fixed menu bar like the picture attached and a left navigation bar with scrolling like the picture attached. maybe because I am new thats why I am unable to use the manuals properly to land me at this point.

if anyone choose to help, need to know 1st that if there are already defined builtin components in ember.js to solve this issue (I am using ember v3.18), I am unable to find any.

2nd, if 1st question answer is no, then how can I build it - or are there any suggestive codes available online for me to learn from?




How to reset scroll on route changes in ember 3?

I'm trying to use hook activate, didTransition, or willTransition, but none of these work, they do nothing at all. I try to start by one route:

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

export default class SectionRoute extends Route { 
  ...

  activate() { scroll(0, 0); }
}

This works in my js browser console:

scroll(0, 0);



mardi 4 août 2020

How to use ember paper icons offline?

I am creating a web module with ember paper where i need to use this module offline as well, now when i use the offline mode the ember paper icons doesn't appear instead just the text appears, can anyone help me getting ember paper work offline.




Error: "No model was found for 'application' and no schema handles the type" when trying to test ember component

This is my component

<section>
    <h2></h2>
    <p></p>
    
</section>

This is my integration test.

import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';

module('Integration | Component | section', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    // Set any properties with this.set('myProperty', 'value');
    // Handle any actions with this.set('myAction', function(val) { ... });

    let section = {
      title: 'Fractions',
      slug: 'fractions',
      body: 'Learn new option of responsiveness. Instead of columns, we use fractions.'
    }

    this.set('model', section);

    await render(hbs`<Section @section= />`);

    assert.equal(this.element.querySelector('h2').textContent.trim(), section.title);
  });
});

I got this error when I execute the test: No model was found for 'application' and no schema handles the type" when trying to test ember component I did not found how to fix it until now.




When run tests on Heroku I get Could not download source code tarball error

when I want to run my tests Heroku throws an error and no shown output.

could not download source code tarball

I tried to run again but every time i try run again or run again without cache option, i got same error.

I searched this error but couldn't get any information.

how can i solve it?




Heroku - EmberJS - Deploy fail ( Unable download node )

when I try to push code on Heroku, the build/deploy fail because of node problem.

Console log

cd dungeon-diary
heroku buildpacks:set https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/emberjs.tgz   
git push heroku master

Output console with error

    remote: Building source:
    remote: 
    remote: -----> emberjs app detected
    remote: -----> Setting NPM_CONFIG_PRODUCTION to false to install ember-cli toolchain
    remote: -----> Fetching buildpack heroku/nodejs-v98
    remote: -----> Node.js detected
    remote: 
    remote: -----> Creating runtime environment
    remote:        
    remote:        NPM_CONFIG_LOGLEVEL=error
    remote:        NPM_CONFIG_PRODUCTION=false
    remote:        NODE_ENV=production
    remote:        NODE_MODULES_CACHE=true
    remote:        NODE_VERBOSE=false
    remote: 
    remote: -----> Installing binaries
    remote:        engines.node (package.json):  10.* || >= 12
    remote:        engines.npm (package.json):   6.x
    remote:        
    remote:        Resolving node version 10.* || >= 12 via semver.io...
    remote:        Downloading and installing node 14.7.0...
    remote:        Unable to download node 14.7.0; does it exist?** 
    remote: 
    remote: -----> Build failed

package.json

  "engines": {
    "node": "10.* || >= 12"
  },



lundi 3 août 2020

Ember.js: Unexpected token

I am learning ember.js and I am following this tutorial:

https://youtu.be/owDmPTSJkrg?t=1194

I am writing a controller for a form:

import Controller from '@ember/controller';

export default class TasksNewController extends Controller {
    actions:{
        addTask: function() {
            var title = $this.get('title');
            alert(title);
        }
    }
}

I get this error:

Build Error (broccoli-persistent-filter:Babel > [Babel: emtasks]) in emtasks/controllers/tasks/new.js

/Users/.../Desktop/emtasks/emtasks/controllers/tasks/new.js: Unexpected token (4:11)

  2 | 
  3 | export default class TasksNewController extends Controller {
> 4 |     actions:{
    |            ^
  5 |         addTask: function() {
  6 |             var title = $this.get('title');
  7 |             alert(title);

Thank you for any suggestions




Ember - Change current route from browser console

I am not at all Ember developer, but I would like to change current route from browser console. Is it possible at all to access correctly Ember, e.g. Ember.Router.prototype.transitionTo('/feed')?

Version of the website is 3.16.9




How to pass a @tracked object from an Ember route model hook

My question is two-fold:

  1. Where is the best place to put some kind of polling logic - in the route file right?

  2. How do I pass this constantly updating value from the Route to some child component? Labeling some variable as "@tracked" and then passing the tracked variable via the model hook?

Let's say I have something like this:

routes/index.js

export default class IndexRoute extends Route {
  @tracked
  recent: {
    A: 0,
    ...
  },

  constructor() {
    super(...arguments);
    this.getRecent();
  }

  getRecent() {
    // poll data / fetch latest
    const {A, ...partialObject} = this.recent;
    
    this.recent = { ...partialObject, A: <some new value fetched>};;
    
    later(this, this.getRecent, 2000);
  }

  model() {
    return this.recent;
  }
}

application.hbs

<p>constantly updating "this.recent":  </p>

I thought if I use the model hook like this, it would be tracked and therefore auto-update but that was not the case. I have this sample Ember Twiddle that emulates what I'm trying to do. I tried to force a re-compute by reassigning the entire variable but it didn't work.

This question is a deeper dive from my initial question here.