vendredi 31 mai 2019

EmberJS: overwriting ember-ajax error helper

I'm overwriting the isUnauthorizedError function of ember-ajax in order to invalidate the user's session, but only if the host of the request matches a specific host. However, I can't find a way to determine the host inside that function. Is there any way?

import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
   isUnauthorizedError(arg1, arg2, arg3) {
     // retrieve host
   }
});




Ember not setting hasMany relationship attribute after retrieving data

Foreward: There are a lot of firsts in this project, such as building my first API, first time using JSON API, first time using Ember, first time posting on SO, etc.

I'm trying to access an 'authors' hasMany attribute in my template containing the latest updates. What I access it in the template, however, nothing is returned. The models are being saved correctly, but the relationship is not being set it appears, as the length of the DS.PromiseManyArray on latest.contentAuthors is 0 while the promise is fulfilled ({ _length: 0, isFulfilled: true, isRejected: false }).

I'm using Ember 3.10 (with CLI). I have full control over my backend (LAMP running ExpressionEngine 5) and am serving API requests through a custom built plugin, though I'm not sure that matters to much as this seems to largely be a frontend problem from what I can discern.

Route

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

export default Route.extend({
    model(){
        let latest = this.store.peekAll('latest');
        if (latest.length < 2){
            latest = this.store.query('latest', { limit: 2, include: "people" });
        }
        return latest;
    }
});

Base Model

import DS from 'ember-data';
const { Model } = DS;

export default Model.extend({
    title: DS.attr()
});

Latest Model

import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';

export default ExpressionEngineBase.extend({
    title: DS.attr(),
    blurb: DS.attr(),
    contentAuthors: DS.hasMany('person')
});

Person Model

import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';

export default ExpressionEngineBase.extend({
    title: DS.attr(),
    latest: DS.hasMany('latest')
});

Template


    <h2></h2>
    
        <div></div>
    
        <div>Can't find author(s)</div>
    
    <p></p>


Data sent from server

{
    "data": [{
        "id": 3161,
        "type": "latest",
        "attributes": {
            "title": "Amazing Video 1"
        },
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/video\/3161"
        },
        "relationships": {
            "people": {
                "data": [{
                    "id": 1,
                    "type": "people",
                    "links": {
                        "self": "https:\/\/cms.example.com\/api\/v1\/people\/1",
                        "channel": "https:\/\/cms.example.com\/api\/v1\/people"
                    }
                }]
            }
        }
    }, {
        "id": 2573,
        "type": "latest",
        "attributes": {
            "title": "Amazing Article 1"
        },
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/white_papers_insights\/2573"
        },
        "relationships": {
            "people": {
                "data": [{
                    "id": 1,
                    "type": "people",
                    "links": {
                        "self": "https:\/\/cms.example.com\/api\/v1\/people\/1",
                        "channel": "https:\/\/cms.example.com\/api\/v1\/people"
                    }
                }, {
                    "id": 52,
                    "type": "people",
                    "links": {
                        "self": "https:\/\/cms.example.com\/api\/v1\/people\/52",
                        "channel": "https:\/\/cms.example.com\/api\/v1\/people"
                    }
                }]
            }
        }
    }],
    "links": {
        "self": "https:\/\/cms.example.com\/api\/v1\/latest?include=people&limit=2"
    },
    "included": [{
        "id": 1,
        "type": "people",
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/people\/1",
            "channel": "https:\/\/cms.example.com\/api\/v1\/people"
        },
        "attributes": {
            "title": "Great Author"
        }
    }, {
        "id": 52,
        "type": "people",
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/people\/52",
            "channel": "https:\/\/cms.example.com\/api\/v1\/people"
        },
        "attributes": {
            "title": "Great Co-Author"
        }
    }]
}

To reiterate, the relationship model is saving and is viewable in Ember Inspector, but the actual link/relationship is not being set.




Ember : dedounce called multiple times on scroll event listener

I added a debounce method inside a scroll event listener. Something like this.

$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});

When I do the scroll on $group the debounce is also called the same number of times the scroll event called. I don't know where is the loophole in this thing.

For example, if 5 times the scroll event printed then debounce called is also called 5 times.

This is the link for ember debounce documentation.




jeudi 30 mai 2019

How to fix 'Webpack Returned Errors to ember-auto-import' Build Error in Ember.js

I have a problem build error like title of my topic, anyone can help me? error

Here's my package.json devDependencies: { "@ember/jquery": "^0.5.2", "@ember/optional-features": "^0.6.3", "broccoli-asset-rev": "^2.7.0", "ember-ajax": "^3.1.0", "ember-cached-shoe": "^0.2.0", "ember-cli": "^3.8.1", "ember-cli-app-version": "^3.2.0", "ember-cli-babel": "^6.16.0", "ember-cli-bundle-analyzer": "0.0.3", "ember-cli-concat": "^1.3.0", "ember-cli-dependency-checker": "^3.0.0", "ember-cli-eslint": "^4.2.3", "ember-cli-fastboot": "^2.0.0", "ember-cli-head": "^0.4.1", "ember-cli-htmlbars": "^3.0.0", "ember-cli-htmlbars-inline-precompile": "^1.0.3", "ember-cli-inject-live-reload": "^1.8.2", "ember-cli-less": "^1.5.5", "ember-cli-moment-shim": "^3.7.1", "ember-cli-qunit": "^4.3.2", "ember-cli-shims": "^1.2.0", "ember-cli-sri": "^2.1.1", "ember-cli-string-helpers": "^1.9.0", "ember-cli-template-lint": "^1.0.0-beta.1", "ember-cli-uglify": "^2.1.0", "ember-concurrency": "^0.8.19", "ember-data": "~3.4.0", "ember-export-application-global": "^2.0.0", "ember-font-awesome": "^4.0.0-rc.4", "ember-in-viewport": "^3.1.5", "ember-link-action": "^0.1.3", "ember-load-initializers": "^1.1.0", "ember-maybe-import-regenerator": "^0.1.6", "ember-moment": "^7.7.0", "ember-resolver": "^5.0.1", "ember-screen": "^1.0.0", "ember-service-worker": "^0.7.0", "ember-source": "~3.4.0", "ember-web-app": "^2.3.0", "eslint-plugin-ember": "^5.2.0", "loader.js": "^4.7.0", "qunit-dom": "^0.7.1" }

I’am using ember-cli: 3.10.1, node: 10.16.0, os: win32 x64.

Please someone help me, thanks.




How to prevent pasting text in ember input helper?

I'm using ember input helper to get some value in the application. The text field should not allow any text to be pasted. (Something like re-enter some value)

I've just tried



This didn't work. But in normal html, The following works.

<input value=inputText onpaste="return false">

But the problem here is no two-way binding (which supports in ember input helper).




merge function occuring error while executing the code

I have the javascript file which not validating the below ember js code:

helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};
var buffer = '', stack1, escapeExpression=this.escapeExpression, self=this;

While I'm executing the above code, I'm getting this.merge is not a function. (Note: I'm upgrading ember from 1.4.0 to 1.12.2 and I'm using Handlebars 2.0.0). Please provide me the suggestion




mercredi 29 mai 2019

Is it possible to extract some files from ember static files?

There is a task to change translations dynamically. Admin should be able to rewrite language constants file. But that won't work till ember rebuild. Can I somehow extract lang files from the dist and use them like "outside of app"?

I guess I can place them on the server and try to load into the Ember app with each refresh. But maybe there is a more interesting way?




Label are not showing while upgrading Ember version

I'm upgrading the ember from 1.4.0 to 1.12. While upgrading labels are not showing

This is my code for corresponding HBR file


    <div class="checkbox-set">
        <ul class="check-list">
            
                
                    <li class="check-list-entry location" >
                        
                            
                            <mo-label>}</mo-label>
                        
                        
                    </li>
                
            
        </ul>
        
    </div>


I need to show the label details by using the above HBR file code.




mardi 28 mai 2019

Can you console.log inside our config/environment.js?

Is there any possible to console the value from .env file to our config/environment.js?




What is the correct way to set session data with ember-simple-auth

I am using Ember-simple-auth for authentication and have followed this.

My login method looks like this:

authenticate() {
  const { username, password } = this.getProperties('username', 'password');
  this.get('session').authenticate('authenticator:oauth2', username, password).catch((err) => {
    this.set('loginError', 'Login failed: ' + JSON.stringify(err.message));
  })
}

This correctly returns the API token and sets isAuthenticated to True.

