jeudi 31 janvier 2019

EmberJS Select onChange event not passing selected value

I'm trying to get the selected value from a select tag, I have tried these cases but I'm not able to get the selected value, Does anyone have an idea on what is wrong with the way I'm declaring the action on the select tag?

Case 1

In this case I got an error:

Uncaught TypeError: Cannot read property 'apply' of undefined

Template:

 
   <select class="form-control" onchange=>
     <option value="">Select an option</option>
     <option value="1000">$1000</option>
     <option value="100">$100</option>
     <option value="10">$10</option> 
   </select>


Route Actions:

actions: {

   ChangeCombo(paramOne, paramTwo, paramThree) {

     console.info(paramOne, paramTwo, paramThree);

   },

}

Case 2

In this case the first parameter is the current Item from de model array, the second one is the string "Price" but the third parameter is undefined and the last parameter which is supposed to be the event object is also undefined.

Console output:

{object}, "Price", undefined, undefined

Template:


   <select class="form-control" >
       <option value="">Select an option</option>
       <option value="1000">$1000</option>
       <option value="100">$100</option>
       <option value="10">$10</option> 
   </select>


Route Actions:

actions: {

   ChangeCombo(paramOne, paramTwo, paramThree, paramFour) {

     console.info(paramOne, paramTwo, paramThree, paramFour);

   },

}

Ember version

ember-cli: 3.7.1 node: 10.1.0 os: win32 x64




mercredi 30 janvier 2019

Building a mobile hybrid app with Ember.js

What are my options and most recent technologies to develop a mobile app, both to Android and iOS using Ember.js?

This doesn't pretend to be an opinion quality based questions, but a way to find the possible technologies.




Ember: how to bind HTML class to Service property, so that class is dynamic

I have a parent route. Inside this route there is a component that is rendered.

The route has a template.hbs file that contains a HTML div element. I need to be able to change the class of this div element from within my child component.

To do this, I was planning on using a service. The idea being inject the service into both the route and child component and then bind the class of the div to a property on the service. Then, when I inject the service into the child component I can change the property and see any changes reflected by the parent route.

Problem is, the binding doesn't seem to work!

Parent Route:

Template: <div class=>

Route.js:

dashboardContainerManager: service('dashboard-container-manager'),

afterModel(model) {
   model.set('containerClass', this.get('dashboardContainerManager').dashboardContainerClass);

SERVICE:

export default Service.extend({
  dashboardContainerClass: null,

  init() {
    debugger; //placed to ensure one instance being made
    this._super(...arguments);
    this.set('dashboardContainerClass', 'container dashboard-container'); //need to set it here to prevent glimmer error
  },

  changeContainerClass(newClass) {
    debugger;
    this.set('dashboardContainerClass', newClass);
  }
});

Child Component:

  dashboardContainerManager: service('dashboard-container-manager'),
  init() {
    this._super(...arguments);
    this.get('dashboardContainerManager').changeContainerClass('test');
  },

The result of the above code is that the class of my div is initially set to "container dashboard-container" because that's the value that the dashboardContainerClass property on my service is initialised to. However, when the value is changed to "test" inside my component, the class of my div isn't updated which suggests it's not bound properly to the value of dashboardContainerClass. I tried using a computed property in various places as well but couldn't get anything to work.

What am I doing wrong here?!




Read from file into config

I have an ember project. The root folder has a file called version which just says 1.1.0

In the root folder I also have my client folder (ember project) with a config folder and then environment.js for my app variables.

Im trying to read from the version file and add its contents in the environment.js file as a varaible.

Im currently trying like this: version: $.getJSON("../../VERSION")

but im getting the unexpected identifier error. With Node I would use: version: fs.readFileSync(__dirname + '/../VERSION').toString().trim(),

How would I do this with ember? thanks




mardi 29 janvier 2019

How to disable airbrake for specific user?

My ember application uses airbrake.io for reporting errors. Airbrake is added to the project using bower : https://github.com/balinterdi/ember-cli-airbrake

This will enable airbrake for all users for the application. Hence errors from all users will be sent to me via airbrake.

What I wanna do is disable/enable airbrake based on the user. Hence when the application loads, I want to be able to decide whether I should enable airbrake or not.

Ideas?




EmberJS: Nothing handled the action

Ember newbie. Using 2.3.0. To an existing application I need to add a button that toggles content on and off the screen. Following the existing code patterns, I added the following two files.

app/components/help.js

import Ember from 'ember';

export default Ember.Component.extend({
    actions: {
      toggleHelp() {
          this.toggleProperty('isShowingHelp');
      }
    }
});

templates/components/help.js

<div class="help">
    <a href="#" >help</a>
</div>

  <p>HELPHELPHELP</p>


And then in various *.hbs files I'm adding to get the button to show up where it is needed.

The button renders as expected as

<div class="help">
    <a href="#" data-ember-action="493">help</a>
</div>

But when I click, I get the error, "Nothing handled the action 'toggleHelp'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble."

I checked the Ember documentation and saw that this matches the instructions.

I think the issue might be because I am calling it as a partial, but none of the other options (view, render, outlet) seems to apply to my limited case.

As per this answer, I tried , but then the error when I click turned into, "ember.debug.js:29112 Uncaught TypeError: Cannot read property 'send' of undefined."

I'm at a total loss... Can anyone point out what I'm missing here? Thanks!




lundi 28 janvier 2019

How to write a CSS Conditional in ember for class attributes?

am stuck on a problem and haven't been able to find a resource that explains this. Sorry if this is obvious but I am an ember newbie.

I want to be able to write an if equals conditional for a table.

Example:

if (data === 'r') {
     change table row to red
else 
    change table row to blue
}

I've been trying by using the following code:

<table class="attr1  red  blue ">
</table>

Any help is appreciated.




ember unit testing models

I am trying to write unit tests for my ember application. Currently the test that model exist works but I want to test computed properties within model which are based on some other properties generated by mirage or returned from API calls. My concern is how shall I initialize or populate data for the model under unit testing?

Sample unit test code for my model: "user" is:

import { moduleForModel, test } from 'ember-qunit';

moduleForModel('user', 'Unit | Model | User', {
    needs: ['model:account']
});

Now I want to write a test where I can use:

let model = this.subject();

And then I shall be able to access the properties injected by mirage. But how can I do that here? I did not find anything on documentation. Please help




dimanche 27 janvier 2019

Component action not triggered in ember

I am facing an issue and not able to rectify what is the problem or bug.

I am having a route in ember and a component which I used in the route.

The problem is whenever I try to trigger some action in the component but the actions specified in the route is being called.

For example,

//main.hbs


//main.js
actions:{
   showRow:function(){
       console.log("Router showRow called");
   },
}
//SampleComponent.hbs
<script type="text/x-handlebars" id="components/sample-component">
   <!-- button 1 -->
   <button ></button>
   <!-- button 2 -->
   <button ></button>
</script>

//SampleComponent.hbs
actions:{
   showRow:function(){
       console.log("Component showRow called");
   },
   hideRow:function(){
       console.log("Component hideRow called");
   },
}

If I click button 1, I get error saying that the action was not handled. If I click button 2, 'Router showRow called' gets printed in the console.

The actual error is enter image description here Still now not able to spot the error, kindly help me to sort these out.

Thanks in advance :-)




