samedi 30 mars 2019

Error - Search filter todo - Emberjs v3.4

import Controller from "@ember/controller";
import { computed } from "@ember/object";
export default Controller.extend({
  filter: "",
  filterTodos: function() {
    var filter = this.get("filter");
    var rx = new RegExp(filter, "gi");
    var todos = this.model;

    return todos.filter(function(todo) {
      return todo.get("title").match(rx) || todo.get("body").match(rx);
    });
  }.property("arrangedContent", "filter"),
  sortedProperties: ["date:asc"],
  sortedTodos: computed.sort("model", "sortedProperties")
});


error Don't use Ember's function prototype extensions ember/no-function-prototype-extensions

error Only string, number, symbol, boolean, null, undefined, and function are allowed as default properties ember/avoid-leaking-state-in-ember-objects




vendredi 29 mars 2019

Ember.js and image uploading

I'm having trouble with uploading images in Ember.js

I have a form to create a user :

<div class="container">
<form onsubmit= enctype="multipart/form-data">
  <div class="form-group">
    <label for="firstName">First name: </label>
    
  </div>
  <div class="form-group">
    <label for="lastName">Last name: </label>
    
  </div>
  <div class="form-group">
    <label for="age">Age: </label>
    
  </div>
  <div class="form-group">
    <label for="job">Job: </label> 
    
  </div>
  <div class="form-group">
    <label for="image">Picture: </label> 
    
  </div>
  <button type="submit" class="btn btn-info">Create</button>
</form>

I know I should encode images in base64 but I have no idea how to do that since I've never done it before.

And in the view, this is how I'm trying to get the image (I know this is not what I should do but I don't know how to do it) :

<div class="container">

<h1> </h1>
<p>Age:  years old</p>
<p>Job: </p>
<img src="" alt="img" id="image">

Any ideas, suggestions, help please ?




action inside li tag does not triggered sometimes in Ember js

I have multiple tabs in my page which link to some internal routes. When an user clicks on a tab ,the route has to be rendered and also the tab has to be highlighted but once in a few clicks the highlighting does not shift to the new tab and the old tab remains highlighted but the route of the clicked tab gets rendered.

The highlighting is done by an action inside the li tag and the #link-to is nested inside the li tag.

In my investigation till now what I have found is that the when this happens the click event is not registered. I get a bunch of mouse events but no click event. Seems like the click event is eaten up.

<ul class="nav nav-tabs">
 
   <li ></li>
 
</ul>

The action should be triggered all times when a tab is click and the new tab should be highlighted.




jeudi 28 mars 2019

Fixing Ember Load Initializers when converting to typescript

Utilizing the ember quick start tutorial trying to convert from js to typescript. Changing the .js files to .ts files throws and error for the 'ember-load-initializers' import. The application will not run without this error being resolved.

I've tried the suggestions list in this answer: Can't find module on migrating ember-cli app to TypeScript

but was unsuccessful.




Ember build issue: "Cannot use the decorators and decorators-legacy plugin together"

I have recently encountered an issue with building my ember project with bitbucket pipelines:

+ ember build --environment="production"
Could not start watchman
Visit https://ember-cli.com/user-guide/#watchman for more info.
Building
Environment: production
cleaning up
cleaning up...
Build Error (broccoli-persistent-filter:Babel > [Babel: ember-data]) in ember-data/adapters/json-api.js
Cannot use the decorators and decorators-legacy plugin together

I am currently using ember-cli version 3.8.1.

The issue occurs with all build environments, not just production. What baffles me is that no new npm package or ember addon was added between last successful build and the ones that have been failing since - and now if I re-run the successful build, that will also fail.

I have gone back in the commit history to a commit that worked, then fast-forward into the present step-by-step - always deleting the node_modules and reinstalling the packages. It always works locally, but it will always fail when the pipeline is run.

I have also tried updating my docker image.

I have already gone through and tried the solutions listed here - but it seems like they have already been addressed in version 3.8.1.

Also, if it is any help, this is my bitbucket-pipelines.yml:

pipelines:
  branches:
    master:
      - step:
         name: Building Ember Project
         script:
          - npm install
          - npm install firebase-tools
          - ember build --environment="production"
      - step:
         trigger: manual
         deployment: production
         name: Deploy to Production
         script:
          - firebase use prod
          - firebase deploy --non-interactive --token ${FIREBASE_TOKEN}

Thank you all in advance!




How to access a JSON file in my controller