My session service uses a computed property to return a promise with the user information like this:

  player: computed('isAuthenticated', function() {
    const userId = this.get('session.content.authenticated._id');
    if (!Ember.isEmpty(userId)) {
      return DS.PromiseObject.create({
        promise: this.get('store').findRecord('user', userId)
      })
    }

I can then access by injecting the session service, but I can't see any session data in my browser. The only thing I can see is ember_simple_auth-session in local storage? How can I extend my own custom class of session data?




this.get(...).then is not a function when using init: ember.js

I am using init() in my component to load some data for a dropdown. On refresh it works but when I leave the tab to another tab then come back I get the following error: index.js:143322 Uncaught TypeError: this.get(...).then is not a function

This code is in my init function and I suspect it has something to do with how ember.js renders but I am struggling to figure out how to make it work. I tried using the other lifestyle hooks but none of them worked.




Ember JS : Lazy load Model data

I'm trying to render ember model data which has more than 1000 records. This will take more than 2 min to finish the rendering part.

So, I have a plan to optimize it. I want to load the first 100 records in the first time. Once they go to the end then I need to load the second 100 records.

How can I do that?




lundi 27 mai 2019

EmberJS + ember-intl: automatically generate additional locales

I'm using Ember with ember-intl for localization and have a en.json file that I want to translate into several different locales (different JSONs). Is there any tool that can help with this?

Initially I wanted to parse the source json file with a script and translate it by using Google Translate API. However, the parsing is pretty complex since ember-intl uses the ICU Message Syntax




ember-cli-mirage trying to stub auth0 (external) URL

I am working on a new Ember.js project and using ember-cli-mirage to stub out my requests. The project is going to use ember-simple-auth and Auth0 for user authentication. I began implementing them in my project, but I'm getting a weird error in the console when I try to sign up with my Google account using the Auth0 login modal:

Your Ember app tried to GET 'https://(my auth0 domain).auth0.com/userinfo',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?

(my auth0 domain redacted above)

I have no idea why Mirage would be trying to stub out a request to an external URL. I was reading the Mirage docs and tried using this.passthrough() in my mirage/config.js file so Mirage would make a real request, but that seems to have had no effect (I'm guessing it only explicitly applies to routes within a namespace defined in the config file).

Can anyone help me understand why this is happening and how to stop Mirage from doing it? Thank you!




dimanche 26 mai 2019

ember assets - "public" assets should not be fingerprinted but they are?

In my Ember.js 3.8 project I have an image file in :

/public/assets/images/foo.png

... According to this (admittedly a little out of date) files put in public/assets/images should be available unchanged when referenced as assets/images.

This is up to date, a little less explicit but says that items placed beneath public will end up beneath assets.

When I do a production build the file I have in /public/assets/images/ ends up /dist/assets/images/ but with a finger print, eg foo-97cf8c0765aefa517d22e1fc71f43d6e.png.

Am I meant to explicitly suppress the finger-printing ? The doco seems to suggest that's not necessary ?




How to delete ads from an embed video code (Not youtube video)

Hello i want to get this embed video from Nbatv live https://live-nba.stream/watch/nba-tv-live.html to my page but without ads. What i need to pput in the html code to block ads




samedi 25 mai 2019

How to get REST Api in Ember JS?

I“m learning ember and have troubles with REST api. I“ve read docs, but I just can't understand, how it works. It’s really a problem, and I’d like to ask experiences people, and I would be very grateful for any help. I just need to understand the principle of how it works. In China, when kung-fu masters teach their students, they say "do as I do". So, show me please how you do it! So, we have two rouset in Laravel backend, that return JSON. Here is response of index (/) route:

<code>
{
    "responce":[
        {
            "id":0,
            "title":"main",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam."
        },
        {
            "id":1,
            "name":"about",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?"
        },
        {
            "id":2,
            "name":"contacts",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem."
        }
    ]
}
</code>

And here is response of posts (/posts) route:

<code>
{
    "posts":[
        {
            "id":0,
            "name":"First",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing."
        },
        {
            "id":1,
            "name":"Second",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto quas quia distinctio ex consequuntur."
        },
        {
            "id":2,
            "name":"Third",
            "content": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam, similique. Voluptatum, libero sequi."
        }
    ]
}    
</code>

In Ember we have routes “index” and “posts”. I suppose there must be some kind of loop that processes the received data and outputs it.

The result on the index page should look something like this:

<pre>
<!--Index page in Ember-->
<h3>main</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae, aliquam.</p>
<h3>about</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, obcaecati? Accusantium ex dolorum voluptate deleniti?</p>
<h3>contacts</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates voluptatibus exercitationem molestias rem.</p>     
</pre>

And on the posts client page:

<pre>
<!--Posts page in Ember-->
<h3>First</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing.</p>
<h3>Second</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto quas quia distinctio ex consequuntur.</p>
<h3>Third</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam, similique. Voluptatum, libero sequi.</p>     
</pre>

What Ember elements should be involved in this, how it all communicates and works? I really have not found any demonstrative examples on the Internet that show the whole chain. If I saw all this, I would immediately understand. Great thanks in advance! (excuse me my french)




jeudi 23 mai 2019

In-template pattern to pass variable to a passed down action (contextual component)

Is it possible to pass a variable to a passed down action entirely in-template?

eg. Parent Component



Child Component


   


..that doesn't work, but it shows an idea of the desired behaviour.

What I current have to do is make an action in item-component to trigger the passed down action with the variable.

eg. Parent Component

  actions: {
    setActiveItem(item) {
      set(this, "activeItem", item);
    }
  }

Parent Component Template



Child Component

  actions: {
    click(item) {
      this.itemClick(item);
    }
  }

Child Component Template


   


What I'm trying to ask, is there a way to skip creating the wrapper action in the child template? Is there an Ember helper where this just works? eg.






ember-bootstrap - rendering "radio" inputs

Using the Ember addon ember-bootstrap I can make a set of radio buttons like this :



with a Controller that looks like this :

export default Controller.extend({

  init() {
    this._super(...arguments);
    this.radioOptions = [
      {
        label: 'Citrus',
        value: 'C',
        inline: true
      },
      {
        label: 'Non-Citrus',
        value: 'N',
        inline: true
      }
    ];
  }

});

The relevant doco is here https://www.ember-bootstrap.com/#/components/forms .

However what I can't do is provide a custom value to each radio button so that I end up with rendered HTML like this :

  <label>Citrus</label>  
  <input type="radio" value="C">
  <label>Non-Citrus</label>  
  <input type="radio" value="N">

I have looked at "Custom Controls" on https://www.ember-bootstrap.com/#/components/forms but I can't see how that applies to this case.




Ember Data: Pushing the data to the store will not replace the changedAttributes of the record?

I am using Ember Data and I have a model say my-model. I am having a realtime notification server to update my application if there is any change for a record. When I am editing an attribute of my-model from UI, the model has some changedAttributes and when the real time notification comes, I am fetching the record from the server and pushing it to the store using store.push(store.normalize('my-model', data)).

Now, In the store the model still has my changedAttributes and it is not replaced. So I believe, the Ember Store will not replace the entire record and will replace only the clean attributes of the record when I do a store.push. I just want to confirm the behaviour. Can someone confirm if my understanding about this is right?




Ember JS : How to reuse ember data while calling?

I have two models to call. In the first model I include somedate like this.

this.stroe.query('comment',{
   include : 'person,address'
});

And in the second call I include the same details that already stored in the store.

this.stroe.query('post',{
   include : 'person,address'
});

So, the API call takes a lot of time to resolve. Is there any way I can use the First API include data in the second API call to create a relationship between those two models(person, address). This would save a lot of time for me.

Anyone, please help me with this.

Note: Examples are testing purpose only.




mercredi 22 mai 2019

How can I add monaco editor

I want to add monaco editor from here : https://github.com/mike-north/ember-monaco.

Actually initially I am using Ace Editor. I want to replace it.

But I could not understand what I have to write in the Monaco editor instance




Ember Mirage - Not able to capture the response

A newbie to ember, I am trying to simulate the API server using ember-cli-mirage. I am creating a request from account.js through store but the response is not something I expect.

## /app/routes/account.js

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

export default Route.extend({
  store: service(),

  model() {
    this.store.findAll('accounts').then(response => {
      console.log(response)
    });
    // return this.store.findAll('accounts');
  }
});



## /app/mirage/config.js

export default function () {
  this.get('/accounts', (schema) => {
    return {
      data: [
        {
          firstName: 'John'
        }
      ]
    };
  }, {timing: 2000});
}

This is the response I get, enter image description here

Is there anything missing?




Cannot read property 'inlineReference' of undefined in rasterizeHTML from jspdf

I'm using jspdf to render HTML to PDF in an Ember app. jspdf is included using the ember-js-pdf plugin, which is getting me jspdf v1.5.3. html2canvas seems to have recently moved to a promise-based model which jspdf isn't ready for, so I tried rasterizeHTML.js instead. Once I made it available in the app by adding

  app.import('node_modules/rasterizehtml/dist/rasterizeHTML.js');

I'm able to build, but then when I print I get this error:

Uncaught TypeError: Cannot read property 'inlineReferences' of undefined
at Object.module.rasterize (rasterizeHTML.js:1009)
at Object.module.drawDocument (rasterizeHTML.js:1081)
at Object.jsPDFAPI.addHTML (jspdf.debug.js:15833)

...and at that point, uh?

It looks like rasterizeHTML is looking for any inline assets to retrieve and include, and not finding any? Is this a bug in rasterizeHTML?




mardi 21 mai 2019

accessing controller properties within controller function in ember

Can't able to access the controller property within a controller function

App.ViewRController = Ember.Controller.extend({ datas:null, actions:{

viewfile:function(){
    let filename = this.get('filename');
    let count=0;
    let data;
            let self = this;
    if (filename!=null)
    {
        filename=filename.trim();
        if(filename.length>0)
        {

            try{
            let obj= new XMLHttpRequest();
            obj.onreadystatechange=function(){
            if(obj.readyState==4 && obj.status ==200)
                {

                    let json=obj.responseText;
                    console.log(self);
                    data = JSON.parse(json);
                    self.set(datas,data);


                }

            }

            let params = "filename="+filename;
            obj.open("POST","view");
            obj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            obj.send(params);
            //this.set('datas',data);
            }
            catch(e){alert(e);}
        }
        else
            alert("enter filename");
        }
        else
            alert("enter filename");
    }

}

the template should will iterrate the datas object with properties. but I couldn't set the datas property within the function in the controller.




lundi 20 mai 2019

options.scales.yAxes[0].ticks.callback not getting updated dynamically in ember-cli-chart

I have embedded ember-cli-chart in my hbs file as

<div class="chart">
    
</div>

In my component file I have created an options property as

options: computed('metric', function() {
  let opts = defaultOptions;
  if (this.metric === 'height') {
     opts.scales.yAxes = [{
         ticks: {
             callback: function(value, index, values) {
              // code to return labels
             }
        }
     }]
  } else {
     opts.scales.yAxes = [{
         ticks: {
             callback: function(item, index, items) {
                 // code to return labels
             }
        }
     }]
  }

  return opts;
});

I want to display Y-Axis labels based on the current selected metric. When first time chart loads it renders correct labels on y-Axis and if I change the metric then the same callback is getting used instead of the other one (in else part) and renders same labels but with updated data values. Can anyone help on this?




How can I make an Ember computed property depend on all descendent properties of a variable?

I'm trying to create a computed property that I want to be reevaluated whenever any value in a deeply nested object changes. I understand that myObj.[] can be used to reevaluate computed properties whenever any object in an array changes, but I want this to be recursive.

eg I have

// should recalculate whenever myObj.x.y.z changes, or when myObj.a.b.c changes
computed('myObj', function() {
  // ...
})

I don't know in advance exactly how the object is structured, and it may be arbitrarily deep.

Neither computed('myObj.[]', ...) nor computed('myObj.@each', ...) seem to work for this.

Any ideas how to do this?




Updating Ember.js environment variables do not take effect using in-repo addon config() method on ember serve

My goal here is to create an auto-increment build number that updates both on ember build and ember serve. In the end, if I can only use this on build, that's totally ok.

I originally asked this question: In-repo addon writing public files on build causes endless build loop on serve In that I was attempting to solve this problem by writing out JSON files. The problem was mostly solved, but not using ember serve.

Instead of doing that, I'm now trying to update the local environment. But this is having a similar problem with ember serve. I've got the build number incrementing fine. I can use the config() method to set custom/dynamic variables in the environment. The problem I'm having is that the even though I can log the change in terminal when config() is called, and I can see it run on serve when files change, I don't see the changes in browser when I output Ember's ENV using ember serve. Here's my addon's methods so far.

Note: the appNumberSetup() function is just reading a local json file in the project root and updating the build number. That's working fine. Anything about pubSettingsFile can be ignored, I won't be using that moving forward.

init(parent, project) {
    this._super.init && this._super.init.apply(this, arguments);
    // we need to setup env in init() so config() and prebuild()
    // will see update immediately
    this.settingsFile = path.resolve(this.appDir,  this.settingsFileName);
    this.addonPubDataPath = path.resolve(this.appDir, 'lib', this.name, 'inc', 'public', 'build-data-output');
    this.pubSettingsFile = path.resolve(this.addonPubDataPath,  this.pubSettingsFileName);
    // this only checks for .env variables and sets defaults
    this.dotEnvSetup();
    // must set this so prebuild skips processing a build number on build
    // else we get build number incremented twice on first run
    // then appNumberSetup() disables so subsequent serve preBuild() will run.
    this.skipPreBuild = true;
    this.appNumberSetup();

},
// this sends our created settings data to ENV.localBuildSettings in app
config(environment, appConfig){
    // this 'buildme' is just an experiment
    let x = `buildme${this.buildNumber}`;
    let r = {
        localBuildSettings: this.settings
    };
    r[`buildme${this.buildNumber}`] = this.buildNumber;
    this.dlog("Config ran...");
    this.dlog(JSON.stringify(r, null, 4));
    return r;
},
preBuild: function(result){
    // init() disables preBuild() here, but subsequent builds with serve still
    // run appNumberSetup() to update this.settings for env and JSON
    if(this.skipPreBuild === true){
        this.skipPreBuild = false;
    }
    else {
        // only run here after init runs
        this.appNumberSetup();
    }
    // don't do this... write file makes endless loop on serve
    // this.saveSettingsFile(this.pubSettingsFile, this.settings);

},

this.settings is a local variable in addon and it updated on build/serve, the JSON looks like this:

{
"appVersion": 911,
"appBuildNumber": 7117
}

Is there a way to update Ember's ENV with dynamic data? (like a new build number)

The addon config() appears to run on each change in ember serve, and it shows the build number in terminal output. But it looks like that runs after postBuild(). Maybe that's why I don't see the changes. Is there a way to update that environment during preBuild()?




Ember list of model not reloaded without refreshing page

I'm displaying only published articles by sorting my list with the 'published' attribute.

Now when I edit an article and set it from 'published' to 'draft' and then I return to the list I see the 'draft' article even if I wrote a filter in my controller.

article.save()
this.transitionToRoute('article.list');

Just going to another page and return to the list, or doing a browser refresh is enough to list properly only 'published' articles and so solve my problem.

Where am I suppose to look to solve my problem without refreshing ? Thanks




dimanche 19 mai 2019

Expecting ':' on a click function on IE

I have an ember project which I am testing if IE. It works on chrome and firefox so far but on IE I cant see anything on the page but I get this error

enter image description here

This error points here, right after the word 'click' and before ()

enter image description here

Which looks fine, this code is located in a component. Ive tried passing in the event and returning true but im still getting this error.

Does anyone know whats causing this?




How to rerender in Ebmer.js component when service got data?

I create service that fetching endpoint in interval. I want tot rerender a component when service fetched data. Maybe I can create some custom event or use observer to listen service changed?




samedi 18 mai 2019

Visual Studio Code terminal freezes when asking to overwrite file for Ember.js

VS Code just installed update 1.34.0

I have created a new project in Ember. When I attempt to create a new route ember g route application, I am asked if I want to overwrite app\templates\application.hbs. When I press Y and then Enter, the terminal freezes. I have to close it and open a new one. Unfortunately, the route is not created.

Is anyone else getting this? Am I doing something wrong?




Ordering of data according to date is returning a server error

I am trying to view the items according to an ordered sequence of date attribute (not created_at) and time attribute, but a GET http://localhost:4200/events 500 (Internal Server Error) is being returned. The ordering is working on every other attribute.

This is my index function in the controller:

def index
    render json: Event.order(eventDate: :asc, startTime: :asc)
end




vendredi 17 mai 2019

How to fix Sentry User Feedback Error - Cannot read property 'showReportDialog' of undefined

I've been trying to get a User Feedback dialog to show when I click on a certain button, but I've had some trouble. I successfully got it to work when I make a call my API and end up getting an error shown first.

However I created a button that would trigger a call to Sentry.showReportDialog, but I get a 'Cannot read property 'showReportDialog' of undefined' error. I've tried using Sentry.capture Message/Exception/Error to generate an eventId, but I still got the same error. This is my current code that's failing, but I've modified it a decent amount and was still getting the same undefined error for showReportDialog, even when I tried the method that worked with my API call. This web application is running using Ember.js v3.5.1 and in my package.json the dependency for sentry is "@sentry/browser": "^4.5.3"

// works
try {
    $('.ember-application').addClass('request-loading');
    this.model.setProperties(properties);
    return yield this.model.save();
} catch (err) {
    // Get feedback from user through sentry
    Sentry.init({
        dsn:'https://ec08003a76fa4b6e8f111237ed3ed8e1@sentry.io/1369772',
        beforeSend(event) {
            if (event.exception) {
            Sentry.showReportDialog({ eventId: event.event_id });
        }
        return event;
    },
});

}

// does not work
try {
    throw new Error();
} catch (e) {
    var eventId = yield Sentry.captureException(e, function(sendErr, eventId) {
        // This callback fires once the report has been sent to Sentry
        if (sendErr) {
            console.error('Failed to send captured exception to Sentry');
        } else {
            console.log('Captured exception and send to Sentry successfully');
            console.log(eventId);
        }
    });
    console.log(eventId);
    Sentry.showReportDialog({ eventId: eventId });
}




Uncaught TypeError: this.transitionTo is not a function in route

I am trying to redirect my page to the homepage after I successfully delete the item but it is telling me transitonTo is not a function.

This is my code:

import Route from '@ember/routing/route';
import Ember from 'ember';
import { inject as service } from '@ember/service';

/**
 * @module lebtivity/routes/event
 */
export default Route.extend({
  /**
   * @type {Service}
   */
  api: service(),

  ajax: Ember.inject.service(),

  /**
   * @param {Object} params The parameters extracted from the URL.
   * @return {Promise<Object>}
   */
  model(params) {
    return this.get('api').request(`/events/${params.slug}`);
  },

  actions:{
    remove: function (model) {
        console.log(model.id);
        Ember.$.ajax({
               method: "DELETE",
               url: model.id,
               success: function(data)
               {
                 this.transitionTo('index');
               }
             })
    }
  }
});




Unable to do a successful delete ajax request in ember

I am trying to make a button delete an item which is an event. In order to do so I have to do an ajax delete request and adjust the event-controller and routes.rb.

This is in my hbs file where I have my button:

<button class="event__delete-btn" >Delete</button>

This is my action remove function in event.js:

actions:{
    remove: function (model) {
        console.log(model.id);
        Ember.$.ajax({
               method: "DELETE",
               url: ":"+model.id
             })
    }
  }

This is my Events Controller I only added the destroy function:

class EventsController < ApplicationController
  def index
    render json: Event.all
  end

  def show
    render json: Event.find_by(slug: params[:slug])
  end

  def destroy
    @event = Event.find(params[:id])
    @event.destroy
    render json: {}
  end

  def create
    event = Event.new(filtered_params)

    if event.save
      render json: event
    else
      render json: { errors: event.errors }, status: 422
    end

  end

  private

  def filtered_params
    params.require(:event).permit(
      :name,
      :description,
      :location,
      :event_date,
      :start_time,
      :end_time,
      :contact
    )
  end
end

These are the routes I have in routes.rb, I added the delete one:

  get 'events' => 'events#index'
  get 'events/:slug' => 'events#show'
  post 'events' => 'events#create'
  delete '/event/:id' => 'events#destroy'

But whenever I am pressing delete I get: DELETE http://localhost:4200/event/:1 404 (Not Found) I am new to ember and rails so what did I do wrong?




Ember - object related item lost on page reload

I have Order and PaymentMethod models in Ember related like so:

order.js

export default DS.Model.extend({
    paymentStatus: DS.attr('number', { defaultValue: 1 }),
    paymentMethod: DS.belongsTo('payment-method'),
})

payment-method.js

export default DS.Model.extend({
    name: DS.attr('string'),
    orderPaymentMethods: DS.hasMany('order')
})

The order is saved to the database - all fine. I then have a route review-order, which obtains the order model (my API is only retuurning order models for the current logged in user)

review-order.js

export default Route.extend({
    model() {
        const order = this.store.findAll('order', { include: 'payment_method' }).then((orders) => {
           return orders.filterBy('paymentStatus', 1).get('lastObject');
       });
       return order;
   }
});

In my review-order template, I am printing out the payment method relationship like so



This works fine when I am navigate (transitioned to) when the order is created - it prints the name of the payment method. However, if I refresh the page, this is lost, and I have no idea why!




How to fix warning "interaction added to non-interactive element no-invalid-interactive"

I just upgraded my Ember addon from version 3.0 to version 3.8, and I get this warning now:

Interaction added to non-interactive element no-invalid-interactive

An example of this is something like:

<div class="some-class" onclick=>
    <div> more content </div>
</div>

What are my options to fix it the right way, so that it is accessible?




jeudi 16 mai 2019

How do I install bootstrap 4 template to Ember web project?

This is a continuation of another post I have posted: click here

I have downloaded the INSPINIA admin theme, which is based off twitter bootstrap. It contains pre-created projects for most web-ui frameworks, except Ember. Steps taken so far:

  1. Installed ember-boostrap
  2. Installed SASS pre-processor
  3. Copied the *.scss files into the app/styles folder
  4. The app.scss file looks as follows:

app\styles\app.scss

@import "ember-bootstrap/bootstrap";

@import "style";

  1. The Ember-Cli-Build.js file is as follows:

Ember-Cli-Build.js

'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    'ember-bootstrap': {
      'bootstrapVersion': 4,
      'importBootstrapFont': false,
      'importBootstrapCSS': false
    }
  });
  return app.toTree();
};




ember-bootstrap errors when rendering a form

I have a problem using ember-bootstrap to render a form. When the route is visited nothing is rendered and in the console the message

enter image description here

appears.

The project is a Bootstrap 3 project and I have just installed ember-boostrap. To do that I did the following :

ember install ember-bootstrap
ember generate ember-bootstrap --preprocessor=sass
ember generate ember-bootstrap --bootstrap-version=3

From reading the doco I believe that was the correct sequence of commands ?

I then created a new route and in the template I put the following :


            
            
            
            
            
            
          


Which is the sample template from the form component in the ember-bootstrap doco .

As I said when I go to visit the the new route I get nothing rendered and the error message shown above.

I feel like I must have overlooked some part of the directions ... is there something obviously missing ?




Ember deploy script failing on specific npm package

I'm trying to deploy to my staging environment using ember deploy and continue to get this error which breaks the build

An error occurred in the constructor for ember-cli-htmlbars-inline-precompile

I tracked down the issue via guess and checking to a specific handlebars template, that once commented out stopped the problem and allowed me to finish the script. Unfortunatley I'm getting this same issue again. This error does not occur when I build or run the app locally.

Is my package.json I'm using node 6.15.1 I've tried v0.3.0, v0.4.0, v1.0.0, and v2.0.0 of ember-cli-htmlbars-inline-precompile to no avail. I'm assuming my problem again is in some handlebars template, but unfortunately without the errors locally I can't deduce the location.

  "name": "~~~",
  "description": "Small description for ~~~~ goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "start": "ember server",
    "build": "ember build",
    "test": "ember test",
    "lint": "eslint .",
    "postinstall": "./node_modules/bower/bin/bower install --allow-root"
  },
  "repository": "",
  "engines": {
    "node": "6.15.1"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {},
  "dependencies": {
    "@babel/core": "^7.4.4",
    "@newrelic/publish-sourcemap": "4.4.0",
    "active-model-adapter": "^2.2.0",
    "babel-eslint": "^7.0.0",
    "bower": "^1.8.2",
    "broccoli-asset-rev": "2.2.0",
    "broccoli-stew": "^2.1.0",
    "ember-ajax": "^3.0.0",
    "ember-cli": "~2.15.1",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-babel": "^6.7.1",
    "ember-cli-bootstrap-sass": "git+https://github.com/~~~/ember-cli-bootstrap-sass.git",
    "ember-cli-content-security-policy": "0.4.0",
    "ember-cli-dependency-checker": "^2.0.0",
    "ember-cli-deploy": "^1.0.2",
    "ember-cli-deploy-build": "^1.1.1",
    "ember-cli-deploy-change-log": "git+https://github.com/~~~~/ember-cli-deploy-change-log.git",
    "ember-cli-deploy-display-revisions": "^1.0.1",
    "ember-cli-deploy-gzip": "^1.0.1",
    "ember-cli-deploy-revision-data": "git+https://github.com/ember-cli-deploy/ember-cli-deploy-revision-data.git",
    "ember-cli-deploy-s3": "git+https://github.com/~~~/ember-cli-deploy-s3.git",
    "ember-cli-deploy-s3-index": "git+https://github.com/~~~/ember-cli-deploy-s3-index.git",
    "ember-cli-deploy-slack": "^1.0.1",
    "ember-cli-eslint": "^4.0.0",
    "ember-cli-flash": "^1.7.1",
    "ember-cli-htmlbars": "^2.0.1",
    "ember-cli-htmlbars-inline-precompile": "^2.0.0",
    "ember-cli-inject-live-reload": "^1.10.2",
    "ember-cli-inline-content": "^0.4.0",
    "ember-cli-loading-slider": "^2.0.0",
    "ember-cli-moment-shim": "^3.7.1",
    "ember-cli-phone-number": "^0.1.4",
    "ember-cli-pretender": "0.5.0",
    "ember-cli-qunit": "^4.0.0",
    "ember-cli-release": "0.2.9",
    "ember-cli-sass": "^10.0.0",
    "ember-cli-shims": "^1.1.0",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^2.2.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-cli-velocity": "^0.4.0",
    "ember-cli-version-checker": "^2.1.2",
    "ember-click-outside": "0.1.12",
    "ember-composable-helpers": "2.1.0",
    "ember-data": "~2.16.3",
    "ember-decorators": "^2.5.2",
    "ember-export-application-global": "^2.0.0",
    "ember-faker": "1.1.0",
    "ember-inflector": "^2.3.0",
    "ember-link-action": "^0.1.3",
    "ember-load-initializers": "^1.0.0",
    "ember-moment": "^7.8.1",
    "ember-new-relic": "0.6.1",
    "ember-resolver": "^4.0.0",
    "ember-simple-auth": "^1.8.2",
    "ember-source": "^2.15.3",
    "ember-welcome-page": "^3.0.0",
    "eslint": "~2.2.0",
    "eslint-config-google": "^0.4.0",
    "eslint-config-xo": "^0.10.1",
    "eslint-plugin-babel": "^3.1.0",
    "express": "^4.16.4",
    "font-awesome": "^4.7.0",
    "glob": "^7.1.4",
    "jquery": "~2.2.4",
    "loader.js": "^4.7.0",
    "phantomjs-prebuilt": "^2.1.16",
    "rsvp": "^4.8.4",
    "sass": "^1.20.1",
    "velocity-animate": "^1.5.2"
  }
}```




Webstorm / Ember, Inspections: "Cannot resolve directory"

Inside app/styles/app.scss, i have this code and works: @import 'node_modules/foundation-sites/assets/foundation';

But, by WebStorm its underlined in red: 'cannot resolve directory' i found that Webstorm is looking for node_modules inside app/styles.

It does not make a difference if i mark the directory node_modules as Recource-Root, i receipt always the same errors.

But Ember works.

How can i tell Web-Storm that there is no Problem? Or is there a better, more recommendet Way for linking foundation in ember?

ember-cli-foundation-6-sass is currently not maintained and it did'nt work for me. I tried this way: https://foundation.zurb.com/sites/docs/installation.html#command-line-tool.html npm install foundation-sites

Thanks, Christian




mercredi 15 mai 2019

Cannot access window.location.search in EmberJS beforeModel

I cannot access window.location.search in the beforeModel. I can however access window.location and search is populated when I open the object.

beforeModel(transition) {
  console.log(window.location) // returns object with populated search
  console.log(window.location.search) // undefined
}

I expected window.location.search not to be undefined because it is populated when I call window.location




Django REST framework - disable browsable api for user view?

In my api, I have a /users endpoint which currently shows (eg address) details of all users currently registered. This needs to be accessed by the (Ember) application (eg to view a user shipping address) but for obvious reasons I can't allow anyone to be able to view the browsable api. I don't think I can use authentication and permissions, since the application needs to log a user in from the front end app (I am using token based authentication) in the first instance. If I use authentication on the user view in Django for instance, I am unable to login from Ember.

Am I missing something?




mardi 14 mai 2019

How to use ember-leaflet using ember-cli 2.16?

So, I downloaded the addon https://miguelcobain.github.io/ember-leaflet/docs/container called ember-leaflet. The ember-cli version that I am using is 2.16. Here's my code

  <LeafletMap lat=lat lng=lng zoom=zoom as |layers|>
    <layers.tile url="https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"/>
  </LeafletMap>

The error that was shown on my console is ember.debug.js:2925 Uncaught DOMException: Failed to execute 'setAttribute' on 'Element': '|layers|' is not a valid attribute name.

Any response is much appreciated




Ember : What is the meaning of re-render in ember js?

I'm using ember.js(version 3.7) and I bite confused now. Now, I'm working on optimizing the code part for our app. First I'll try to find What are the things are re-render in components? After getting into this topic I bite confused with it.

In ember they used didRender() method to trigger re-rendering things (jQuery DOM Manipulation, Asnyc function loading,etc...). Right now I don't have much idea about re-render in ember. Can someone explain to me re-render in detail? And, please share if you have any resource about re-render in ember.

Thanks in advance.




"Already up-to-date" and "Run 'yarn' to install missing dependencies"?

I've got a bit of a weird situation where "ember s" reports "Missing yarn packages" followed by a list of missing packages (two of them) and then "Run 'yarn' to install missing dependencies".

However when I run 'yarn' I get the message "success Already up-to-date" .

Any ideas how to get out of this circle ?


There's something I did immediately before this started which I guess is the source of my problem

Getting rid of an Add-on

I had installed an Ember Add-on which had generated problems so I decided to get rid of it . To do that I did the following :

git push -f origin 913c2dee12b0363df0664c9c63e0443abe0adb57:foo-bar
git reset --hard 913c2dee12b0363df0664c9c63e0443abe0adb57
yarn
yarn install
yarn clean
yarn install
yarn

Where 913c2dee12b0363df0664c9c63e0443abe0adb57 was the last commit before the unwanted add-on was installed. I don't think there was anything wrong in doing that but now I'm wondering.


Output of running Ember Server

When I run 'ember s' I get this output ...

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: foobar -> ember-cli-build-date -> ember-cli-babel

Missing yarn packages:
Package: @bower_components/jquery
  * Specified: jquery/jquery-dist#
  * Installed: (not installed)

Package: @bower_components/jstree
  * Specified: vakata/jstree#^3.3.5
  * Installed: (not installed)

Run `yarn` to install missing dependencies.



Stack Trace and Error Report: /tmp/error.dump.33c6e8c0abc9fc8abd355dc080268f9c.log
An error occurred in the constructor for ember-cli-dependency-checker at /media/mint/dev/foobar/node_modules/ember-cli-dependency-checker


Warning about ember-cli versions

I don't think this is relevant but just for completeness

Running the 'yarn' results in the following appearing in the output text ...

warning foobar@0.0.0: "dependencies" has dependency "ember-cli" with range "~3.8.1" that collides with a dependency in "devDependencies" of the same name with version "3.8"




How to structure correctly route and folders in emberjs?

Say I have this folder structure:

- app
-- pods
--- dashboard
----- zones
------ index
------- controller.js
------- route.js
------- template.hbs
------ show
------- areas
-------- controller.js
-------- route.js
-------- template.hbs
------- controller.js
------- route.js
------- template.hbs

And in router.js

    this.route('zones', function() {
      this.route('show', { path: ':zone_id/cities' }, function() {
        this.route('areas', { path: ':city_id/areas'});
      });
    });

Now

When I visit dashboard/zones - all zones will be loaded

And when I clicked one item from zones, it will be redirected to dashboard/zones/1/cities which will load cities in page

And when I clicked one item from cities, it will be redirected to /dashboard/zones/1/cities/4/areas -

Now the problem is /dashboard/zones/1/cities/4/areas url is correctly hit, but the template is not showing.

What is missing or wrong with my setup ?




ember.js - update form in modal and on its own route?

Within a 3.x Ember.js app I want to show the user an update form overload over the existing screen.

The existing screen would be on a route '\vegetables' and the update form would be on '\vegetables\update\carrots'. If the update was a conventional form there wouldn't be a problem but how do I go about displaying a form overlaid on the existing form ? Is there an add-on for this ?

I'm using bootstrap to style the ui and so bootstrap modals are available but I'm not sure how that would fit into a template ?

I have seen a number of addons but they all seem to be aimed at a modal appearing within the current route and for reasons of authentication/authorization I want a seperate route for this update operation.

Thanks




Ember - saving Foreign Key relationship, using Django DRF (JSON API)

I have the following models for Order, User and PaymentMethod.

In Django, they are defined (fields excluded for brevity) as follows:

class User:
    email = models.EmailField(unique=True)
    class JSONAPIMeta:
        resource_name = 'users'

class PaymentMethod:
    name = models.CharField(max_length=255, unique=True)
    class JSONAPIMeta:
        resource_name='payment-methods'

class Order:
    user = models.ForeignKey(User,blank=True,null=True,on_delete=models.SET_NULL,related_name="user_orders")
    payment_method = models.ForeignKey(PaymentMethod, null=True, on_delete=models.SET_NULL, related_name="order_payment_methods")

    class JSONAPIMeta:
        resource_name = 'orders'

I have serializer classes as follows:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','email')

class PaymentMethodSerializer(serializers.ModelSerializer):
    class Meta:
        model = PaymentMethod
        fields = ('id', 'name')

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ('id','user','payment_method')

The viewsets are as follows:

from rest_framework import viewsets

class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all().order_by('id')
    serializer_class = OrderSerializer

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class PaymentMethodViewSet(viewsets.ModelViewSet):
    queryset = PaymentMethod.objects.all()
    serializer_class = PaymentMethodSerializer

In my Ember models, I the relationships are simple (I have created a serializers which transforms paymentMethod in Ember to payment_method for Django)

user:

export default DS.Model.extend({
    email: DS.attr('string'),
});

order:

export default DS.Model.extend({
    user: DS.belongsTo('user'),
    paymentMethod: DS.belongsTo('payment-method'),
});

payment-method:

export default DS.Model.extend({
    name: DS.attr('string'),
    orderPaymentMethods: DS.hasMany('order')
});

In Ember, I save the order as follows, having already obtained objects for the user and payment method:

let orderData = {
   user: userObject,
   paymentMethod: paymentMethodObject
};

this.store.createRecord('order', orderData).save().then((order) => {
    ... redirect etc
});

This saves the order fine with regard to the user object, but it's not saving the payment method relationship.

Upon inspection of the create method in the Order serializer, the payment method object is not present.

To fix this, I tried overriding the create method of the order view set as follows:

 def create(self, request, *args, **kwargs):
     payment_method_id = request.data.get('payment-method').get('id')
     payment_method = PaymentMethod.objects.get(id=payment_method_id)

     s = OrderSerializer(data=request.data)
     if s.is_valid():
         s.save(payment_method=payment_method)
     return JsonResponse({"data":request.data})

This works - and saves the payment method relationship, but I need to return a valid JSON API response, which the above is not.

There has to be an easier way for me to save the payment method relationship?

Any help much appreciated!




lundi 13 mai 2019

What does `take` mean in Ember.js template

I've got this each loop in an ember template. What does the take argument do here?








Ember JS: Passing parameters to Model.save() for custom API

I'm working on an Ember.js application using Ember Data on a somewhat unusual JSON API.

To query an item from that API the URL looks like /singleitem?collection_id=1&item_id=2 To fetch the data I'm using this model hook:

import Route from '@ember/routing/route';
export default Route.extend({
    model(params) {
        return this.store.query('singleitem', {item:params.item_id, collection:params.collection_id});
    }
});

In a component I show data from the API in an <input type="text"> field and when the user changes the content I want the component to update my model and write it back to my API:

import Component from '@ember/component';
export default Component.extend({
    async change() {
        this.test.set('title', 'Hello World!');
        await this.test.save();
    }
});

This code sends a PATCH request to /singleitem/2 where 2 is the 'id' property from the response of the JSON API item.

How can I pass parameters to save() so that the PATCH request is sent to /singleitem?collection_id=1&item_id=2 – just like I've been able to do in this.store.query?




Why is app folder needed inside an in-repo engine?

In ember engines, if we generate a route/component/ using ember CLI, entry for generated one will be done in addon folder and app folder under lib/ folder. Why is the content inside the app folder needed or is it just the ember-cli creates it as if it is an in-repo addon? I have removed the app folder inside the engine and it works just fine for me.




Cant we put a ember concurrency task in glimmer component getter, which is tracking the components arguments

-- when an ember concurrency task is called glimmer components getter then it runs in infinite loop.

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';

export default class UserTableComponent extends Component {
  @service store;
  @tracked users;

  get taskStatus() {
    let params = {
      'account_id':this.args.account,
      'page':this.args.page
    }
    this.getUsersTask.perform(params);

  }


  @task(function*(params) {
      let recordsWithMeta = yield this.store.query('user', params);
      this.users= recordsWithMeta.toArray();
    }) getUsersTask;

}


<UserTable 
  @account=
  @page=
  >          
</UserTable>

Note: it runs in infinite loop.




dimanche 12 mai 2019

How to add INSPINIA bootstrap to Ember application

New user to 3rd party bootstrap templates for Ember and need help.

I purchased the INSPINIA admin template from www.wrapbootstrap.com. The download comes with multiple pre-created projects with INSPINIA built in (e.g., Angular, Rails, etc.) but not for Ember. I reached out to the creator to see if they could include a project for Ember and they said no.

So, I am curious, does anyone know how to add INSPINIA to an Ember web application? Is it as simple as ember install bootstrap and then copy the *.css file? Note: the INSPINIA template comes with way more files than just a *.css, and I am using ASP.NET CORE 2.2 for the web API.

Any help is appreciated.




Remove event listeners when element gets deleted

I have a project where im using a plugin that produces something like the picture below:

enter image description here

In a div element, it spins so it has event listeners which are declared in the plugin like this...

window.addEventListener('resize', resizeHandler);

The plugin is abit long so i will link the full file here: https://pastebin.com/6e7HLDV3

I then call the library like this:

new skillsCloud(this.$()[0], this.get('entries'));

Where entries is just an array of objects for each text item.

What i want to be able to do is delete this element and it will leave no trails and properly dispose of all the event listeners.

How would I even get a chance to run the code that will remove the listeners if its about to be destroyed?

Is it worth making a function called dispose where I do it and then call before i delete the element?

Any help is appriciated




How can I create a Filter/Search dropdown list attribute in Ember?

I am new to Ember. Would like to understand as to how can I implement a Search/Filter dropdown in Ember like one below in JS.

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    <a href="#about">About</a>
    <a href="#base">Base</a>
    <a href="#blog">Blog</a>
    <a href="#contact">Contact</a>
    <a href="#custom">Custom</a>
    <a href="#support">Support</a>
    <a href="#tools">Tools</a>
</div>

And JS would look like this

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i < a.length; i++) {
      txtValue = a[i].textContent || a[i].innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
         a[i].style.display = "";
      }
      else {
         a[i].style.display = "none";
      }
  }
}




Trigger a computed property when element is inserted

i have an ember project with a service that gets the correct font size for an element based on its width. For responsive scaling.

Here is my code.

Element:

screenSizeService: service('screen-size'),
utilsService:      service('utils'),

portrait:  computed.readOnly('screenSizeService.portrait'),
landscape: computed.readOnly('screenSizeService.landscape'),

style: computed('screenSizeService.{width,height}', 'landscape', 'portrait', function()
{
    console.log('calculating');
    //Since the properties have to be consumed, get their values
    this.get('screenSizeService.width');
    this.get('screenSizeService.height');

    //Params = scale if it's landscape, scale if it's portrait, min font size, max and the parent to watch the width of
    return this.getFontSize(1.2, 1.2, 30, 60, this.$();
}),

getFontSize(landscapeScale, portraitScale, min, max, parent)
{
    const scale = (this.get('landscape')) ? landscapeScale : portraitScale;
    const fontSize = this.get('utilsService').scaleFontSize(parent, scale, min, max);
    return htmlSafe('font-size: ' + fontSize + 'px');
}

So this listens to the resize event and calculates every time it changes. This works really well except for when it initally loads.

On the initial load, The parent that im passing through doesnt have a width therfore cannot calculate its font size until the page is resized.

Here is my screen size service:

init()
{
    this._super(...arguments);
    this.get('resizeService').on('resize', this, this.screenSizeChange);
    this.screenSizeChange();
},

willDestroyElement()
{
    this._super(...arguments);
    this.get('resizeService').off('resize', this, this.screenSizeChange);
},

screenSizeChange()
{
    const width  = window.innerWidth;
    const height = window.innerHeight;

    this.set('width',  width);
    this.set('height', height);

    if (width >= height && !this.get('landscape'))
    {
        this.set('landscape', true);
        this.set('portrait',  false);
    }

    if (height > width && !this.get('portrait'))
    {
        this.set('landscape', false);
        this.set('portrait',  true);
    }
}

Lastly, My utils function that calculates the font size:

scaleFontSize(parent, scale, min, max)
{
    const parentWidth = (parent && parent.width()) ? parent.width() : null;
    if (!parentWidth) {return;}

    scale = scale || 1;
    min   = min   || 1;
    max   = max   || 1000;

    return Math.max(Math.min(parentWidth / (scale * 10), parseFloat(max)), parseFloat(min));
}

Would anyone know a possible way around this so it calculates on didInsertElement?

I have tried setting the style on didInsertElement, but then it doesnt change on resize. I think because im setting it twice.

Any help is appriciated




vendredi 10 mai 2019

Adding or appending object with object javascript

i am having 2 objects and the code is

Object 1

var existingValue=self.get('objHubDto').ftd.gridDataDTO.gridDTOMap[name].gridDataMap;

Object 2

var newValue =  self.get('childDataList')

I need to merge/add/append this two in newvalue value eventhough it having duplicate key values




Use electron in ember project

I am new to electron development. Is there any way to develop an electron project in ember without using ember-electron add-on. If possible how to use require keyword in the ember project?




jeudi 9 mai 2019

How to uses customelements.define in ember js

I need to the emberjs example program using customelements.define. I want to replace registryElement instead of customelements.define




How to pass/hide signed_id to Rails API controller when updating a model

I'm using Rails 5.2 API with Ember JS ember-active-storage add-on and would like to know how it is possible to update a model with an existing attached image without attaching a new one? It seems like Rails ActiveStorage needs to get the blob signed_id in a hidden input field to be able to process the request correctly in case of direct uploads. For example, if I try to update the model that has a photo, photo attribute being the photo URL, Rails will raise the error:

ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignature)

as there is no siged_id provided in the request params.

Any ideas? Or am I missing something? Thank you.




How to force ember.js to fully load all routes before it renders the index route?

I've recently created my first web app with ember.js. When I move between routes, they take too long to load which creates some ugly and not very app-like effects.

Unfortunately I am still very new to ember.js and therefore I'm unsure of which keywords to look and search for.

Feel free to check out this project at http://elephants.surge.sh/home.

Is there a method to load all routes, nested routes, templates, and components at once, while showing a loading template and before rending the index route?




Alternate code for document.registerElement in chrome

Hi I need the alternate code for document.registerElement. Because by this june month it is going to remove by Chrome. Can anybody please provide me the alternate code for the above.




mercredi 8 mai 2019

How can I model an object that has a plain array of strings with ember data?

How can I model an object that has a plain array of strings? If I do the following it shows me the emails but when modifying their value they are not updated.

The server sends/receives the following data:

"data":
[
    {
        "attributes" : {
            "id":1,
            "name":"Jhon",
            "emails":["jhon@gmail.com","jhon@other.com"]},
            "relationships": (,..}
        }
    }

    ...

Model:

export default Model.extend({
  id: attr('string'),
  name: attr('string'),
  emails: attr('boolean')
})

Template:


    <input type="text" value=>





mardi 7 mai 2019

emberjs: how to get id and update the model data

I have two components items and item-list.

my item route is:

this.route('items', function() {
  this.route('items', { path: '/:item_id' });
});

In my Items list when clicked to one of the items it takes to those items with a specific team_id.


  <div class="items-list" >
     
  </div>


In my Item component, I wrote a task which will run every minute to get the data of that item.

I am new to emberjs, I don't know how to update the model data. I am trying to get the data using store.findAll() will this update the model data and how to get the id of the current item to pass it in store.findAll()

  didInsertElement() {
    this._super(...arguments);

    this._startPolling();
  },

  _startPolling() {
    this.__poll_id = this.poll.addPoll({
      interval: 1000 * 60,
      callback: this.updateTask.bind(this)
    });
  },

  updateTask() {
    this._updateItem.perform();
  },

  _updateItem: task(function* updateItem() {
     /* how to pass current item id and will this update the model*/
    let data = yield this.store.findAll(`/items/:id`);
  }).restartable(),

  willDestroyElement() {
    this._super(...arguments);

    this.poll.clearPoll(this.__poll_id);
  }




When packaging an SPA (and no Java code) into a WAR, how to serve the index.html for every URL except for those that match actual asset files?

I have a single-page webapplication, that when built must be installable into a java-ee application server, such as Glassfish. That is, I should package it into a WAR.

This single-page webapplication is strongly separated from its backend application, it should be buildable and deployable by itself. That is, the WAR only should and will include the single-page webapplication.

If possible, I would like to solve this without having any Java code.

In the case of a single-page application, the URL routing should function like this:

  1. If the requested URL matches a static asset file (html, js, css, etc.), then that file should be served.

  2. In any other case the index.html should be served.

When the second point does not apply, the application (by default) can only be accessed at its entry point (index.html). And not with URLs pointing directly to any subroutes.

There is a workaround, since In Ember.js it is possible to set an option to use hash based subroute URLs. But this has its limiting drawbacks, and I'd like to entirely avoid.

The solution I currently have however is working only by switching on said workaround. I'm using maven and the maven-assembly-plugin to achieve this.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>My App</name>
  <build>
    <finalName>finalName</finalName>
    <plugins>
      <plugin>
        <!-- assemble static content -->
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptors>
            <descriptor>static.xml</descriptor>
          </descriptors>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

static.xml

(dist is the directory where ember-cli puts the compiled assets, that I need to include.)

<?xml version="1.0" encoding="UTF-8"?>
<assembly>
  <id>static</id>
  <formats>
    <format>war</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <fileSets>
    <fileSet>
      <directory>dist</directory>
      <includes>
        <include>**</include>
      </includes>
      <excludes>
        <exclude>WEB-INF/*</exclude>
      </excludes>
      <outputDirectory>/</outputDirectory>
    </fileSet>
    <fileSet>
      <directory>WEB-INF</directory>
      <includes>
        <include>**</include>
      </includes>
      <outputDirectory>/WEB-INF</outputDirectory>
    </fileSet>
  </fileSets>
</assembly>

I also have a web.xml inside the WEB-INF folder, but this is essentially empty.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

</web-app>

So to summarize the question: Is it possible to have said routing logic without writing any Java code, that is without any "gluing" or "middleman" server side module?




Fetch is undefined on IE11 when authenticating with cognito

I have an ember app where I log on and it authenticates me using ember-cognito and ember-simple-auth.

this.get('sessionService').authenticate('authenticator:cognito', credentials).then(() => {
         console.log('authenticated');
    }).catch(( reason ) => {

        console.log(reason);
    });

This works on every browser except ie which i get the error 'fetch is not defined'.

This appears in the catch section which means cognito is trying to use fetch.

I have been looking into this but cant find a solution for my scenario.




dimanche 5 mai 2019

In-repo addon writing public files on build causes endless build loop on serve

I'm having difficulty with my in-repo addon writing to appDir/public. What I'd like to do is write out a JSON file on each build to be included in the app /dist. The problem I'm running into is when running "ember serve", the file watcher detects the new file and rebuilds again, causing an endless loop.

I've tried writing the JSON file using preBuild() and postBuild() hooks, saving to /public, but after build, the watcher detects it and rebuild over and over, writing a new file again each time. I also tried using my-addon/public folder and writing to that, same thing.

The only thing that partially works is writing on init(), which is fine, except I don't see the changes using ember serve.

I did try using the treeForPublic() method, but did not get any further. I can write the file and use treeForPublic(). This only runs once though, on initial build. It partially solves my problem, because I get the files into app dist folder. But I don't think ember serve will re-run treeForPublic on subsequent file change in the app.

Is there a way to ignore specific files from file watch? Yet still allow files to include into the build? Maybe there's an exclude watch property in ember-cli-build?

Here's my treeForPublic() , but I'm guessing my problems aren't here:

treeForPublic: function() {
    const publicTree = this._super.treeForPublic.apply(this, arguments);
    const trees = [];
    if (publicTree) {
        trees.push(publicTree);
    }
    // this writes out the json
    this.saveSettingsFile(this.pubSettingsFile, this.settings);
    trees.push(new Funnel(this.addonPubDataPath, {
        include: [this.pubSettingsFileName],
        destDir: '/data'
    }));

    return mergeTrees(trees);
},




vendredi 3 mai 2019

Using process.env vars in Ember

This may be a dumb question, but how to get access to process.env vars inside of my ember app? I tried to access process.env in one of my controllers, but I received an error that process was not defined.




Why isn't Corber building an apk for my Ember project?

I want to turn an existing Ember project into a mobile app, so I decided to learn Corber, which links Ember and Cordova to (theoretically) make the webapp -> mobile transition easy. However the steps from Corber's docs give me the error 'No apk found'

I created an empty Ember project using 'ember new test-corber' then ran 'corber init' and chose android when asked what platforms to init with. I then changed the two environment variables that the Corber guides specify for Ember setup (and nothing else) and ran 'corber start'. At this point I always get the message "No apk found" and the process ends. The apk is supposed to be put in test-corber/corber/cordova/platforms/android/outputs/apk/debug/ but there isn't even an outputs/ folder.

I'm on Ubuntu 16.04, java 1.8.0_191, corber 1.3.10, gradle 5.4.1, node 6.16.0, and ember 2.18.2 (though I also tried it on 3.9.0)

I've tried selecting different emulators, reinstalling Gradle, creating a new project, and searching online for solutions to no avail. I'm open to any ideas or suggestions.




Empty req.body with ember, express, postgresql app

When making a post request in ember, the request body in the server is having an empty object.

I tried switching from jsonapi in ember to restapi but it did not work. What is getting stored is NULL since title in the pool query is undefined.

Server:

const JSONAPISerializer = require('jsonapi-serializer').Serializer;
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
const cors = require('cors');
const { Pool } = require('pg')
const bodyParser = require('body-parser');

const app = express();
const pool = new Pool({
    user: "zumo",
    host: 'localhost',
    database: 'app',
    password: 'password',
    port: 5432
})

const port = process.env.PORT || 3000
var bookSerializer = new JSONAPISerializer('books', {
    attributes: ['id', 'title']
});

app.use(express.json())
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.get('/books', (req, res) => {
   pool.query('SELECT * FROM books', (error, results) => {
       if(error) {
         throw new Error(error);
       }
       let books = bookSerializer.serialize(results.rows);
       res.status(200).json(books);
   })
})

app.post('/books', (req, res) => {

    try {
        let { title } = req.body;
        console.log(title)
        pool.query(`INSERT INTO books (title) VALUES ($1)`,[title] , (error, result) => {
            if(error) {
              console.log(error);
            }
            let book = bookSerializer.serialize(result.rows);
            res.status(201).send({book});
        })
    }
    catch(e) {
        console.log(e);
    } 
})

app.listen(port, () => {
    console.log('Server up on port: ', port);
})

I am using json-api serializer in ember.




jeudi 2 mai 2019

getting error while setting a global variable during recurssion in ember.js

so i have implemented a timer in my ember code, which works fine, but while running test it fails i get this error saying

Uncaught Error: Assertion Failed: calling set on destroyed object: <front@component:qwtery/my-comp::ember629>.timer = 9

note that this happens only when i run the tests

and here is my code

didReceiveAttrs(){
    this._super(...arguments);
    this.set('timerStop', false);
    this.set('anotherTimer', 0);
    this.set('timer', null);
    var timeLimit = this.get('question.time_limit');
    if(timeLimit > 0)
    {
      this.set('timerEnabled', true);
      this.timerFunc(timeLimit,0);
    }
  },

timerFunc: function(count, val) {
    if (count >= 0 && !this.get('timerStop')) {
      this.set('timer', count);
      this.set('anothertimer', val);

      var a = setTimeout(() => {
        return this.timerFunc(count-1, val+1);
      }, 1000)
    }
    else {
      code to show message that timer has stopped
    }
  }

So if this is not the right way to implement a timer, why do i get the message "calling set on destroyed object:" only while running the test and not while i try it out manually




Getting an infinite loop from set function in ember.js

I am trying to display a div with the class loader only while a PDF page is loading.

It works, but somehow the function this.displayPage(pdf,1) is getting looped over.

After renderPage(page) is called, it goes back to didRender() > this.displayPage(pdf,1).

This only happens when I use set(this, 'pageIsRendering', false/true) so I'm thinking my problem might have to do with this.

I tried debugging my code but I don't understand what's creating the loop.

I am using PDFJS library to display the PDF document.

Here is my component.js code

  pageisRendered: true,
  pageIsRendering: false,

  didRender() {
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';
    set(this, 'setPageValueInput', document.querySelector('.set-page-value'));
    let pdfDoc = pdfjsLib.getDocument(this.url).then(pdf => {
      this.displayPage(pdf, 1);
      this.shownPdf = pdf;
      document.querySelector('.total-page-number').value = this.shownPdf.numPages;
    });
  },

  displayPage(pdf, num) {
    set(this, 'pageIsRendering', true);
    pdf.getPage(num).then(page => {
      if (this.pageisRendered) {
        this.pageisRendered = false;
        this.renderPage(page);
      }
    });
  },

  renderPage(page) {
    let scale = this.pdfScale; // render with global pdfScale variable
    let canvas = document.querySelector('.pdf-canvas');
    let context = canvas.getContext('2d');
    let viewport = page.getViewport(scale);
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    let renderContext = {
      canvasContext: context,
      viewport
    };
    page.render(renderContext).then(() => {
      this.pageisRendered = true;
      set(this, 'pageIsRendering', false);
    });
  },

Here is my html code

<div class="pdf-container ">
    <div class="canvas-container">
        
          <div class="loader">
            
          </div>
        
    </div>
</div>




mercredi 1 mai 2019

unable to get included(has_many) part in ember-cli-mirage

So in my code i am trying to fetch a author and its related books

this is my server response

data:{
attributes:{name: "joseph"}
type:"Author"
id:"1"
relationships: {books: {data: [{id: "1", type: "books"}, {id: "2", type: "books"}]}}
}
included:
[
{id: "1", type: "books", attributes: {title: "catch22"}},
{id: "2", type: "books", attributes: {title: "catch23"}}
]


and this is my serializer

import { JSONAPISerializer } from 'ember-cli-mirage';

import { underscore } from '@ember/string';



export default JSONAPISerializer.extend({


 alwaysIncludeLinkageData: true,

 keyForAttribute: function(attr) {

   return underscore(attr);

 },

 keyForRelationship: function(rawKey) {
   return underscore(rawKey);

 }

});

so in my code i m usinf queryRecord to fetch the author infomation

so in my mirage/config.js i have tried this

this.get('/authors', () => {
    some logic i need to implement here 
    var author = server.db.authors.find(1)
    // debugger
    var included = []
    var book_array = []
    var included_array = []
    if(author.bookIds != null){
      author.bookIds.forEach((book) => {
        var book = server.db.books.find(book)
        book_array.push({id: book.id, type: "books"})
        included_array.push({id: book.id, type: "books", attributes: book})

      })
      included =  included_array
    }

    return {data: {type: 'authors', id: author.id, attributes: author, relationships: {books:book}}, included:  included_array };
});


but i am only getting the author details, and i m not getting the book details

if i try something like this.get('author.books.length') in my code, i get 0, i am not sure what else needs to be done to get the hasMany part

Can any one tell me how to get the has many part

Thanks




Self reference when storing new object

We have a Ruby on Rails backend server and an EmberJS frontend.

We create a new object in Ember that is part of a tree structure (having a parent, children, etc.). We would like to return all the objects in the tree structure as part of the reply from the backend server; eg. when we create a new object we will return self + ancestors. This is where the problem arises. The reply from the server returns an ID for the new object and the same ID is referenced in the self + ancestors data. This results in Ember/Ember data rejecting the data since the ID is already referenced in the data store; eg:

Error: Assertion Failed: 'node' was saved to the server, but the response returned the new id '9f06c18e-0507-41d2-a8af-c330fa896bac', which has already been used with another record.

Is there any way to setup the model so the above is possible? Eg. Ember/Ember data won't reject the new object due to it already being referenced in the reply?




Django Rest Framework JSONAPI and sideloaded/included resources

I am using the Django Rest Framwork JSON API for my Ember back end.

The (data) response I am getting back includes the "relationship" key but I need to sideload resources for a particular model, and hence want to include the "included" key as shown on the Ember docs https://guides.emberjs.com/release/models/relationships

I have a Product model with a FK relationship to a Tax model.

Here is my tax serializer:

from rest_framework_json_api import serializers
from .models import Tax

class TaxSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tax
        fields = ('id', 'name', 'amount')

Here is my product serializer:

from rest_framework_json_api import serializers
from .models import Product
from tax.serializers import TaxSerializer

included_serializers = {
    'tax': TaxSerializer
}

class Meta:
    model = Product
    fields = ('id', 'name', 'image', 'price','tax')

class JSONAPIMeta:
    included_resources = ['tax']

For this I've followed the example from https://www.mattlayman.com/blog/2017/sideload-json-api-django/

However, my response still includes the "relationships" key, and not the "included" key eg

"data" : [
   {
     "type":"products",
     "id": "1",
     "attributes": {...omitted for brevity ...
     },
   "relationships": {
      "tax": {
         "data": {
             "type":"tax",
             "id":"1"
          }
       }
    }
  },
  {...etc....}
]