How do I display data from Rails backend to Ember frontend without saving it in the database and without using Ember-Data?

The problem:

I have used rest-client to pull news articles from newsapi.org through my Rails backend. I can display that data on localhost:3000/articles. I do not (necessarily) want to save this data to a database and would like to simply display it on my Ember frontend after calling it on my Rails backend. I get this error:

Error while processing route: article Assertion Failed: You must include an 'id' for article in an object passed to 'push'  

I understand this to mean that my data has no 'id' - which it doesn't. I have no control over the data coming in.

{
  "status": "ok",
  "totalResults": 6868,
  "articles": [
{
  "source": {
    "id": "mashable",
    "name": "Mashable"
  },
  "author": "Lacey Smith",
  "title": "Cannabis may alter the genetic makeup of sperm",
  "description": "A new study suggests that marijuana use can not 
only lower sperm count, but also affect sperm DNA. Read more... More 
about Marijuana, Cannabis, Sperm, Science, and Health",
  "url": "https://mashable.com/video/cannabis-sperm-dna/",
  "content": null
},  

Ember-Data doesn't like this because it's not in JSONAPI format and I can't change it to JSONAPI. How do I display this data on my ember frontend without using Ember-Data and without having to save it into my database? The tutorials I've found all have examples using databases and Ember-Data.

What I've already tried:

I tried to save it to my database and load from there, but I'm thinking that might complicate the idea, since I would need to scrape the data and save it to my database and that has proven difficult to do. I'm not experienced with backend stuff and haven't found many answers. If you have an answer for doing it this way, feel free to answer here:

How to automatically save data from url to database

I'm willing to try it out. I thought originally this would be the best way to go. I could save the data and only add to the database when new articles were returned. I'm not having any luck this way, so I thought I'd approach it from another direction.

Thanks for any help!




Emberfire issue with firebase with underscore in node

I am trying to retrieve data from an existing firebase database using Emberfire in an ember.js app. I can authenticate firebase and sign in. The problem being when trying to access the node daily_mail the error I get from Emberfire is permission_denied at /dailyMail: Client doesn't have permission to access the desired data. It removes the underscore and camelcase's my node. Is there any workaround. The database has appropriate rules in place, so that is not the problem. It is only requiring the user to be authenticated at each node for now. dailyMail simply doesn't exist it's daily_mail.

Model

import Client from './client';

export default Client.extend({
  model: function() {
    return this.store.findAll('daily_mail');
  }
});




vendredi 25 janvier 2019

Promise Retry Wrapper for Ember

I have a snippet of Ember code that calls an API end point and populates an array when a response arrives (there are other items added to the array independently of the API call. I omitted irrelevant code for simplicity):

descriptor: Ember.computed("qParams", function(){
    let qParams = this.get("qParams");
    let data = new Ember.A();
    let callHomePromise = this.get("store").find('info-extractor', qParams).then(item => {
            data.pushObject(item);
            });
    return data;
    })

This code works fine and does what it is intended to do. I would like to create a retrier: in case this.get("store").find fails due to the underlying AJAX call responding with 401, for example, I would give it a couple more tries. Based on this answer https://stackoverflow.com/a/51332115/1518685 I devised the following wrapper:

export default function (promiseFactory) {

  let retryChain = Ember.RSVP.reject();
  for (var count = 0; count < 3; count++) {
  retryChain = retryChain.catch(reason => {
      return new Ember.RSVP.Promise((resolver, rejector) => {
        promiseFactory().catch(r => {
        setTimeout(rejector.bind(null, reason), 1000);
      }).then(ok => { resolver(ok); })
      });
    });
  }

  return retryChain;
}

Which I execute this following way:

import retrier from 'project/utils/retrier';

//....

descriptor: Ember.computed("qParams", function(){
    let qParams = this.get("qParams");
    let data = new Ember.A();
    let callHomePromise = retrier(() => { this.get("store").find('info-extractor', qParams)}).then(item => {
            data.pushObject(item);
            }).catch(reason => { /* do stuff with reason */});
    return data;
    })

I simulated bad requests (by setting faulty qParams variable) and observing multiple AJAX requests failing and eventually permanent failure gets captured within the catch() method after the retrier. However, when the call is successfully, the retrier promise never gets resolved and I can't figure our why?

Any help would be highly appreciated.




Custom styling not transferring over properly when deploying to Heroku

We have a rails app with an EmberJS frontend that we just deployed to Heroku, but our styling got messed up when it was deployed. The images, Bootstrap, and Ember-Paper show up properly, but the styling does not. We're using scss and we don't have anything in our ember css file. All of our custom styling shows up fine locally but not when deploying to Heroku. We tried looking into this and found someone who said that the static file was not being accessed on heroku. We're not totally sure what this means or how to go about fixing it. The file structure looks like this:

Our scss file imports bootstrap and ember-paper

This is our github repo: https://github.com/ciarrapeters/rate-my-coop-v2

This is our heroku app: https://ratemycoop.herokuapp.com/companies

The image should not be nearly as massive as it is on the site, and there is more custom styling

bundle/
.git/
app/
    assets/
        config/
        images/
        javascripts/
        stylesheets/
            application.css
        .DS_Store
    channels/
    controllers/
    helpers/
    jobs/
    mailers/
    models/
    serializers/
    views/
    .DS_Store
bin/
config/
db/
frontend/
    app/
        adapters/
        components/
        controllers/
        helpers/
        models/
        routes/
        styles/
            app.css
            app.scss
        templates/
        resolver.js
        app.js
        router.js
        index.html
    config/
    dist/
    node_modules/
    public/
        assets/
            images/
                .DS_Store
                kenneth.png
            .DS_Store
        robots.txt
        .DS_Store
    tests/
    tmp/
    vendor/
    .watchmanconfig
    .template-lintrc.js
    .eslintignore
    .ember-cli
    .travis.yml
    .gitignore
    .editorconfig
    testem.js
    .eslintrc.js
    ember-cli-build.js
    README.md
    package.json
    package-lock.json
lib/
log/
node_modules/
public/
test/
tmp/
vendor/
package-lock.json
config.ru
package.json
Rakefile
README.md
.gitignore
Gemfile
Gemfile.lock
.DS_Store




jeudi 24 janvier 2019

emberjs component communication

I have some trouble with component communication. Lets say I have 3 nested components. Parent -> which has child -> which has child . How can I access component-c directly from component-a, if component-c is not rendered. Is this even possible. Thank you




Dynamic primaryKey on ember serializer

I am trying to set primaryKey on ember seializer dynamically. Is it possible?

Here is what I can get from the server as response

account: {iban: "ibanValue", currency : "currencyValue"} or {bban: "bbanValue"}

import DS from 'ember-data';
import ApplicationSerializer from './application';

const {
  EmbeddedRecordsMixin,
} = DS;

export default ApplicationSerializer.extend(EmbeddedRecordsMixin, {
  primaryKey: 'iban'
});

I setted primaryKey to 'iban' but it can be 'bban'. How can I set one of them as primaryKey?




mercredi 23 janvier 2019

EmberJS - How to partially nest parent and sub routes?

I have a lot of nested urls.

e.g. Project list -> Project detail

The Project list template's route should only display the list if the route Project details is not called.

I did it by creating a computed property that check the currentRouteName of the server routing.

Then I add this to my template:

  <div>Element that should be display in both route.</div>

  
    
  
    <ul> ... </ul>
  

Note that some elements of Project list should be still display in Project detail.

Is there a better way to do this?




Have Error while try to Update Ember 2.14.2 to Ember 2.18.2

Anyone please help me with Ember update.My current code base was 2.14.2 and I try to update 2.18.2.And I got the below error.

Could not start watchman
Visit https://ember-cli.com/user-guide/#watchman for more info.
Cannot find module 
'/sampleApp/bower_components/ember/ember-template-compiler.js'

Anyone, please guide me with this. If you have another method to upgrade the version of ember please let me know or please help to solve the issue.

Thanks in advance.




mardi 22 janvier 2019

close all child window automatically when parent tab window is closed in JSP

In a window one one tab have an i frame element which should render document viewer componenet while clicking one popup button inside i frame element it open a seperate window like this. the jsp code is

<param name="bar2button1" value="openInFullScreen(), Popup out, ../../../eops/images/external.png, ../../../eops/images/external.png, true" />

and javascript code is

function openInFullScreen() {
    var popup = window.open(window.location.href, "_blank",  "popup", "fullscreen");        
    if (popup.outerWidth < screen.availWidth
            || popup.outerHeight < screen.availHeight) {
        popup.moveTo(0, 0);
        popup.resizeTo(screen.availWidth, screen.availHeight);
    }       
}

it worked fine but what i need is after opening multiple document from the viewer when i close the tab which contain the document viewer it should automatiacally close all the cooresponding child tabs.

the tab closing functionallity is done from ember side.

Any idea how to achieve this?




How to test if an ember component is missing a parameter?

We have a button component that looks like this in our handlebars file.



It's essentially like except it does a little bit more. We recently found a button on our site that was broken because it was missing the link parameter. I was wondering if there was a way to test or enforce that our link parameter is always filled out. I'm not sure off-hand how to test this though or if it is possible.




Ember - Compile Error: bs-form-element is not a helper

Recently i update my existing ember ember project to 2.10.0 version after update i try to run the project but it shows some compile error

uncaught Error: Compile Error: bs-form-element is not a helper

I include this in login page on my project like this

 <div class="panel-body">
                
                    <fieldset>
                         
                        
                        <!--div class="checkbox">
                            <label>
                                <input name="remember" type="checkbox" value="Remember Me">Remember Me
                            </label>
                        </div-->
                        
                    </fieldset>
                
            </div>

I am not sure whether this is plugin related issue or something could some one please help to sort this issue




dimanche 20 janvier 2019

Ember: error while i am running ember serve

I am try to upgrade exisiting ember project cli version by following this tutorial

https://emberigniter.com/update-latest-ember-data-cli/

after finishing this i try to run ember serve it shows error like

missing path

i doknow what exactly it was trying to say and also i am new to ember could any one help me sort out this issue.




samedi 19 janvier 2019

Bind html string in controller to template does not trigger click event

I have a html string in controller and I bind this to view, but the action does not trigger on clicking.

I already applied the triple braces or htmlSafe to avoid html escape, the button shows on the template but when clicking on it does not trigger action newAlert

## hello.js

import { htmlSafe } from '@ember/string';
import { computed } from '@ember/object';

export default Controller.extend({
  htmlString: computed(function() {
    return htmlSafe('<button >Test Alert</button>')
  }),
  actions: {
    newAlert: function(){
      alert('Hello')
    }
  }
});

## hello.hbs



Could you guys help me shows what is going wrong?




vendredi 18 janvier 2019

Does Emberjs has a lifecyle method that's before attributes get updated?

I want to have control over an Ember component before the attributes get updated. (Conditionally setting attributes' values with static values belonging to a specific component). Ideally, I want to have something like willUpdateAttrs. But I couldn't find anything similar in the documentation. Does anyone know if this is available in Ember? If not, what would you suggest me to do?

Note: I'm aware there's a willUpdate method, but it's called when the component is about to update but not when the attributes is about to update.

Any help would be much appreciated! Thanks!




jeudi 17 janvier 2019

Register custom event in ember-power-select( onmouseEnter, OnMouseLeave)

How may I register my custom event(onmouseEnter, OnMouseLeave) in Ember-power-select. By default it supports only: onblur, onchange, onclose, onfocus, oninput, onkeydown, onopen, scrollTo.




How to autoplay a video in ember.js in Chrome

I have a very very simple ember app.

In my application.hbs, I only have the following code (no other routes or templates)

<video autoplay loop muted playsinline>
  <source src="https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4">
</video>



The problem is that I cannot get this video to autoplay on Chrome. Initially, this seemed like a Chrome specific issue, but even after following this popular question, the top answer does not fix my problem.

Even more, if I create a simple html page, this video autoplays on Chrome and as well as any other browser. Thus, I can only recreate this problem from an ember application.

Also note that if I were to open the autoplay video from a seperate route (i.e. I change to a new page and come back), the autoplay now works. Thus this problem only occurs when the app first loads. I can't find any popular components that can substitute.

I'm curious how I can get this video to autoplay when opening Chrome for the first time.




How to properly set up Ember auto-imports using VSCode and the Javascript Language Service?

I'm trying to set up auto-imports in VSCode for my Ember project and I'm encountering issues with imports from the Ember library.

I have properly set up imports from within my application, those work just fine, but when trying to import from @ember, it either doesn't find the import at all, or it's imported from a ridiculous relative path, or it's imported just fine, in some cases.

My jsconfig.json looks like this:

{
    "compilerOptions": {
        "target": "es2018",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "baseUrl": ".",
        "paths": {
            "sbct-web/tests/*": ["./tests/*"],
            "sbct-web/config/*": ["./config/*"],
            "sbct-web/*": ["./app/*"]
        }
    },
    "exclude": [
        "node_modules",
        "bower_components",
        "tmp",
        "vendor",
        ".git",
        "dist",
        "temp",
        "public",
    ]
}

I also tried with a dumbed down version that only had the exclude field, but the results were the same. I also tried to force typeAcquisitions, same results (I suspect the types are fetched just fine, because I can peek definitions of @ember modules).

In order to better understand the issue, here's a short recording of what I'm encountering:

ember auto imports




Get Model from Router and then update it

So, at certain point in my application I have a route that retrieves a model, lets say user model, that looks like this:

routes/users.js
model(params) {
    return this.get('store').findRecord('user', params.id);
}

Then, at some point in the template i've got this:

templates/users.js

...
<button onclick=>Save Changes</button>

Which should allow me to change users name and save it.

The saveChanges action in controller looks like this:

controllers/users.js
saveChanges(){
    this.get('model').save();
}

Now the problem is that it seems that the input from the template is not bounding the value with records attribute, whenever the input value changes it does not changes the models value.

The second problem is that this.get('model').save(); doesn't even sends a patch to the server.

Everything else just works fine, its just this that doesn't work. Does anyone have a clue what could be wrong here?

Thanks!




How to send addicional information along with ember Delete model request

I have an ember model that I want to delete. So, according to the documentation I could do any of the following:

store.findRecord('post', 1, { backgroundReload: false }).then(function(post) {
        post.deleteRecord();
        post.get('isDeleted'); // => true
        post.save(); // => DELETE to /posts/1
    });

OR

store.findRecord('post', 2, { backgroundReload: false }).then(function(post) 
{
  post.destroyRecord(); // => DELETE to /posts/2
});

But, let's say that in order to delete the post model I need addicional information. For exemple, I also want to know the 'idAplication' (aplication sending delete request) and 'userEmail' (user trying to delete post).

The problem is: by default the ember store will only send me the post id: myapi.com/posts/1

How can I do this ? How to send something else with the body delete request using ember model ?




mercredi 16 janvier 2019

How can I use a model in a component in isolation but maintain a one-way bind for model refreshes?

I currently have component that displays a table of results abse don the m odel passed into it:

\\pagedContent is a computed property of the model


The table updates its contents as various filters are selected via query params. I've bee trying to implement some 'sort on click' behaviour to the table headings with the following code:

    import Component from '@ember/component';
    import {
      computed
    } from '@ember/object';

    export default Component.extend({

      model: null,
      init() {
        this._super(...arguments);
        this.dataSorting = ['total_users']
        this.dataSortingDesc = ['total_users:desc']
      },

      sortedDataDesc: computed.sort('unsortedData', 'dataSortingDesc'),
      sortedData: computed.sort('unsortedData', 'dataSorting'),
      unsortedData: computed('model', function () {
        return this.get('model');
      }),

      actions: {
        columnsort(property) {
          if (!this.get('tableSorted')) {

            this.set('dataSortingDesc', [`${property}:desc`])
            this.set('model', this.get('sortedDataDesc'))
            this.set('tableSorted', true)

          } else {
            this.set('dataSorting', [property])
            this.set('displayModel', this.get('sortedData'))
            this.set('model', null)
          }
        },
      }
    });

The sorting works as expected but I have a problem due to the two way binding of the model. Other components on the template also uses the model and when the data in the table is sorted, it creates all kinds of problems with those components.

I tried to create a seperate 'copy' of the model using a computed property like follows:

  \\a new property
  displayModel: computed('model', function () {
    return this.get('model');
  }),
  sortedDataDesc: computed.sort('unsortedData', 'dataSortingDesc'),
  sortedData: computed.sort('unsortedData', 'dataSorting'),
  unsortedData: computed('model', function () {
    return this.get('model');
  }),

  actions: {
    columnsort(property) {
      if (!this.get('tableSorted')) {

        this.set('dataSortingDesc', [`${property}:desc`])
        this.set('model', this.get('sortedDataDesc'))
        this.set('tableSorted', true)

      } else {
        this.set('dataSorting', [property])
        this.set('displayModel', this.get('sortedData'))
        this.set('model', null)
      }
    },

The table then iterates over displayModel to create itself. This produces a behaviour where the columns sort but then the display 'freezes' once a column heading is clicked and does not update as the underlying model updates. In this case, I can see from my other components that the model continues to update as new filters are applied.

I was also unsuccessful using a oneWay and didUpdateAttrs implementation. I'd be grateful for any advice.




Why cannot see any code completion after imported an EmberObject extension into a different file, using Visual Studio Code?

As already explained in the title, I can't see any code completion after imported an EmberObject extension

  • file form.js:

    import EmberObject from '@ember/object'; 
    
    const Form = EmberObject.extend({
            isTouched: false,
            isValid: false,
            errors: null,
            value: null,
            init() {...},
            getSomething(){ ... }  
    }
    
    
  • file component.js

    import Form from '../../classes/form';
    
    init() {        
     this._super(arguments);        
     // console.log(this.elementId);        
     this.form = Form.create({          
         email: [this.email, Validators.required, Validators.email],
         password: [this.password, Validators.required]         
     });
    }
    
    

at this point in component.js when I type this.form. the editor (VSC) doesn't give me any real suggestion on Form class/EmberObject

Any guess?




mardi 15 janvier 2019

How to fix 'Cannot lock down 82274202 byte memory area' and 'AcquireSelfRealTime error'?

I was following the steps at https://github.com/fossasia/open-event-frontend/blob/development/docs/installation/local.md to set up the project locally. When typing ember serve, I get the following error:

Starting Ember....
Registering: list_commands
Registering: quit
Registering: toggle_erispolling
Starting Ember version 0.7.2
Initializing Ember services
Registering: loadscript
Registering: connect
Registering: meta_refresh
Registering: meta_abort
Metaserver Service created
Registering: set_value
Registering: get_value
Setting home directory to /home/rounak/.ember
Cannot lock down 82274202 byte memory area (Cannot allocate memory)
Cannot lock down 82274202 byte memory area (Cannot allocate memory)
Cannot use real-time scheduling (RR/5)(1: Operation not permitted)
JackClient::AcquireSelfRealTime error

I have already tried ways such as adding username to the audio group and modifying the limits.conf file but to no avail. I even tried sudo ember serve but then I get the following error:

Starting Ember....
Registering: list_commands
Registering: quit
Registering: toggle_erispolling
Starting Ember version 0.7.2
Initializing Ember services
Registering: loadscript
Registering: connect
Registering: meta_refresh
Registering: meta_abort
Metaserver Service created
Registering: set_value
Registering: get_value
Setting home directory to /home/rounak/.ember
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
No protocol specified
xcb_connection_has_error() returned true
Home directory not accessible: Permission denied
No protocol specified
xcb_connection_has_error() returned true
Home directory not accessible: Permission denied
ALSA lib pcm_dmix.c:1052:(snd_pcm_dmix_open) unable to open slave
AL lib: (EE) ALCplaybackAlsa_open: Could not open playback device 'default': No such file or directory
No protocol specified
No protocol specified
No protocol specified
terminate called after throwing an instance of 'Ogre::RenderingAPIException'
  what():  OGRE EXCEPTION(3:RenderingAPIException): Couldn`t open X display :0 in GLXGLSupport::getGLDisplay at /build/ogre-1.9-Gd49ok/ogre-1.9-1.9.0+dfsg1/RenderSystems/GL/src/GLX/OgreGLXGLSupport.cpp (line 807)
Crashed with signal 6, will try to detach the input system gracefully. Please report bugs at https://bugs.launchpad.net/ember
Aborted

Please help me to overcome this.




How to load page in application.hbs?

I have to work with ember.js only in front-end for some website and my friend asked me to load a connexion page then a home page with a navbar etc... My problem is about and I don't really understand because when I my next home page, connexion is still here... I don't know what instruction write in application.hbs in order to load Connexion.hbs then index.hbs with navbar... Can someone help and explain me ?

I just want to load connexion.hbs when I load my website, then I click on "sign in" I want to load another page with a navbar (I already have this code, thanks bootstrap) and home page. I just need some link between my pages.

Thanks !




lundi 14 janvier 2019

In Ember.js, how can I return a hard 404 code if a route is not found?

badurl

I have the following route whenever a bad route is given from my webpage. The problem however, is that even though "technically" it says a 404, it's really not a 404. At the network level, this is actually a 200 level code.

twohundredcode

Now this makes sense. After all, the web server appropriately handles the URL but it's my ember app that catches the error.

Can I need explicitly send out a 404 using Ember.js?




dimanche 13 janvier 2019

undefined is not an object (evaluating 'this.get('i18n').t') , Error while qunit testing ember app usuing i18n translations

Here's my code which works fine.

    export default Route.extend({
  beforeModel() {
    this.controllerFor('myreusable-template').set('currentStep', 'prepare_data');
  },

  afterModel(model) {
    if (model.get('roles.length') === 0) {
      model.newRole({
        name: this.get('i18n').t('routes.myreusableTemplate.addRoles.user1')
      });
    }
  }
});

here are my test case file imports

import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
import tHelper from 'ember-i18n/helper';
import localeConfig from 'ember-i18n/config/en';

moduleFor('controller:myreusable-template/my-file', {
  unit: true,
  needs: ['service:layoutSizeData',
    'service:i18n',
    'locale:en/translations',
    //'locale:en/config',
    'util:i18n/missing-message',
    'util:i18n/compile-template',
    'config:environment'],
  beforeEach() {
    this.container.lookup('service:i18n').set('locale', 'en');
    this.registry.register('locale:en/config', localeConfig);
    this.registry.register('helper:t', tHelper);
  }
});

And this is the error I am getting while executing the file.

undefined is not an object (evaluating 'this.get('i18n').t').

I am following the i18n doc to write the imports but it still not working. I am using ember ember-cli: 2.12.3, "ember-i18n": "5.0.1".




Ember.Computed is not a function

I'm trying to setup simple application with Ember using ember-chart: https://www.npmjs.com/package/ember-cli-chart

I have my charts.hbs file:

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
        
            <div class="chart-container">
                
            </div>
        
        </div>
    </div>
</div>

and my charts.js controller with sample from documentation of Chart.js:

import Controller from '@ember/controller';
import Ember from "ember";

export default Controller.extend({
    CHARTTYPE: 'bar',
    CHARTDATA: Ember.Computed('', function () {
        return {
            labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        }
    }),
    CHARTOPTIONS: Ember.Computed('', function () {
        return {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    }),
    CHARTWIDTH: 500,
    CHARTHEIGHT: 500,
});

In index.js route i have redirection to charts route:

beforeModel() {
    this.replaceWith('charts');
}

When I am trying to open my localhost:4200 after ember s it gives me an error in console:

router.js:927 Error while processing route: index Ember.Computed is not a function TypeError: Ember.Computed is not a function

I tried to search for an answer but nothing seems to work.




How to mirror site that uses server side javascript and RequireJS? That is - force the app to recognize site already loaded?

I am having a heck of a time saving a site for offline viewing, due to the way the app uses javascript.

Some background:

  1. The site uses Ember-JS for rendering. It uses RequireJS for loading various modules used for various tasks such as user interaction. It also uses a tool called New Relic but I think it is just for reporting.
  2. I have no access to the remote server.
  3. I log on to site to gain access.
  4. When site fully loads, when viewing source code from Chrome, apart from and some other boiler plate content, there is no content actually displayed. Instead you have

    \<--EMBER_CLI_FASTBOOT_BODY-->

Ignore that backslash - I just couldn't figure out how to get the editor to properly display commented HTML...

  1. I use Chrome Extension Save All Resources to save site for offline. But that doesn't result in a useful .html file.
  2. So, in Chrome Dev Tools, I view the DOM in order to grab the actual, rendered HTML and save a html file at required folder level so that assets saved in 5 above are referenced correctly.
  3. All is good, but when I open the saved HTML file (via localhost), it first loads the page and all looks well, but then the page suddenly goes blank...

So... with above out of the way, I have spent weeks trying to reverse engineer this thing. I have stepped through the javascript and there are a ton of actions going on since the app doesn't realize that it doesn't have to do anything and it is trying to do everything that it does when first rendering the page. A ton of initializers, etc, etc, etc.

For instance, there is a part of the app that contains this:

define("site/initializers/login-refresh", ["exports", "ember", "jquery", "site/config/environment"], function(e, t, n, a) {
    e.default = {
        name: "login-refresh",
        initialize: function() {
            var e = this,
                r = 0,
                l = void 0;
            if ("readonly" !== a.default.environment) {
                var i = (0, n.default)('<iframe id="login-refresh" style="width: 1px; height: 1px; left: -500px; position: fixed;"></iframe>');
                (0, n.default)("body").append(i);
                var o = function n() {
                    if (r++, t.default.run.later(e, n, 6e4), !document.cookie.match(/masquerading/)) {
                        r % 15 != 0 && document.cookie.match(/^canvas_user_id=|; canvas_user_id=/) || (console.log("Refreshing session"), i.attr("src", "/login/saml?return_to=/accounts/1"));
                        var a = document.cookie.match(/(\s|^)ad_user_login=([0-9]+)[^0-9]/i);
                        a || (a = document.cookie.match(/(\s|^)ad_session_id=[0-9]+%2c([0-9]+)[^0-9]/i)), !l || a && a[2] === l || !confirm('You seem to have changed users.  Press "Ok" to reload this page with your new credentials.') || (window.location = "/login/saml?return_to=" + encodeURIComponent(window.location.href)), a && (l = a[2])
                    }
                };
                t.default.run.later(this, o, 6e4)
            }
        }
    }
})

At the point where the page goes blank, the code jumps to this section and in the Chrome Dev Tools console I see errors about not being able to load that /login/saml?return_to page. Understood.

So I edited one of those if statements above to be

if (false) {
                        r % 15 != 0 && true || (console.log("Refreshing session"), i.attr("src", "/login1/saml?return_to=/accounts/1"));
                        var a = document.cookie.match(/(\s|^)ad_user_login=([0-9]+)[^0-9]/i);
                        console.log(a);
                        a || (a = document.cookie.match(/(\s|^)ad_session_id=[0-9]+%2c([0-9]+)[^0-9]/i)), !l || a && a[2] === l || !confirm('You seem to have changed users.  Press "Ok" to reload this page with your new credentials.') || (window.location = "/login2/saml?return_to=" + encodeURIComponent(window.location.href)), a && (l = a[2])
                    }
                };
                //t.default.run.later(this, o, 6e4) 

With that alteration and commenting out that annoying timer the page now loads, and I see images and the app's audio players, but there is no working javascript interaction. For instance, the page has various elements that act like bootstrap collapse. The part of the app that controls that functionality is

define("site/mixins/interactions/reveal_content", ["exports", "jquery"], function(e, t) {
    function n(e) {
        this.el = e, this.interactionData = e.find(".interaction_data"), this.container = e.find(".interaction_content")
    }
    n.prototype = {
        init: function() {
            var e = (0, t.default)("<div />").append((0, t.default)(this.interactionData.find("td")[1]).detach()),
                n = (0, t.default)('<div class="pointer" />').append((0, t.default)(this.interactionData.find("td")[0]).detach());
            this.container = this.container.parent().find(".RevealContent"), this.container.append(n), this.container.append(e.hide()), n.click(function() {
                (0, t.default)(e).slideToggle("slow")
            }), n.find("a").click(function(e) {
                e.preventDefault()
            })
        }
    }, e.default = n

And here is the HTML for one such element:

<div class="interaction_content RevealContent" style="min-height: 400px; width: 400px;">
    <div class="pointer">
        <div id="area49275747_95" class="component image-component float-left clear-none  booted">
        <img src="somelink.html" title="" alt="" style="padding-right: 10px;" width="58" height="59">
        </div>
        <p class="body" id="area49275747_96"><em><strong><a href="#">Workshop Answers 5.<br></a></strong></em></p>
    </div>
    <div style="display: none;"><p class="body" id="area49275747_104"><strong><em>6th and 7th </em></strong></p></div>
</div>

Now, I have confirmed that this HTML is same on remote version of loaded page. And note how you have "booted" in class name for this particular div:

<div id="area49275747_95" class="component image-component float-left clear-none  booted">

I would think that tells the app (in theory) that all content is loaded/booted. So the HTML is all there, but somehow the app is nonetheless not letting any of the javascript functionality to work and I just can't figure out why... Maybe because I interfered with that login-refresh function, something else is breaking, like event listeners not loading. I just don't know. Or maybe I am missing something that is so simple, while all this time I have been stepping through code, trying to understand what RequireJS is all about and whether it is screwing things up, or whether this New Relic is culprit, etc, etc.

I have thought about writing a script to just convert all the interactions to standard jquery and HTML5, but that will be a lot of work. I really hope I can just get all these RequireJS module defines to work in this offline context...

I am tempted to turn this into a code challenge and offer 100 EURO/USD to the first person that can help me figure out what I need to do... Anyway, the app file is large, about 1.4 MB. I can post if anyone is interested, but I thought maybe someone right off the bat understands what is central to the problem just from what I have described here.

Disclaimer: I am a guitarist and not a developer. I know a thing or two about coding, but this sort of enterprise level app is beyond my current understanding... That said, if someone can point me in right direction I can get this straightened out :-)

Thanks!

Brian




samedi 12 janvier 2019

ember-cli-eslint, ember-cli-stylelint to run automatically only if desired

I understand that the purpose of ember-cli-eslint, ember-cli-stylelint to run automatically.

I am wondering if there is a way to control this behavior.

Like, run ember-cli-eslint, ember-cli-stylelint automatically only if there is certain ENVIRONMENT_VARIABLE or maybe write a custom script.

I am wondering if that is possible. Google search did not provide me any pointer.




How to define multiple variables in one deep in a EmberJS path route

I want to define a path which looks like that: diff/:left...:right

The params in the route looks is {left...:right: "1...2"}.

Is there some special syntax to use when the variables are not between two slashes /?




Why does my Firebase injection fail to register and be available for acceptance tests?

I've imported the Firebase SDK into my Ember app. There is an initializer that injects Firebase into the entire app like so:

export function initialize(application) {

  const config = {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "my-app-xxxxxx.firebaseapp.com",
    databaseURL: "https://my-app-xxxxxx.firebaseio.com",
    projectId: "my-app-xxxxxx",
    storageBucket: "my-app-xxxxxx.appspot.com",
    messagingSenderId: "xxxxxx"
  }

  if( typeof firebase !== 'undefined'  && firebase) {
    firebase.initializeApp(config);
    application.register('firebase:home', firebase, {instantiate: false});
    application.inject('route', 'firebase', 'firebase:home');
  }
}

export default {
  name: 'firebase',
  initialize
};

This is initializer properly injects firebase and makes it available in all my routes and templates as far as I can tell. I'm able to use authentication and read, write to the database correctly.

The problem happens when I try to write an acceptance test. For example a simple test where I enter the main route:

import { module, test } from 'qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';

module('Acceptance | login', function(hooks) {

  setupApplicationTest(hooks);

  test('visiting /login', async function(assert) {

    await visit('/home');

    debugger;
    assert.equal(currentURL(), '/home');


  });
});

Hitting the home route instantly produces a window alert of ReferenceError: firebase is not defined. Shouldn't the initializer have handled this?

I don't understand why firebase is readily accessible and everything works when the app is running normally, yet it is undefined when used with an acceptance test.




vendredi 11 janvier 2019

Is there a way to customize selected item in ember-power-multiple-select without rendering custom component's template for each selected option?

As the docs state,

In multiple selects the selectedItemComponent component is rendered as once per each selected option.

I wonder if there is a way to make it render in a different way: I need to show selected value when only one option is selected, but when there are several options selected I'd like to display

"<selectedThings> - 3" i.e just a text - type and number of selected options.




jeudi 10 janvier 2019

How to upgrade ember-cli globally to run ember serve of the latest

I'm trying to get Ember-cli globally to the latest version so that when I run ember new it actually installs the latest version. I've followed the instructions here: https://cli.emberjs.com/release/basic-use/upgrading/

npm uninstall -g ember-cli
npm install -g ember-cli
ember --version

And the version (v2.15) does not reflect the change (v3.7). I've also checked the version just after uninstalling and it still shows up as if it hadn't been removed. I've also tried running npm cache clean after the uninstall.

I'm running ubuntu 16.04

I've also tried following the similar question here: How to upgrade ember cli version and it does NOT solve my problem.

Is there some way to select what version to use when running ember new? Or change the global version selected?




mercredi 9 janvier 2019

How to resolve Ember deprecation: "Use defineProperty to define computed properties"

While attempting to update an Ember application to Ember 3.6 (currently on the 3.4 LTS), I have come across several instances of the following deprecation.

https://deprecations-app-prod.herokuapp.com/deprecations/v3.x/#toc_ember-meta-descriptor-on-object

Use defineProperty to define computed properties

until: 3.5.0

id: ember-meta.descriptor-on-object

Although uncommon, it is possible to assign computed properties directly to objects and have them be implicitly computed from eg Ember.get. As part of supporting ES5 getter computed properties, assigning computed properties directly is deprecated. You should replace these assignments with calls to defineProperty.

These deprecations display in the browser console as:

DEPRECATION: [DEPRECATED] computed property 'session' was not set on object '<app@component:component1::ember439>' via 'defineProperty' [deprecation id: ember-meta.descriptor-on-object] See https://emberjs.com/deprecations/v3.x#toc_use-defineProperty-to-define-computed-properties for more details.

DEPRECATION: [DEPRECATED] computed property 'gStories' was not set on object '<app@component:component2::ember427>' via 'defineProperty' [deprecation id: ember-meta.descriptor-on-object] See https://emberjs.com/deprecations/v3.x#toc_use-defineProperty-to-define-computed-properties for more details.

component1:

HBS:

<div>
  
    <h2>Signed in</h2>
  
    <h2>Sign Up</h2>
    
  
</div>

JS:

The session service is from ember-simple-auth: http://ember-simple-auth.com/api/classes/SessionService.html

import Component from '@ember/component';
import { service } from 'ember-decorators/service';

export default class Component1 extends Component {
  @service('session') session;
}

component2:

HBS:


  <h2>
    Stories
  </h2>

  
    
  


JS:

import Component from '@ember/component';
import { computed } from 'ember-decorators/object';
import { argument } from '@ember-decorators/argument';

export default class Component2 extends Component {
  constructor() {
    super(...arguments);
  }

  @argument
  stories = null;

  @computed('stories')
  get gStories() {
    let stories = this.get('stories');
    let gStories = [];
    stories.forEach((story) => {
      "use strict";

      if (story.get('type') === 'g') {
        gStories.pushObject(story);
      }
    });

    return gStories;
  }
}

I'm hoping that someone can show me how to resolve the two cases above in which I can clean up the remainder of my application. Perhaps there is a better coding practice that I should be using instead as the deprecation states "Although uncommon".

Any additional background information on this deprecation would be appreciated.

Thanks in advance!




Is there a more "ember way" to compute this value?

Note: I am forced by circumstance to use Ember 2.18, but interested if ^3.4 has it if 2.x does not.

I am computing a Boolean based on two other Boolean. Inside the class there is this:

userEmail: '',
feedbackText: '',
emailIsValid: match('useEmail' /^.+@.+\..+$/),
feedbackTextIsValid: gte('feedbackText.length', 5),
disableSubmit: computed('emailIsValid', 'feedbackTextIsValid', function() {
  return (!this.get('emailIsValid) || !this.get('feedbackTextIsValid'));
}),

In other words, the property disableSibmit should be true if userEmail is not a valid email or if feedbackText is less than 5 characters. It does this properly

What I am wondering is if I can use something similar to not or match to return True If either of 2 other values is not True




how to select ivy-tab default tab

Im using ember version of ivy-tabs to populate my tabs. and when there is an error im using a condition to add a class which will be show the tab in red color. but when the color is changing the tab is also getting changed. i need to stop this or load it into default tab. i tried with their documentation and release notes and there is no clue on that.

code as follows



    <div class="edit_profile">
      <div class="modal--content--sidebar">
        
          <ul role="presentation" class="modal_tabs">
            <li role="presentation" class="modal_tabs--item ivy-tabs-tab">
              
                Personal
              
                Personal
              
            </li>
            <li role="presentation" class="modal_tabs--item ivy-tabs-tab">
              
                Contact
              
                Contact
              
            </li>
            <li role="presentation" class="modal_tabs--item ivy-tabs-tab  " >
              
                Professional
              
                Professional
              
            </li>
          </ul>
        
      </div>

      <div class="modal--content--container">

        <div class="modal--content--scroll_container">
          

            

          

          

            

          

          

            

          

        </div>


  




mardi 8 janvier 2019

Ember 3.6 super-rentals tutorial LEAFLET_MAPS_API_KEY using environment.js

While going through the ember 3.6 super-rentals tutorial I ran into a few snags adding the ember-simple-leaflet-maps. I couldn't get the environment variable LEAFLET_MAPS_API_KEY to set. https://guides.emberjs.com/release/tutorial/service/

To my understanding, the tutorial has you set an environment variable on your operating system? Maybe I'm wrong in thinking that, but I wanted a way to just add the variable to my project /config/environment.js

After the addon was installed:

ember install ember-simple-leaflet-maps

I opened the geocode.js file to see how the service was injecting the api key. Path is: node_modules\ember-simple-leaflet-maps\addon\services\geocode.js

The line of code was:

let accessToken = getOwner(this).resolveRegistration('config:environment')['ember-simple-leaflet-maps'].apiKey;

From there I just added the lookup it was looking for to my file /config/environment.js

let ENV = {
    modulePrefix: 'super-rentals',
    environment,
    rootURL: '/',
    locationType: 'auto',
    'ember-simple-leaflet-maps': {
      apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

Rebuild the project and serve, my maps are now showing up

ember build
ember serve




Event handling in EmberJS components using blocks

I've been working on a UI in Ember and I am having difficulty implementing some of the event handling as described on the documentation here

I have a section of a nav bar I need to highlight on hover. The nav bar is made up of ember-bootstrap components.

    

<div class="container-fluid" style="padding-left:50px;padding-right:50px; ">
    <a class="navbar-brand" href="#"><img style="max-width:250px; margin-top: -12px;margin-bottom: -12px" src="/assets/images/logo_white_3x.png"></a>
    
        
            
                LIVE
            
        
    
    <div class="navbar-nav mr-left">
        
            
                " as |dd|}}
                    Link<span class="caret"></span>
                        
                            Link
                            Link
                        
                
                
                    Current User: <b>MICKEY MOUSE</b>
                
            
        
    </div>
</div>


To accomplish this I tried to use one of the block events described n the documentation:

 //template
 
  <h1>link</h1>
 

//component
export default Component.extend({
  hover() {
    alert('hovered')
  },
  actions: {
      //actions here
  }
});

This produces the following error: hover not found, and the catch-all block handler didn't handle it

I thought it might be because the name of the even must be hyphenated so changed it accordingly. This produced a no component or helper by that name error.

Copying and pasting the same text from the guide produces the same errors which suggests there is something more fundamental I am not understanding.

Can anyone shed any light?




lundi 7 janvier 2019

ember data different models for same endpoint

I have an API that doesn't return JSON data in a format that Ember-Data expects. Especially when getting a list of resources versus a single resource.

For example, GET /api/widgets/{id}

Should return a single widget model that might look like this:

//app/models/widget.js

import DS from 'ember-data';

export default DS.Model.extend({
   name: DS.attr('string'),
   weight: DS.attr('number'),
   color: DS.attr('string')
});

Whereas getting the full list of widgets via GET /api/widgets/ returns a model that should look like this:

// app/models/widgetlist.js

import DS from 'ember-data';

 export default DS.Model.extend({
   total: 22,
   widgets: DS.hasMany('widget')
});

(I think that's how my widget list model should look. It's essentially a total count of widgets in system and current paginated set of widgets)

I'm having a really hard time figuring out what combination of models, custom adapter and/or custom serializer I need in order to get this to work.




Jquery Datatable shows "No data available" even having datas in ember

i included datatable in my ember application where i load some datas in grid. Even though there is data the at the end of my grid it shows "No data available" and also pagination search sort are not working. Could you please help me how to resolve this issue




dimanche 6 janvier 2019

How to handle action in EmberJS in nested Component

so I have nested components in EmberJS and can't manage to properly handle their actions.

I have route Create and in its template Component pixel-grid:

<div class="row">
<div class="col-sm-7">
    
</div>
<div class="col-sm-5">

</div>

In pixel-grid template i have component named pixel-cell:

<table class="mx-auto">

<tr class="table-row">
    
    <th class="table-cell">
        
    </th>
    
</tr>


Component pixel-cell have an empty template since I don't need it for now. In pixel-cell component js file I have:

import Component from '@ember/component';

export default Component.extend({
classNames: ['cell', 'clickable'],
tagName: 'div',

init() {
    this._super(...arguments);
},

});

This code obviously do not compile since I did not handle this action. But..

I tried to set action in pixel-cell but then Ember told me that pixel-grid should have that action. So I did put this changeColor action in pixel-grid -> that doesn't work.

So I tried to handle this by something like this in pixel-cell js:

click() {
    this.sendAction('changeColor');
},

-> that doesn't work.

I have no idea how it should work ;/ I tried to read guides but still can't manage that. Please help.




samedi 5 janvier 2019

How to determine where a function is invoked?

Like in which hook of the component the function was called ?

I need to assert that a function in my mixin is invoked only in the didInsertElement() hook and not before, so that the function could handle the DOM.




jeudi 3 janvier 2019

EmberJS - HTML string compile with actions

I have the following HTML string and I want to render it dynamically including with the onclick event listener. How to do it in EmberJS?

hello.js

export default Ember.Component.extend({
    didInsertElement() {
        var message = `
            <p>Hello World!</p>
            <a onclick=>Learn More</a>
        `;
        this.set('message', message);
    },

    actions: {
        handleOpenUrl() {
            //open url code
        }
    }
});

hello.hbs

}




How to add more keys to request payload on click of a button?

I have a custom request payload to get api response in an ember-bootstrap-modal. Now I want to add another toggle button "show/hide" which should add/remove keys to my request payload object on click of it. How can I do that?

X.js :

let reqPayload = {
    retrieveFlags: {
        childFare: true,
        additionalGuestFare: true,
        roundUpFare: true,
        averageFare: true
        }
      }

y.hbs:

<button>Show</button>

on click retrieveFlags should be

let reqPayload = {
    retrieveFlags: {
        childFare: true,
        additionalGuestFare: true,
        roundUpFare: true,
        averageFare: true,
        refundableFare: true,
        nonRefundableDepositFare: true,
        nonRefundableFare: true,
        }
      }




How can I use cordova's InAppBrowser in an Ember application?

We're creating a hybrid app using the Corber addon for Ember and we wish to use the InAppBrowser plugin for Cordova to enable user authentication.

How can we access the cordova.InAppBrowser object within Ember?

I've added the below code to the authenticator's authenticate method as recommended by various sites, however cordova is showing as undefined. I haven't been able to find any documentation as to what to import into the file to enable the cordova.InAppBrowser object.

const browser = cordova.InAppBrowser.open(<someUrl>, "_blank", {
    location: "no", 
    toolbar: "no", 
    hidenavigationbuttons: "yes"
});
browser.addEventListener('loadstart', function(event) {
    if (event.url.indexOf(<someRedirectUrl>) === 0) {
        browser.close();
    }
});

I would like to be able to open "someUrl" in an InAppBrowser to allow users to authenticate using an OAuth2 site.

Many thanks




How do I type a decorated property which type is changed by the decorator?

Here's some code that works perfectly in JS:

import Component from '@ember/component';
import {task} from 'ember-concurrency';

class Foo extends Component {
  currentRecordId!: string; // passed from template

  @task
  fetchRecord *(id) {
    return yield this.store.findRecord('foo', id);
  }

  async fetchCurrentRecord() {
    return this.fetchRecord.perform(this.currentRecordId);
  }
}

Ember Concurrency is an alternative to promises that allows cancelling and managing them similar to Observable from RxJS. Since JS promises don't allow cancelling, Ember Concurrency uses yield instead of async/await.

The task decorator used above converts a generator function into a TaskProperty instance that has a .perform() method.

Please note, that, though weird, this pattern has proven its handiness and reliability in non-typed JS apps.

But typing it presents a challenge.


Here are

export declare function task<T, A>(generatorFn: () => Iterator<T>): Task<T, () => TaskInstance<T>>;

export declare function task<T, A>(
  generatorFn: (a: A) => Iterator<T>
): Task<T, (a: A) => TaskInstance<T>>;

export declare function task<T, A>(
  generatorFn: (a: A) => Iterator<PromiseLike<T>>
): Task<T, (a: A) => TaskInstance<T>>;

export declare function task<T, A1, A2>(
  generatorFn: (a1: A1, a2: A2) => Iterator<T>
): Task<T, (a1: A1, a2: A2) => TaskInstance<T>>;

// More variants of arguments skipped

export interface TaskInstance<T> extends PromiseLike<T> {
  readonly error?: any;
  readonly hasStarted: ComputedProperty<boolean>;
  readonly isCanceled: ComputedProperty<boolean>;
  readonly isDropped: ComputedProperty<boolean>;
  readonly isError: boolean;
  readonly isFinished: ComputedProperty<boolean>;
  readonly isRunning: ComputedProperty<boolean>;
  readonly isSuccessful: boolean;
  readonly state: ComputedProperty<TaskInstanceState>;
  readonly value?: T;
  cancel(): void;
  catch(): RSVP.Promise<any>;
  finally(): RSVP.Promise<any>;
  then<TResult1 = T, TResult2 = never>(
    onfulfilled?: ((value: T) => TResult1 | RSVP.Promise<TResult1>) | undefined | null,
    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
  ): RSVP.Promise<TResult1 | TResult2>;
}

interface Task<T> extends TaskProperty<T> {
    readonly isIdle: boolean;
    readonly isQueued: boolean;
    readonly isRunning: boolean;
    readonly last?: TaskInstance<T>;
    readonly lastCanceled?: TaskInstance<T>;
    readonly lastComplete?: TaskInstance<T>;
    readonly lastErrored?: TaskInstance<T>;
    readonly lastIncomplete?: TaskInstance<T>;
    readonly lastPerformed?: TaskInstance<T>;
    readonly lastRunning?: TaskInstance<T>;
    readonly lastSuccessful?: TaskInstance<T>;
    readonly performCount: number;
    readonly state: TaskState;
    perform(...args: any[]): TaskInstance<T>;
    cancelAll(): void;
}

export interface TaskProperty<T> extends ComputedProperty<T> {
    cancelOn(eventNames: string[]): this;
    debug(): this;
    drop(): this;
    enqueue(): this;
    group(groupPath: string): this;
    keepLatest(): this;
    maxConcurrency(n: number): this;
    on(eventNames: string[]): this;
    restartable(): this;
}

These types aren't official and can be customized.


I struggle with properly typing the topmost code sample.

The error I'm getting is:

Property perform does not exist on type () => IterableIterator<any>.

It is understandable, since fetchRecord is defined as a generator.

Moreover, TypeScript officially does not support decorators that change the type of decorated property.

So the question is: how to work around the limitation and type such a decorator without reverting to @ts-ignore?

In addition to typing the fetchRecord property, I would like to properly type the arguments that I pass into this.fetchRecord.perform() and which are received by the generator.

Thank you. ^__^




mercredi 2 janvier 2019

How can I load a stylesheet dynamically in an Ember route?

I'd like to breakup my stylesheet and import smaller chunks on route load. With the code below I'm able to successfully create the <link> element with the correct attributes. Once the DOM is loaded is appears in the <head> just as I would have expected it as if I loaded in index.html. However, the styles don't load.

beforeModel() {
  let link = document.createElement('link');
  const rootURL = this.get('router.rootURL');

  link.rel = "stylesheet";
  link.type = "css";
  link.href = `${rootURL}assets/muh_sheet.css">`;

  document.head.appendChild(link);
}

It shows up in the <head> tag with the correct src, no console errors. Still doesn't load the styles.




How to send property values to svg files using ember-inline-svg?

I am using ember-inline-svg, there is a logo.svg file , I'm calling it with

in my hbs file. It works fine. I just need to send one more data param to it and access that in the svg file so that i can dynamically generate svgs I would i go about doing that ?