In my Ember app, I have a JSON file filled with data in my public directory (I.E. public/data/articles.json.

I have an article route where I would like to load in this data and display it in the front-end. How could I do this successfully? I am willing to use the model hook, however I don't know of a solution off-hand.

I currently have the following code in my controller. However, this doesn't work (most likely because the data is loaded in after it is rendered).

import Controller from '@ember/controller';
import $ from 'jquery';

export default Controller.extend({
  init() {
    this._super(...arguments);
    $.getJSON("/data/articles.json", function (data) {
      console.log("test");
      console.log(data);
      this.articleData = data;
  }
})




Include nested models but accessing to Proxy objects

Im working in Ember 3.1 and JSON:API format to get data from backend.

My models are something like follow:

// Continent model
export default DS.Model.extend({
  name: attr('string'),
  countries: hasMany('countries'),
});

// Country model
export default DS.Model.extend({
  name: attr('string'),
  president: belongsTo('president'),
  regions: hasMany('region')
});

// President model
export default DS.Model.extend({
  name: attr('string')
});

// Region model
export default DS.Model.extend({
  name: attr('string')
});

The way a fetch my models are:

fetchInformation: task(function* () {
    yield get(this, 'store')
      .findRecord('continent', continent,
        {
          include: 'countries,'
          + 'countries.president,'
          + 'countries.regions'
        }
      ).then((continent) => {
        get(continent, 'countries.firstObject') // This one gets resolved properly
        get(continent, 'countries.firstObject.president') // Get Proxy object
        get(continent, 'countries.firstObject.regions.firstObject') // Get Proxy object
      })

I thought that by using 'include' and the server replying as JSON:API specs, I would have access to all those properties.

To me it seems that those nested relationships needs to get resolved somehow.

What am I missing? Is there any way to work easily with nested models?




mercredi 27 mars 2019

Is there a way to define and iterate over an array in ember handlebars templates?

I'm working on a styleguide and need to iterate over an array in a handlebars template.

I know that you can iterate over objects or other variables when passed into a template, but is there a way to iterate over a collection defined in the template? I think this breaks the "no-logic in views" concept that handlebars pushes, but I imagine this is a common use case.


  <div class='banners-container'>
    <div class='content'>
      <div class='banner banner- has-icon has-dismiss'>
        <p>Banner </p>
      </div>
    </div>
  </div>



I would expect this to output 4 collections of the banners-container elements, but it's not outputting anything.

What's the best way to handle this use case?




EmberJs outlet inside multiple nested route

I do not strictly understand outlets and rendering templates in EmberJS. Until now I have been doing mostly CRUD operations or my routes weren't nested as many times as here so I haven't faced this problem yet. Using in parent route was enough.

The problem comes with my approach that I used to. Everything works fine when I do visit routes admin/*, but when I try to get into e.g. admin/organization/{id}/user it renders an admin/organization template what I would want to avoid. I suppose these things can be done using renderTemplate() function inside route.js but I can't figure these things out.

I recreated my routes structure in twiddle below: https://ember-twiddle.com/5c4ef7ba1225ac3e85ac2d457af7ff48

Could someone explain me that, please?




Ember-paper and class?

I'm working on a project made with Ember.js I'm using ember-paper for buttons and also Ember-intl to translate my application (english and french). I have a basic HTML button with this code :

<button class= ></button>

But when I use ember-paper with this kind of code :

Test

I can't find a way to add my if statement and the action.

 >

Do you know how to do that ?

Thanks for your help !




Implementing a Database - Cannot read property 'initializedRelationships' of undefined

I was facing a problem when I was implementing a database "Error while processing route" and I solved it but I got new error - Cannot read property 'initializedRelationships' of undefined

here was my program Implementing a Database - Error while processing route - https://i.stack.imgur.com/hlNkq.png




Docker + EmberCLI + Windows = Not working

System overview

I am developing applications in Ember and I am not able to update the CLI to the most current version due to older applications are still in development (version 2.15). But I want to try to refactor some parts to ember 3.8.

Since I need a 3.8 ember CLI for this I tried to use a docker container for it so, that I can leave the working CLI on my system (v2.15) untouched.

I am using Docker Desktop CE V2.0.0.3 (31259) with Docker Engine 18.09.2. The package is: "danlynn/ember-cli:3.8.1". I am doing everything in a PowerShell with elevated rights. (The linux containers are run in a Moby image in Hyper-V)

On my system is no other container running during these tests/problem solvings:

PS C:\docker_ember> docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
PS C:\docker_ember>

What is working?

When I am running a container with a bash to be able to use the ember CLI, everything works fine - even "npm i" and "ember build":

PS C:\docker_ember> docker run --rm -ti -v ${PWD}:/myapp -p 4200:4200 -p 7020:7020 -p 7357:7357 danlynn/ember-cli:3.8.1 bash


root@a39fe0269e04:/myapp# npm i
npm WARN rollback Rolling back npm-bundled@1.0.5 failed (this is probably harmless): ENOTEMPTY: directory not empty, rmdir '/myapp/node_modules/fsevents/node_modules/npm-bundled'
npm WARN rollback Rolling back os-homedir@1.0.2 failed (this is probably harmless): ENOTEMPTY: directory not empty, rmdir '/myapp/node_modules/fsevents/node_modules/os-homedir'
...
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.7 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.7: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

audited 64805 packages in 61.406s
found 1 low severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details


root@a39fe0269e04:/myapp# ember build
Environment: development

ember38/templates/index.hbs
  2:4  error  Incorrect indentation for `<div>` beginning at L2:C4. Expected `<div>` to be at an indentation of 2 but was found at 4.  block-indentation
  3:8  error  Incorrect indentation for `` beginning at L3:C8. Expected `` to be at an indentation of 6 but was found at 8.  block-indentation

===== 1 Template Linting Error

cleaning up...
Built project successfully. Stored in "dist/".


root@a39fe0269e04:/myapp#

What is not working?

But the problem is, and I am not able to find the reason for it: "ember server"/"ember s" will not work. After some starting time the console just sais:

Port 4200 is already in use.

But it is not. I have checked every port on windows and in the container - its free. I even changed the port in the .ember-cli config file to other port without even leaving the container (I tried >10) - all are "in use".

I tried other variants of the docker command - even one without any port exposing:

docker run --rm -ti -v ${PWD}:/myapp -p 4200:4200 -p 7020:7020 -p 7357:7357 danlynn/ember-cli:3.8.1 bash

docker run --rm -ti -v ${PWD}:/myapp -p 4200:4200 -p 7020:7020 -p 7357:7357 --add-host=localhost:172.18.80.177 danlynn/ember-cli:3.8.1 bash

docker run --rm -ti -v ${PWD}:/myapp --network="host" danlynn/ember-cli:3.8.1 bash

docker run --rm -ti -v ${PWD}:/myapp --net=host --pid=host --privileged danlynn/ember-cli:3.8.1 bash

docker run --rm -ti -v ${PWD}:/myapp -p 4200 -p 7020 -p 7357 danlynn/ember-cli:3.8.1 bash

# This one replaces the bash with a real ember CLI command.
docker run --rm -ti -v ${PWD}:/myapp -p 4200:4200 -p 7020:7020 -p 7357:7357 danlynn/ember-cli:3.8.1 ember s

So I tried some other container, that opens ports - NGINX:

PS C:\docker_ember> docker run --rm -ti -p 80:80 nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
27833a3ba0a5: Pull complete
e83729dd399a: Pull complete
ebc6a67df66d: Pull complete
Digest: sha256:dff6326b09c76bef1425ee64c2e218b38737cdb5412b8ccf84ca70740bfa1db2
Status: Downloaded newer image for nginx:latest
172.17.0.1 - - [27/Mar/2019:07:46:05 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36" "-"
2019/03/27 07:46:06 [error] 8#8: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "localhost", referrer: "http://localhost/"
172.17.0.1 - - [27/Mar/2019:07:46:06 +0000] "GET /favicon.ico HTTP/1.1" 404 556 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36" "-"
^C

PS C:\docker_ember>

It's just working flawlessly.

What have I tried to solve this problem?

  1. I resetted docker desktop to factory defaults. (this will even delete every image)
  2. I uninstalled the whole docker for windows software (that even deleted the moby image) - and reinstalled it, freshly downloaded from the docker hub.
  3. I deleted every hyper-v network adapter before reinstalling the docker desktop CE software.
  4. I tried to use a "pure" node 8 docker container and installed ember-cli@3.8.1 manually in it - but same result.
  5. I restarted windows many times.
  6. I resetted the whole windows network with using "netcfg -d". (that even removed every saved wifi key, etc.)

I am just out of options, since the port is not in use - change it and it is magically already in use AGAIN. The docker containers are able to open ports and use them: NGINX works flawlessly. I guess, there is some other reason preventing nodeJS ports from getting opened.

Any tips?




mardi 26 mars 2019

Export ember project dependency licenses

I have a requirement for being able to export a list of dependency open source licenses of my Ember project's non-development dependencies.

We have some Node apps and I've been able to use license-checker, and that will output a a list for the Ember app as well.

The problem is that it doesn't seem to be possible to separate out the dev vs. non-dev dependencies (because ember-cli installs all dependencies in devDependencies). This means my export contains tons of build dependencies that we never actually ship.

I've looked at ember-cli-license which hasn't been updated in years and ember-cli-json-license which works but has the same problem.




Why I;m getting error when implementing my database

here is the adapter In Ember Data, an Adapter determines how data is persisted to a backend data store. Things such as the backend host, URL format and headers used to talk to a REST API can all be configured in an adapter.

/* adapters/application.js */

import FirebaseAdapter from "emberfire/adapters/firebase";
export default FirebaseAdapter.extend({});

A Controller is routable object which receives a single property from the Route .. here is the controller

/* controllers/cars.js */

import Controller from "@ember/controller";
export default Controller.extend({
  actions: {
deleteCar(id) {
  this.get("store")
    .findRecord("car", id, { reload: true })
    .then(car => {
      car.destroyRecord();
      car.save();
      //self.transitionToRoute("cars");
    });
   }
   }
  });

/* controllers/cars/edit.js */

import Controller from "@ember/controller";
export default Controller.extend({
actions: {
  editCar: function(id) {
  var self = this;

  var make = this.get("model.make");
  var model = this.get("model.model");
  var year = this.get("model.year");

  this.store.findRecord("car", id).then(function(car) {
    car.set("make", make);
    car.set("model", model);
    car.set("year", year);
    car.save();
    self.transitionToRoute("cars");
    });
    }
    }
    });

   /* controllers/cars/new.js */

   import Controller from "@ember/controller";
   export default Controller.extend({
   actions: {
     addCar: function() {
      var self = this;
      var rand = Math.floor(Math.random() * 10000 + 1);
      var newCar = this.store.createRecord("car", {
    id: rand,
    make: this.get("carMake"),
    model: this.get("carModel"),
    year: this.get("carYear")
    });
    newCar.save();
    self.transitionToRoute("cars");
   }
   }
   });

In Ember Data, models are objects that represent the underlying data that your application presents to the user. Note that Ember Data models are a different concept than the model method on Routes, although they share the same name .. here is the model

   /* models/cars.js */

   import DS from "ember-data";
   export default DS.Model.extend({
      make: DS.attr("string"),
      model: DS.attr("string"),
      year: DS.attr("string")
    });

In Ember, when we want to make a new page that can be visited using a URL, we need to generate a "route" using Ember CLI .. here is the routes

  /* routes/cars.js */

  import Route from "@ember/routing/route";
  export default Route.extend({
   model() {
      return this.store.findAll("car", {
      orderBy: "make"
     });
    }
   });

 /* routes/cars/edit.js */

 import Route from '@ember/routing/route';
   export default Route.extend({
   });

 /* routes/cars/new.js */

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

  export default Route.extend({
   model() {
       return this.store.findAll("car");
    }
    });

The EmberRouter class manages the application state and URLs .. here is the router

  /* router.js */

   import EmberRouter from "@ember/routing/router";
    import config from "./config/environment";

    const Router = EmberRouter.extend({
    location: config.locationType,
     rootURL: config.rootURL
    });

   Router.map(function() {
      this.route("cars", function() {
      this.route("new");
      this.route("edit", { path: "/edit/:car_id" });
    });
    this.route("users");
   });
   export default Router;




lundi 25 mars 2019

How to redirect an Ember page without rendering?

We have an Ember UI that we're porting to a Single Sign-on provider. This is behind a server-side feature flag such that, when the flag is on, the user is redirected to the SSO provider login portal and, when the flag is off, the user may still login through an Ember route.

I have this functioning with a call to a server endpoint in the Ember Service init() call. However, since this is an asynchronous call, the page continues rendering before the request returns, the results processed and the browser redirected. Thus, the user can briefly see the old login form before being redirected to the SSO portal. I would prefer that the user only see a blank browser window before the SSO portal is shown.

Is there a way to get the Service init() method to block on the results of a server call?

The application is structured somewhat oddly. The Login pages are actually a separate app, so I can hook anywhere in the application code without worrying about breaking the actual app. I have tried also hooking into the Application and only calling the Ember.Application.create() method from inside the server call promise resolution. However, it seems that loading the login page components at all triggers their render.




dimanche 24 mars 2019

Ember - Disable Prototype extension

Can anybody check the below link and help me to understand and resolve it. https://discuss.emberjs.com/t/disable-prototype-extension/16354




How to fix Uncaught TypeError: Cannot read property 'id' of null in node?

I am trying to create a web page application using node, ember and mongodb which is able to edit or to delete the existing songs on my database, the webpage is already able to display the songs and to add new ones. The problem occurs when I click on my "EDIT" link next to a song - it throws "Uncaught TypeError: Cannot read property 'id' of null" when it's supposed to fetch me a song by it's id.

Here's my app/routes.js code:

...
router.route('/songs/:song_id')
                            .put(function(req, res) { songs.updateSong(req, res, req.params.song_id) })
                            .delete(function(req, res) { songs.deleteSong(req, res, req.params.song_id) });
...

Here's my api/song.js code:

...
module.exports.updateSong = function(req, res, id) {
        Song.findByIdAndUpdate(id, {$set: req.body.song}, function(err, song) {
            if (err) {
                res.send(err);
            };
            res.json({song: song});
        });
};

module.exports.deleteSong = function(req, res, id) {
        Song.findByIdAndRemove(id, function(err, song) {
           if (err) {
                res.send(err);
           }
            res.json({song: song});
        });
};
...

Here's my app/router.js code:

...
Router.map(function() {
  this.route('song');
  this.route('about');
  this.route('new');
  this.route('edit', {
      path: ":song_id"
  });
});
...




samedi 23 mars 2019

How to ensure Ember is saving variable state on reload

I'm creating and saving a form using Ember but when I reload the page the toggle keeping track of whether the form has been submitted or not resets to false.

I have a page where the default text is 'You have no account linked'. I then have a button that when pressed displays a form for the user to fill out information . When they click submit and save their information, the form disappears and renders some text about their account. When I reload the page however the text renders to the default 'You have no account linked', and when I click the submit form button, their information is populated in the form fields. How can I ensure that when the page is reloaded the text about the user account is displayed?

This is the controller for the page

export default Controller.extend({
  isToggled: false,
  emailConnected: false,
  actions: {
    submitImap(mailbox, toggle, email) {
      this.get('ajax')
        .request(`/api/accounts/${this.session.account.id}/mailboxes/imap`, {
          method: 'POST',
          data: mailbox
        })
        .then(() => Utils.notify("IMAP settings saved.", 'success'))
        .catch(() => Utils.notify("Error saving IMAP account. Try again", 'error'));
        this.send('contract', toggle);
        this.send('expand', email);

    },
    disconnectIMAP(mailbox, property, email) {
      this.get('ajax')
        .request(`/api/accounts/${this.session.account.id}/mailboxes/imap`, {
          method: 'DELETE',
          data: {
            user_id: mailbox.user_id
          }
        }
      )
      .then(() => {
        this.set(property, { smtp: {}});
      })
      .then(() => Utils.notify("IMAP removed. ", 'success'))
      .catch(() => Utils.notify("Error removing IMAP account", 'error'));
      this.send('contract',email );
    },
    expand: function(toggle) {
      this.set(toggle, true)
    },
    contract: function(toggle) {
      this.set(toggle, false)
    }

This is the template handling the form submission

<h3>IMAP/SMTP</h3>
  

    
        <p> Edit your IMAP settings below </p>

    
        <p>
        You currently have IMAP account <strong></strong>
        connected for messaging.
      </p>
        <button    class = 'btn btn-danger'>Disconnect</button>


    

  
    <p>
      You currently do not have an account linked for messaging.
    </p>

  


  
    <form name='imap' class='modern-form full-width' >
      <div class='row'>
        <div class='col-sm-6'>
          <h4>IMAP</h4>
          <div class='form-group'>
            <label>
              Host
            </label>
            
          </div>
          <div class='form-group'>
            <label>
              Port
            </label>
            
          </div>
          <div class='form-check'>
            
            <label for='ssl'>
              SSL
            </label>
          </div>
          <div class='form-check'>
            
            <label>
              TLS
            </label>
          </div>
          <div class='form-group'>
            <label>
              Username
            </label>
            
          </div>
          <div class='form-group'>
            <label>
              Password
            </label>
            
          </div>
        </div>
        <div class='col-sm-6'>
          <h4>SMTP</h4>
          <div class='form-group'>
            <label>
              Host
            </label>
            
          </div>
          <div class='form-group'>
            <label>
              Port
            </label>
            
          </div>
          <div class='form-check'>
            
            <label for='ssl'>
              SSL
            </label>
          </div>
          <div class='form-check'>
            
            <label>
              TLS
            </label>
          </div>
          <div class='form-group'>
            <label>
              Username
            </label>
            
          </div>
          <div class='form-group'>
            <label>
              Password
            </label>
            
          </div>
        </div>
      </div>
      <button type="submit" class='btn btn-success'>
        Save
      </button>
      <button  class = 'btn btn-danger'>
        Cancel
      </button>
  </form>


  <button  class= 'btn btn-success'>
   Connect email
 </button>


Right now, if I submit the form the behavior is as expected, displaying the current username of the account, but on reload the emailConnected variable resets to false and the default of 'you have no account connected' is present and when I click the form the values are populated.




How to Handle 503 Response from Server in Ember Application?

Getting a 503 Response from in ember application. How to debug as a UI Developer? What UI Developer can Handle these kind of response.




jeudi 21 mars 2019

Ember.js - Acceptance tests UnrecognizedURLError: /tests

Having recently migrated Ember CLI from 2.15.0 to 3.7.0, the acceptance tests have regressed heavily. Having run the qunit codemod, the following issue seems to persist: UnrecognizedURLError: /tests.

I have produced a minimum reproduction of the issue via the following acceptance test:

import { module, test } from 'qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';


module('Acceptance | poc', function(hooks) {
  setupApplicationTest(hooks);
  setupMirage(hooks);

  test('visiting /poc', async function(assert) {
    await visit('/');

    assert.equal(currentURL(), '/');
  });
});


This results on the three following issues:

Promise rejected before "visiting /poc": /tests?filter=poc
Source:     UnrecognizedURLError: /tests?filter=poc 

beforeEach failed on visiting /poc: You must call one of the ember-qunit setupTest(), setupRenderingTest() or setupApplicationTest() methods before calling setupMirage()
Source:     Error: You must call one of the ember-qunit setupTest(), setupRenderingTest() or setupApplicationTest() methods before calling setupMirage()

Promise rejected after "visiting /poc": Cannot use 'in' operator to search for 'destroy' in undefined@ 80 ms
Source:     TypeError: Cannot use 'in' operator to search for 'destroy' in undefined

Any advice would be greatly appreciated!




How do I properly forward paths to an Ember app in Nginx?

Ember cannot simply be configured like this:

location / {
    index index.html;
}

We need any possible contents of the public directory accessible from the root. E.g. my.example.com/img/logo.png

location / {
    try_files $uri $uri/ /index.html;
}

However, we need every route (path) to be a possible entry-point to the Ember app, so we need to redirect non-asset files to index.html.

I had assumed it would be something like this. This is wrong:

location / {
    try_files $uri $uri/ index.html$uri$is_args$args;
}

The routes appended to index.html result in 404.

Next attempt, use the # hash internally, don't let the user know. This is wrong:

location / {
    try_files $uri $uri/ index.html#$uri$is_args$args;
}

This does not work because # turns the rest into a comment. As far as I understand, nginx ignores # internally anyway.

Next attempt, we use ? in stead. This works:

location / {
    try_files $uri $uri/ /index.html?/$request_uri;
}

We can now 'enter' the application from any non-index path. However, now we've "used up" the query string. We can no longer use the query string, at least not as an entry path, e.g. sharable link. Hence the question:

How do I properly forward paths to an Ember app in Nginx?

  • Allow deep paths
  • Allow query string

E.g.: my.example.com/posts/pinned?sort=asc




mercredi 20 mars 2019

Cannot get HTML anchors to work when opening URL with Chrome Ember.js

I have the following simple ember application (only an application.hbs file).

Here I have several anchors and would like the user to click on one and get to that section of the page (much like what is used in wikipedia).

Here's the problem. If I click one of the links at the top, it works. However, if I am in Chrome and I type in an anchor url (I.E. localhost:4200/#midnight_love), the the URL will load the Ember app, but fail to jump to the anchor. I have found that this only occurs in Chrome and that the site will jump to the anchor in both Firefox and Internet Explorer. All the code needed to recreate this problem is given below if you simply copy/paste into your application.hbs of an ember app.

Also note that this exact same code would work across all browsers, had I pasted this code simply into an HTML file.

Application.hbs

<ul>
<li class="toclevel-2 tocsection-3"><a href="#Early_career"><span class="tocnumber">2.1</span> <span class="toctext">Early career</span></a></li>
<li class="toclevel-2 tocsection-4"><a href="#Initial_success"><span class="tocnumber">2.2</span> <span class="toctext">Initial success</span></a></li>
<li class="toclevel-2 tocsection-5"><a href="#What's_Going_On_and_subsequent_success"><span class="tocnumber">2.3</span> <span class="toctext"><i>What's Going On</i> and subsequent success</span></a></li>
<li class="toclevel-2 tocsection-6"><a href="#Last_Motown_recordings_and_European_exile"><span class="tocnumber">2.4</span> <span class="toctext">Last Motown recordings and European exile</span></a></li>
<li class="toclevel-2 tocsection-7"><a href="#Midnight_Love"><span class="tocnumber">2.5</span> <span class="toctext"><i>Midnight Love</i></span></a></li>
</ul>

<h2><span class="mw-headline" id="Early_career">Early_career</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="Initial_success"></span>Initial_success</h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="What's_Going_On_and_subsequent_success">What's_Going_On_and_subsequent_success</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="Last_Motown_recordings_and_European_exile">Last_Motown_recordings_and_European_exile</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="">Foo</span></h2>
<h2><span class="mw-headline" id="Midnight_Love">Midnight_Love</span></h2>




Is it possible to use mouseEnter with ember-bootstrap components?

I'm currently using Ember Bootstrap in a project and creating a Navigation Bar has been my first real experience of using contextual components.

The current code for the nav bar is as follows:



<div class="container-fluid" style="padding-left:50px;padding-right:50px;height:50px ">
    <div class="navbar-nav mr-left">
        
        

        
        Dropdown 1 <span class="caret"></span>
        
        Link 1
        Link 2
        
        

        
        Current User: <b>MICKEY MOUSE</b>
        
        
        
    </div>
</div>


Part of the specification for this component is that a sub-menu appears to the left when a user hovers over one of the dropdown links and I'm having a hard time working out how to do it.

The main problem is I can't work out how to take advantage of the mouseEnter event in a contextual component like this. Where I could normally add an action in element space like:

<h1 >Text</h1>

I'm unable to do so here because the element space is controlled by the sub-components. Likewise, If I try and use a closure action like



Then I am unsure how to specify the action fire on the mouseEnter event and get errors of an 'action not found' nature - I suspect because the Ember Bootstrap add on does not expose a anAction action for me to use.

Any guidance would be greatly appreciated.

( I did try to set up a working twiddle for this but was unable to do anything except show an empty navigation bar with no links!)




Can i access ember service variables in my whole application?

I Created an ember service and i initialized its value now i updated that value in a controller. I want this updated variable in my complete application ? What should i supposed to do. Any help will be appreciated. Thanks




Ember 1.4.0 to Ember 1.13 Upgradation

I'm upgrading the code from Ember 1.0.4 to Ember 1.13. When I'm execute the below code using ember 1.13 I'm getting the error

RenderResult.build = function (env, scope, template, options, contextualElement) {
   var dom = env.dom;
   var fragment = getCachedFragment(template, env);
   var nodes = template.buildRenderNodes(dom, fragment, contextualElement);

   var rootNode, ownerNode, shouldSetContent;

   if (options && options.renderNode) {
     rootNode = options.renderNode;
     ownerNode = rootNode.ownerNode;
     shouldSetContent = true;
   } else {
     rootNode = dom.createMorph(null, fragment.firstChild, fragment.lastChild, contextualElement);
     ownerNode = rootNode;
     initializeNode(rootNode, ownerNode);
     shouldSetContent = false;
   }

I'm getting the below error while execute the code.

    Uncaught TypeError: template.buildRenderNodes is not a function
   at Function.RenderResult.build (core.js:9567)
   at render (core.js:9553)
   at core.js:10465
   at renderAndCleanup (core.js:10470)
   at Object.block [as default] (core.js:10464)
   at yield (core.js:9495)
   at handleKeyword (core.js:9470)
   at handleRedirect (core.js:9469)
   at Object.inline (core.js:9481)
   at Object.content (core.js:9349)




mardi 19 mars 2019

How to handle multiple ember models for same resource

I have a model user in app/models/user.js with the following:

import attr from 'ember-data/attr';
import Model from 'ember-data/model';

export default Model.extend({
  email:        attr('string'),
  username:     attr('string'),
  firstName:    attr('string'),
  lastName:     attr('string'),
  currency:     attr('string'),
  locale:       attr('string'),
  avatar:       attr('string')
});

And I want to update its attributes in different routes:

In http://localhost:4200/account/profile I want to update just:

  • firstName
  • lastName
  • avatar
  • username

In http://localhost:4200/account/preferences I want to update just:

  • locale
  • currency

I'm using ember pod structure so I was thinking to create two models inside those routes with custom adapters and serializers to handle validations and serialize just the attributes that I want for each route.

- models
  - user.js
- pods
   - account
     - profile
       - adapter.js
       - controller.js
       - model.js
       - route.js
       - serializer.js
       - template.hbs
     - preferences
       - adapter.js
       - controller.js
       - model.js
       - route.js
       - serializer.js
       - template.hbs


But this solution has problems with data binding because I'm not updating the user model.

What would it be a good approach for doing this?




set alias for `model` hook

HELP

If there is a model hook in app/routes/post.js say

model() {
  return this.store.query('post');
}

in template the returned promised is accessed using


  ...


Is there any way to set alias for the model? Something like this in route or controller?

posts: alias('model')

So I can access the returned promise in the template as


  ...


Is there something which is already there or I'm missing from the ember documentation?




lundi 18 mars 2019

CSS trickery -- how can I apply hover "fill" on current svg and previous svg siblings

I'm looking for a way to fill in current element and previous sibling elements based on hover. I'm working with handlebars (through Ember) and normal CSS. Here's some code for context --

order-feedback-stars.hbs - this renders 5 stars, empty or filled based on if the tag is clicked

<div class="feedback-star-container">
  
    <a  class="feedback-star">
      
        
      
        
      
    </a>
  
</div>

I've been experimenting with different CSS classes and selectors, but all I've been able to do is highlight just the element that I'm hovering over with the following CSS --

feedback.scss

svg:hover {
   fill: #1F4F46;
 }

Here is what the stars look like. If I hover over the 5th star, then the expected result is that all the previous stars get filled in green. Some advice would be much appreciated -- thanks so much!

Stars




Stack trace: Error: Assertion Failed: 'data-adapter' is not a recognized type

Ember data won't show on the inspector.The error is showing below. I am using module unification in new ember. module unification ember

Can someone tell me how to fix it because I need to see data in ember inspector?

Ember Inspector has errored.
This is likely a bug in the inspector itself.
You can report bugs at https://github.com/emberjs/ember-inspector.
Error message: Assertion Failed: 'data-adapter' is not a recognized type
Stack trace: Error: Assertion Failed: 'data-adapter' is not a recognized type
    at assert (http://localhost:4200/assets/vendor.js:73088:19)
    at Resolver._definitiveCollection (http://localhost:4200/assets/vendor.js:73063:31)
    at Resolver.identify (http://localhost:4200/assets/vendor.js:73027:37)
    at Resolver.resolve (http://localhost:4200/assets/vendor.js:73055:27)
    at Class.resolve (http://localhost:4200/assets/vendor.js:98399:36)
    at Class.resolve (http://localhost:4200/assets/vendor.js:98232:25)
    at Class.superWrapper [as resolve] (http://localhost:4200/assets/vendor.js:41053:22)
    at _resolve (http://localhost:4200/assets/vendor.js:12906:36)
    at Registry.resolve (http://localhost:4200/assets/vendor.js:12445:21)
    at Registry.resolve (http://localhost:4200/assets/vendor.js:12450:60)
warn @ VM2062:92
handleError @ VM2062:149
(anonymous) @ VM2062:3515
_run @ backburner.js:1066
run @ backburner.js:748
run @ index.js:111
wrap @ VM2062:3511
messageReceived @ VM2062:3482
get.onMessageReceived.message @ VM2062:3476
get.forEach.callback @ VM2062:127
_messageReceived @ VM2062:126
run @ VM2062:344
_run @ backburner.js:1066
run @ backburner.js:748
run @ index.js:111
chromePort.addEventListener.event @ VM2062:343




Pods Structure in Ember Addon

With respect to this question, I created an ember-addon project and it is working fine as expected.

But If I try to introduce pods structure in the ember-addon project it is not working.

It throws error that the route is not found.
What should I do?


Thanks In Advance!




ember-cordova cannot multi-upload photos with x-file-input

I am using the plugin from https://github.com/thefrontside/emberx-file-input. I want to multi-select photos while uploading. I can do it from the laptop. But when I use ember-cordova and create app on my android device, I cannot multi-select photos even though I have added the multiple = true in the code. Here is the code below,






After installing Ember Fastboot not run

I`ve upgrade my ember app from 1.13 to 2.3 and add ember-cli-fastboot. But after installing this plugin, he`s not working. Parallel i create new project with version 2.18 and repeat installation. And fastboot works fine. I cant start my project from zero. Because he`s working on the server. I can only upgrade my ember step by step.

Ember version:

ember: 2.3.2
ember-cli: 3.8.1
node: 10.15.2
os: linux x64

Build info:

Slowest Nodes (totalTime => 5% )              | Total (avg)         
----------------------------------------------+---------------------
LessCompiler (1)                              | 681ms               
Rollup (3)                                    | 604ms (201 ms)      
Babel: ember-data (2)                         | 367ms (183 ms)      
Babel: chat (3)                               | 250ms (83 ms)       
Babel: ember-cli-fastboot (1)                 | 213ms               
Package /assets/vendor.js (1)                 | 190ms     




dimanche 17 mars 2019

How to access controller property in Ember.computed.sort

In a Ember 1.13 i have a controller that uses Ember.computed.sort:

export default Ember.Component.extend({
    sortedItems: Ember.computed.sort("allItems", function(a, b) {
        //How to access columnList from here?
    }
    columnList: ["name","shortcode"]
})

I need to access columnList property of the component controller instance to customize behaviour of comparision function provided to Ember.computed.sort. How to access the columnList inside comparision function in a place indicated in the code above?




vendredi 15 mars 2019

Which JavaScript framework/library is best suited? [on hold]

I am currently prototyping and plan on building a web app which will be used to assort many different features of a product into feature-packages ready to be loaded on its central computing unit. It's basically a big, "smart" form that converts many inputs into a machine-readable output.

I never built anything like this so I'm asking What framework/library is best suited for this task? Angular? React? Vue? Ember? Backbone? Something else? I saw people being angry about some of them being used inflationary and I want to do it right.

Specifications

  • basically a big form (radio/check/text-inputs)
  • REST-API
  • compiling inputs based on JSON dictionary
  • usability is important
  • looks are not
  • easily expandable in the future

Please be sure to stick to facts as this isn't a question about which is superior but a question about which is best suited for that task. (To make this an useful Q&A for everyone you could answer it in a more broader sense so the next guy evaluating their own project can get an answer out of it as well.)

Thank you




Ember-simple-auth and ember-fetch no authorization in fetch query

I am using ember with ember-simple-auth(1.7.0) for authentication. Here is the application adapter function :

authorize(xhr) {
    let { email, token } = this.get('session.data.authenticated');
    let authData = `Token token="${token}", email="${email}"`;
    xhr.setRequestHeader('Authorization', authData);
  }

When I use ember-fetch(5.1.3) there is no header for authentication :

fetch('/appname/v1/user/count'+count_params).then((response)=>{return response.json()})

The same model do successful emberDS query with the auth info in the header. How can I add the information to the fetch headers ?




jeudi 14 mars 2019

Intellisense for Ember injected services

I am a bit frustrated that there doesn't seem any decent "Ember intellisense" available in any common IDE (like VS Code, Webstorm, Atom). By "intellisense" I mean that, as long as my Ember project is a standard Ember CLI project with all the common Service, Helper folders etc., and I inject e.g. a service using myService: service(), this would be recognized by Intellisense and, after typing this.myService, I would see all functions in the service. Also, if I Ctrl+Click on the function in this.myService.myFunction(), I would expect to navigate to the definition of myFunction.

For other frameworks, such as Angular, there are plugins which support all this.

Is it really the case that in the Year 2019, I have to use "Find in Files" to find the definition of a service function, like I did 25 years ago when programming with Visual Basic 3?

Does anyone know of a way or tool which I might have missed, and which would support this scenario? Note that I don't speak of bare-bones features such as switching between router/controller/template, but of real intellisense for custom objects.




Ember fetch data coming from same route with different dynamic segment id

I want via an action to change the dynamic segment id from the url at the same route.E.g. go from http://localhost:4200/dashboard/my_missions/3 to
http://localhost:4200/dashboard/my_missions/1. Nothing is triggered because of the same route i guess. How can i fetch the new model data with the dynamic id change ???

My rooter.js:

Router.map(function() {
  this.route('dashboard', function() {
    this.route('my_missions', {path: '/my_missions/:mission_id'});
  });
});

My route: dashboard/my_mission.js

import Ember from 'ember';

export default Ember.Route.extend({
    model: function(params) {
        this.set('missionId', params.mission_id);
        return this.modelFor('dashboard');
    },
    setupController(controller, model) {
        this._super(...arguments);
...




Render sidebar based on model in EmberJS

I started with learning EmberJS and maybe the answer is trivial, but after some researching I still can't find a solution. I my model template I have some buttons(each for different object) which after click should expand sidebar with its details.

What do I want to reach is something like this: example screenshot

Could someone provide me some simple twiddle?




Ember 1.13 upgradation

I'm upgrading the code from Ember 1.0.4 to Ember 1.13. When I'm execute the below code using ember 1.13 I'm getting the error

title: Ember.computed('content.title', 'managedObject.isHome', 'managedObject.finalManagedObject', {
                set: function(name, value) {
                    this.set('content.title', value);
                },
                if (this.get('content.title') !== undefined) {
                    return title;
                }
                if (this.get('managedObject') == RSuite.rootNode) {
                    return "Home";
                }
                get: function() {
                  return this.get('managedObject.label') || this.get('managedObject.finalManagedObject.displayName');
                }
            }),

I'm getting the below error while execute the code.

Uncaught SyntaxError: Unexpected token this




How do I debug a failing ember-cli build?

I have an oldish ember-cli project. It's Ember 3.5, but it came from 2.x initially (and has some bower components). It used to build and deploy fine. But now I started it from a clean computer. I changed nothing, except reinstall its dependencies.

npm install
./node_modules/bower/bin/bower install
./node_modules/ember-cli/bin/ember build -prod

After some processing, I see the following error:

ajv.js: property right of assignmentexpression expected node to be of a type ["expression"] but instead got null

I try to lock some versions (i.e. remove ~ and ^ from package.json version numbers and run npm install again) and I either get the same error or something equally vague.

async.js: Property object of MemberExpression expected node

Trying the same with bower results in other error messages:

uglifier: Unexpected token: punc (:)

There were others but I didn't write everything down. I've spend quite some time on this. The problem is that every error, including their stack trace, doesn't really help me find where the problem is.

How can I debug this? How can I fix this? I thought package-lock.json was made to prevent this, but I guess I'm in dependency hell either way. Perhaps it was a problem with bower.json? There is no bower-lock.json.




mercredi 13 mars 2019

Fetching data from other model Ember

I have a user model

export default DS.Model.extend({
    username : DS.attr('string'),
    numberOfQuotes: DS.attr('number'),
    numberOfFollowers: DS.attr('number'),
    numberOfFollowing: DS.attr('number')
});

and a quotes model

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

And i am getting quotes which also includes the user id and for this i am using

quotes :this.store.findAll('quote') But i am unable to get the user object so i am unable to retreive the data. Any help will work thanks.




Refresh ember model

I have a simple route calling

model: function(params) {
  return this.store.find("booking", params.booking_id);
},

When the route is visited, changes can be made, and I want them to be reset the next time the page is visited during the same session, unless they have been saved. The simple operation of refreshing the data once obtained with { reload: true } now doesn't seem to have an easy, straightforward alternative.

How do I do this? Thank you.




Combining two emberjs apps

I am currently using ember 1.13. I have two apps which use emberjs. Now I am thinking of integrating these two apps by creating a new route in the first app and display specific route of the second app. Many suggested to use ember-engines,but they need ember 2.10 or higher.Since my application mostly depends on IE 8,I cannot migrate from ember 1.x.

So what should I do? Thanks in advance!!

Cheers!!!




lundi 11 mars 2019

ember vertical collection rendering only when clicked

When I use the ember vertical collection from https://github.com/html-next/vertical-collection, it only renders new components when clicked on the screen, it does not render new components while scrolling. Here is the code below


        -----
    




How can I add an external javascript tag to an Ember JS app without touching the index.html?

Is it possible to load an external javascript resource in Ember without touching index.html?

If I could add to html, I would simply add the following and it works.

    <script type="text/javascript">var my_data = [{ foo: "bar", value: 1.234 }];</script>
    <script type="text/javascript" async src="https://external.com/file.js"></script>
</body>

I tried appending the tag using jQuery, but it won't actually launch the javascript on the client:

$('body').append('<script type="text/javascript">var my_data = [{ foo: "bar", value: 1.234 }];</script>');
$('body').append('<script type="text/javascript" async src="https://external.com/file.js"></script>');

Where file.js sends my_data to external.com.

Unfortunately I'm building a single-page-app for a client without access to index.html. What do you recommend to append the two script tags? Is it possible?


It gets worse. I need to send my_data to external.com again after a user action.

In a traditional html environment I would do the following: (this works)

page1.html:

    <a href="/page2.html">user action to track</a>
    <script type="text/javascript">var my_data = [{ foo: "bar", value: 1.234 }];</script>
    <script type="text/javascript" async src="https://external.com/file.js"></script>
</body>

page2.html:

    <script type="text/javascript">var my_data = [{ foo: "qux", value: 3.21 }];</script>
    <script type="text/javascript" async src="https://external.com/file.js"></script>
</body>

How can I accomplish the same thing in Javascript, on a single-page-app, without touching index.html?




Convert data and time

Want to remove TimeZone details from date+time.(EmberJS)

Input: "2019-03-11T09:00:00.000+09:00" (GMT+9) .

Like to convert in this format "2019-03-11T09:00:00.000+00:00" (GMT+0)




Ember equivalent of (missing) computed.notEqual?

Curious what do as equivalent to the following computed property. In fact, there is no notEqual method built in to Ember's computed.

  isNotPizza: computed.notEqual('controllers.application.currentRouteName', 'pizza'),




Ember 3 Computed Properties

I'm trying to migrate from ember 2 to ember 3, and i have problems with computed properties.

Before, i had this kind of computed properties in a component :

import Ember from 'ember';

totalPrice: Ember.computed('attr1', 'attr2', () => {
    return this.attr1 + this.attr2;
})

and i could do in the hbs template something like :

Total : 

In the new version of ember, i have this :

import { computed, set } from '@ember/object';

totalPrice: computed('attr1', 'attr2', () => {
   return this.attr1 + this.attr2;
})

But in the template, the displayButton property is display as [object] and not with the value. Am i missing something ?




import node js module in ember js framework

I am trying to import a simple node js module into Ember js. I followed the quick start at https://guides.emberjs.com/v3.8.0/getting-started/quick-start/ and got the People List working.

Then I added the simple upper-case module using npm install upper-case and added it to ember-cli-build.js as mentioned in https://guides.emberjs.com/release/addons-and-dependencies/managing-dependencies/.

After that, I opened scientists.js and added import to upper-case as follows:

import Route from '@ember/routing/route';
//import uc from 'upper-case';

export default Route.extend({
  model() {
    var arr = new Array();
    arr[0] = 'Marie Curie'; // uc('Marie Curie');
    arr[1] = 'Mae Jemison';
    arr[2] = 'Albert Hofmann';
    return arr;
  }
});

If I remove the comments, it shows me a blank screen. If I use 'Marie Curie'.toUpperCase() it works, but I want to be able to import such node modules. How can I achieve this?

I have already tried exception while importing module in ember js and ember-auto-import, but they don't seem to work for me. The above method I tried seems to be simple and would be nice if it can work this way.

PS: I could make upper-case work in other JS frameworks such as React and Vue, so the module itself doesn't have any issues.




dimanche 10 mars 2019

How can I resolve the defineProperty deprecation error?

I received an error called DEPRECATION: [DEPRECATED] computed property 'value' was not set on object via 'defineProperty' [deprecation id: ember-meta.descriptor-on-object] and I am really sure which resource file it would like me to resolve. However, I seen the documentation about the deprecations that is related to what I've received and I found this

https://deprecations-app-prod.herokuapp.com/v3.x/#toc_use-defineProperty-to-define-computed-properties https://emberjs.com/api/ember/release/functions/@ember%2Fobject/defineProperty

Please give me an example on how to resolve it as I kind of a bit confused.

Here's my code

    value: computed('formGroup.value', function() {
      let rawValue = this.get('formGroup.value');

      return !!rawValue;
    }),


    /**
     * @public
     * @property maxLength
     * @type {number}
     */
    maxLength: null

Any response is much appreciated.




Ember Cli Mirage: Active Model Adapter with JSONAPISerializer

I am on halfway of implementing JSON API structure (with underscore attributes).


Actual state for development environment is:

I use the Active Model Adapter structure for requesting to the backend for resources and backend response me with JSON API structure.

In Application Serializer I am using JSONAPISerializer. I override methods:

serializeBelongsTo
keyForRelationship
keyForAttribute
serialize
serializeAttribute
serializeHasMany

and for development, everything works for me (backend in Rails communicate with Ember very good).


The problem is with Ember CLI Mirage and conventions (not sure if there are simple solutions or I need to override again methods in this addon).

Actual state with Ember Cli Mirage and test environment:

I am using import { JSONAPISerializer } from 'ember-cli-mirage'; and then trying to manipulate proper request and then transform it for JSON API format.

It could work like this:

Ember Adapter (Active Model Adapter format - with underscore attributes) ---> Mirage Serializer should get request (find resources created before in tests with associations) and then response it with JSON API format ---> JSON API Serializer could catch it and fill Ember DS.

For now, I have a missing part to serialize it for all cases to JSON API standard (with underscored attributes)

Where should I do this transformation to minimize overriding JSONAPISerializer Mirage Serializer.

I noticed that there are some helpers, but I have a problem to wrap this knowledge together (http://www.ember-cli-mirage.com/docs/advanced/route-handlers#helpers)




vendredi 8 mars 2019

Emberjs Mirage Data - Cannot seem to replicate tutorial

I've recently finished the Emberjs tutorial and want to replicate it without following the tutorial to solidify the leanings.

I cannot seem to get the mirage data or even straight route.js data to work in my .hbs file.

mirage/config.js

   export default function() {

  this.namespace = '/api'

  this.get('/job-opening', function() {
    return {
      data: [{
        type: 'job-opening',
        id: 12,
        attributes: {
          title: 'Cleaner',
          employer: 'Dirty Co.'
        }
      }, {
        type: 'job-opening',
        id: 54,
        attributes: {
          title: 'Production Master',
          employer: 'We Make Things Inc.'
        }
      }, {
        type: 'job-opening',
        id: 3,
        attributes: {
          title: 'King of the Hill',
          employer: 'Mount Everest LLC'
        }
      }, {
        type: 'job-opening',
        id: 231,
        attributes: {
          title: 'Garbage Person',
          employer: 'Try to be a better person pty ltd'
        }
      }]
    }
  })

adapters//application.js

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
  namespace: 'api'
});

routes/job-opening.js

import DS from 'ember-data';

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

job-opening.js

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

export default Route.extend({
  model() {
    return this.store.findAll('job-opening')
  }
});

templates/job-opening.hbs

Doesn't seem to load at all, I assume error in the job-opening.js because when I copy the data from mirage.js and move it straight into the job-opening.js and remove this.store.findAll('job-opening') it will load the hardcoded html.

<div>"Hello World!"</div>


  <h3></h3>
  <h3></h3>
  <br>


<br>
<div>"Goobye Cruel World!"</div>



This makes me thing it's something wrong with how I have mirage setup or maybe the model. I've tried restart the ember server. Currently in development. I've also tried to re-read the tutorial and looked around on stack and didn't find anything. Feel like I've made a simple mistake somewhere..

My goal here is just to get the data on screen with no formatting.

Thanks in advance for any and all help.

Update.. to show what I mean when I add in hardcoded values..

routes/job-opening.js This will produce html when I load the page like below. but no model values..

"Hello World!"

"Goobye Cruel World!"

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

export default Route.extend({
  model() {
    //return this.store.findAll('job-opening')
    return {
      data: [{
        type: 'job-opening',
        id: 12,
        attributes: {
          title: 'Cleaner',
          employer: 'Dirty Co.'
        }
      }, {
        type: 'job-opening',
        id: 54,
        attributes: {
          title: 'Production Master',
          employer: 'We Make Things Inc.'
        }
      }, {
        type: 'job-opening',
        id: 3,
        attributes: {
          title: 'King of the Hill',
          employer: 'Mount Everest LLC'
        }
      }, {
        type: 'job-opening',
        id: 231,
        attributes: {
          title: 'Garbage Person',
          employer: 'Try to be a better person pty ltd'
        }
      }]
    }
  }
});




findAll with a property defined by parent

2 components, 1 parent 1 child. The parent is a list with buttons. User clicks the button and the child editor becomes visible and the variable listType gets passed to the child from the parent.

I want a property to do a findAll in the child based on the listType property, e.g.

listType:null,
records: this.get('store').findAll(this.get('listType'));

problem is when the child editor first inits listType is undefined and takes a moment for the data to be passed down from the parent. How should I compute the records based on the listType so that it can dynamically change records when a different listType is selected from the parent list and not crash when the listType property is undefined on init?

This might seem a little weird but I have 20 different listTypes and being able to compute records this way will save me from having to create an additional 40 files to save and delete the model types required.




How to properly dockerize Ember.js FastBoot

Deploying a dockerized Ember.js app stack can be done with three or four containers. For https it's easiest to proxy over a specialized container that handles vhosts and ssl certificates.

              Internet
                 │
               Server
                 │
             Container
            nginx-proxy
               https
                 │
         ╭───────┴───────╮
    Container        Container
      Ember             API
www.example.com   api.example.com
                         │
                     Container
                         DB

This works fine. But when the Ember app becomes a FastBoot app, the FastBoot server will do the requests to the API for the first pageview server-side. And the API is not reachable via DNS, nor is it https.

How should a setup like this realistically be accomplished?




categorical ui-search in ember

I am trying to make a local category search box using Semantic UI in ember, Here is what I have done so far:

//component nav-bar.js
import Component from '@ember/component';

export default Component.extend({
  searchables: [
    { category: 'Country', title: 'India' },
    { category: 'Country', title: 'Germany' },
    { category: 'Currency', title: 'USD' }
  ]



//component nav-bar.hbs

    <div class="item">
      
        <input type="text" placeholder="Search..." class="prompt">
        <div class="results"></div>
      
    </div>


This is resulting in a simple search box instead of a local categorical search. What should I do to get a categorical search box instead?




Cannot Access Ember child route via url and redirects me to the parent route

I want to access a child route via url eg:https://my-app.com/dashboard/library. When i click this, Ember redirects me to https://my-app.com/dashboard and populates this route's model data correctly, but i want to go to https://my-app.com/dashboard/library, with its new model data. From the other hand i can access https://my-app.com/login via url, that has no model data btw.

At environment.js i have locationType: "auto", and my router.js is like:

Router.map(function() {
  this.route('login');
  this.route('dashboard', function() {
    this.route('child', {path: '/child/:child_id'});
    this.route('library');
  });
});

May be a configuration flag or a Router config issue ?

How can i access this child route via url or has something like that happened to any of you?




Configuring WSGI to service a single index.html file for a single page application

I have a standard Django application set up using WSGI on Apache2 (Ubuntu 18.04)

I now want to serve all front end content via a single index.html file (still allowing access the /admin url and ensuring the REST api calls via /api work). I'm using Ember for the single page application.

Any help much appreciated!

Here is my current .conf set up:

DocumentRoot /var/www/examplesite.co.uk/public_html

Alias /static /home/someuser/djangoprojects/someuser_v1_project/static
<Directory /home/someuser/djangoprojects/someuser_v1_project/static>
      Require all granted
</Directory>

Alias /media /home/someuser/djangoprojects/someuser_v1_project/media
<Directory /home/someuser/djangoprojects/someuser_v1_project/media>
      Require all granted
 </Directory>

 <Directory /home/someuser/djangoprojects/someuser_v1_project/someuser_v1_project>
 <Files wsgi.py>
        Require all granted
 </Files>
 </Directory>

 WSGIDaemonProcess examplesite.co.uk python-home=/home/someuser/virtualenvs/someuser_env python-path=/home/someuser/djangoprojects/someuser_v1_project
 WSGIProcessGroup examplesite.co.uk
 WSGIScriptAlias / /home/someuser/djangoprojects/someuser_v1_project/someuser_v1_project/wsgi.py




jeudi 7 mars 2019

Ember reset items in Ember data when returning to route

I have a route in my Ember app which returns a set of records in the model hook like so:

routes/dashboard.js

model() {
  return this.store.findAll('pending-post');
}

Assuming this returns 10 records, I can see the 10 records in the data tab of Ember Inspector, and when I log . The network tab also shows that an array of 10 records returned in the data object.

I then go to another route in my app and edit a post so that it is no longer pending. This change is persisted to the backend.

When I return to the dashboard, the model hook runs again. The request in the network tab now returns an array of 9 objects, as the API is only returning 9 items.

However, the data tab in Ember inpector still shows 10 items and there are still 10 items in .

What is the best way to force Ember data to remove the item that was not returned by the API the second time around?




Initialize Array in Ember JS Component

I am new to Ember and I am currently working on 3.8 version of Ember. I just want an array to be initialize in component file and then to use the array in template file. Thanks in advance.




Ovverride file in ember addon

I need to override this method: normalize(payload, modelName)

in ember-cli-mirage addon and serializer-registry file

https://github.com/samselikoff/ember-cli-mirage/blob/master/addon/serializer-registry.js#L21

I have no idea where to put file to override it in my ember project.




mercredi 6 mars 2019

Emberjs: conditional transition to route

I am trying to do conditional transition in my router.js. I need to determine the condition(Which is eligibility) based on the boolean value returned by another rest service. Can I write a function to determine that value in router.js and how to use that value to redirect my transition to two separate routes. If the eligibity is true, I need to do this.route('coverage', { path: '/' }); else this.route('inEligible', { path: '/' });

Please provide me an example. I am very new to ember.




force ember store to skip cache and get data from API call

I am trying to understand how can I force ember store to make another api call instead of fetching records from cache when I use findAll. I know if records are already loaded then ember returns cached data unless asked to skip it. On doing some study (blogs, documentation and stack overflow), people has suggested to use reload: true flag with findAll but its not working for me. When I do a reload:true flag then store still returns me data from the cache.

If I am missing anything, then please help.




mardi 5 mars 2019

Hardcoded select item/conditionals in Ember hbs

Instead of tying records to a data list I have a hardcoded list of buttons. What I want is to tie a conditional to the buttons but don't know how. I can when a record gets set to selected item but not with hardcoded values e.g.

<button class='task data ManagedList'>Agreement Type</button>

and then the conditional

want to make it so that when the hardcoded Agreement Type button is clicked the condition if selectedItem is true for this condition




Ember referencing property or getter

I'm a bit confused as to when to reference a property and when to use a getter, and why.

For example, a controller might inject a service for an uptodate location property:

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

    location    : computed('maps.location', function() {
        return this.get('maps').getLocation()
    }),

But getLocation in the service is a simple getter:

getLocation() {
    return this.get('location')
},

Why not use one of these:

this.get('maps').location
this.get('maps').get('location')
this.get('maps.location')

and prevent having to write getters for every parameter? In the spirit of convention over configuration, isn't writing getters a bit redundant?

Simply put, when looking at examples and tutorials, I see different patterns:

  • service.property
  • service.get('property')
  • service.getProperty()

What is correct, when and why?




Detecting multiple request from same ip

I have hosted a web service and for in logs I have seen that there are multiple request come from some ip addresses. I want a way to detect these ip and show captcha to this ip through php code.




lundi 4 mars 2019

using bootstrap with ember 3.8

We start with a new application, using Ember 3.8 and bootstrap/SASS. There seem to be two add-ins available which support bootstrap within Ember, ember-boostrap and ember-cli-bootrap-sassy.

While the former implements ember components for most of the bootstrap features and also "replaces" the original bootstrap.js by it's own implementation, with the latter, it seems I can still use all the original components and js implementations.

From first glace, I would be much more comfortable with ember-cli-bootrap-sassy, since I could still use all bootstrap examples from the web, and having a "customized" version of bootstrap.js also seem somewhat counter-intuitive to me. Also, what about all the bootstrap features ember-bootstrap does not implement, but I still require? It seems like I might be ending with an appliation which would use ember-bootstrap, but additionally uses all sorts of "workarounds" for things not implemented.

Since I don't have much experience in this field, I would be glad for some recommendations and insights from experts.




Ember.JS When I create a new record, how can it be Sorted

I have a view showing a ticket and it's replies.

The replies are reiceved ordered_by Created_at DESC

When I save a new reply here is what I do :

route :

model(params) {
return hash({
  ticket: this.store.findRecord(
    'ticket',params.ticket_id,{include: 'replies'}
  ),
  owners: this.get('store').query('adminUser',{filter: 'supporters'}),
  reply: this.store.createRecord('ticket/reply')
})
}

And the controller :

saveReply(reply){
  reply.set('ticket',this.get('model.ticket'))
  let promise=reply.save()
  promise.then(
    (reply)=>{
      this.set('model.reply',this.store.createRecord('ticket/reply'))
      return reply
    }
  )
  return promise
}

Instead of having the reply at the top of the list, it's at the bottom. How can I order the ticket.replies ?




Ember jQuery selector

Can the below line of code fail or rather throw any JS error in any case (if any of the element in the hiearchy is not found)

Ember.$(".some-panel").closest(".other-panel").siblings("div[role='headline']").find(".some-text").html("Some title");




dimanche 3 mars 2019

Should I upgrade from LTS to another LTS ember version?

I've been trying to upgrade my ember app from 2.18 to 3.4.4 and I just want to know if I chose the correct ember version which is 3.4.4? Any response is much appreciated.