vendredi 28 juin 2019

Model properties are not set

I'm trying to get data from a server and set it to Ember's DS.Model (by ember's magic). But records are created with no data.

I have got a model models/product.js:

const { Model } = DS;

export default Model.extend({
    name: DS.attr(),
    price: DS.attr()
});

In routes/product.js I request all products:

    model() {
        return this.store.findAll('product');
    }

The server returns data: https://gyazo.com/ba38b756f334bc22d07fe18ccfddda34

I expect ember to create 3 records with data from the server. But actually, it creates this https://gyazo.com/a9a7b77d838ec33b05e5f81ef8304cdb

What is wrong? I guess I shouldn't specify any adapters and serializers to get default Ember behavior.




Recompute Ember custom helper on change of a controller property that is passed to the helper

I'm changing the value of a property in my controller and the helper fails to recompute them.

Sample code here:

My template looks like,


    <span>Warning</span>


In my controller,

changeAction: function() {
    let that = this,
        info = that.get("info");
    set(info, "showWarning", true);
}

my helper,

import { helper as buildHelper } from '@ember/component/helper';

export default buildHelper(function(params) {
    let that = this,
        info = that.get("info");
    if(info.showWarning ) {
        return true;
    } else {
        return false
    }
});




jeudi 27 juin 2019

Is it possible for Ember Liquid Fire to hide a bootstrap column?

I have a layout with a number of columns as follows:

<div class="container-fluid">
  <div class="row">
    <div class="col">
      //col content
    </div>
    <div class="col">
      //col content
    </div>
    <div class="col">
      //col content
    </div>
  </div>
</div>

I'd like to use Liquid Fire to hide some columns based on a property, something like this:

    
    <div class="col">
      //col content
    </div>
    

However this breaks the flex sizing of the row. The column that is the subject of the liquid-if is rendered very small when visible whilst the others size according to flex.

I think this is because Liquid-Fire creates it's own <div class="liquid-container"> and <div class="liquid-child"> which is breaking what Bootstrap expects for flex sizing.

With that in mind I tried to add the col class to the invocation:

    

      //col content

    

But when the property changes the content clears and the empty column remains in the DOM.

Is there anything I can do here? I don't really know any other way to animate DOM removals.




Type definition merge for Route in ember-cli-typescript

I'm using ember-cli-typescript to type my Ember.js app step by step. My legacy app uses Route.reopen in an initializer to add a method getParentRoute to the every Route. I could probably subclass Route and use the subclasses Route all over my project, instead I wanted to use typescript definitions in types/*.d.ts to tell the typescript compiler that there is the getParentRoute() method. I've looked at the typescript definitions, but I'm stuck.

I played around with something like:

declare module '@ember/routing/route' {
    export default interface Route {
        getParentRoute() : Route;
    }
}

But that lead to the TS-Error that I need to implement Route instead of extending it. Makes sense, as I declare the interface. But makes no sense for me, as this code is used in ember-data/index.d.ts.

I also tried something like that, but it TS keeps yelling at me that getParentRoute does not exist on Route.

declare module 'ember' {
  export namespace Ember {
    export class Route {
      getParentRoute() : Route;
    }
  }
}

I would expect that the default ember types can be extended, but it seems that is not an easy task due to the complexity of the ember module system. Any help is appreciated. Thanks in advance!




Babel build error when running coverage test with ember-cli-code-coverage

On any version of ember-cli-code-coverage over 1.0.0-beta.4 I get the same error

Build failed.
Build Error (Babel) in chat/components/chat-box.js

chat/components/chat-box.js: You gave us a visitor for the node type "ClassPrivateProperty" but it's not a valid type

chat-box.js has nothing to do with the error so it makes no sense and it also has no test for it.

So why am I getting this error and what does it mean?




Ember store.findAll is reloading view and store.query is not

At the moment, when an article is added to the store, my view is not updated when I use store.query(), filtering server side, in my route but it's updated when I use store.findAll() with filtering client side.

With findAll, filtering client side

//route.js
model() {
return this.get('store').findAll('article');
}

//controller.js
articleSorted: computed.filterBy('model', 'isPublished', true),

and with query filtering server side

//route.js
model() {
  return this.get('store').query('article', { q: 'isPublished' }),
}

The fact is that findAll is reloading and query is not.

I've found this but did not understand https://github.com/emberjs/ember.js/issues/15256




Yarn not installing packages

I'm trying to downgrade my version of ember-cli-code-coverage and once I change the version in my package.json and run yarn install it "installs" but when I go to run the coverage test COVERAGE=true ember test it gives me this error.

Missing yarn packages: 
Package: ember-cli-code-coverage
  * Specified: v1.0.0-beta.6
  * Installed: 1.0.0-beta.8

Run `yarn` to install missing dependencies.

So run yarn and then this is what I get.

yarn install v1.3.2
(node:8156) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
[1/5] Validating package.json...
[2/5] Resolving packages...
success Already up-to-date.
Done in 1.15s.

package.json (under devDependencies): "ember-cli-code-coverage": "v1.0.0-beta.5"




mercredi 26 juin 2019

Why does a `hasMany` relationship create an OPTIONS and GET request for each item in the relationship?

I currently have a response like so from my API:

{
  "data": [{
      "attributes": {
        "customer_name": "The Name",
      },
      "id": 1,
      "relationships": {
        "tasks": {
          "data": [{
              "attributes": {
                "name": "The task",
              },

            ]
          }
        },
        "type": "customer"
      }
    ]
  }

And Ember loads the model correctly. However, when I try and consume the computed property the relationship creates, Ember initiates an OPTIONS and subsequent GET request for each item in the relationship.

I haven't worked with these kinds of relationships before so this may be the expected behaviour but I'm a bit confused.

If it is going to do a request for each one, why bother sending the items as part of the original model via a relationship at all? Why not just do a normal model retrieval which would probably be much quicker.

It seems really wasteful so I suspect I'm not handling or understanding something correctly, I'd appreciate any insight.




mardi 25 juin 2019

html5 tag video download button not working in app

The download button in html5 video tag is not working in ember-cordova mobile app.

I have tested it on both web and chrome in mobile and it is working perfectly. Its just not downloading in app. Any ideas on how to fix this?




How to resize chrome window for ember acceptance test?

Simple case: hamburger menu for small displays, need to test it.

The question is: how to change display size for chrome browser in ember.js test env?




dimanche 23 juin 2019

Add a sibling div to Ember Form For input element

I am using Ember Form For and I want to know if it is possible to add a sibling element.

Currently doing this:

will render this:

<div>
  <label><input type="radio" value="female" />Female</label>
</div>

I need a container sibling element which I can add CSS pseudo classes to. I am unable to target parent containers of the input hence why I need a sibling element. So something like this is what I am after:

<div>
  <label>
    <input type="radio" value="female" />
    Female
    <div class="someClass></div>
  </label>
</div>




samedi 22 juin 2019

Where is this value defined - "(action (mut foo) true)"?

On the surface this is a question about ember-cp-validations but really it's about the action (mut foo) construct. I have read the release notes for when that was first introduced but it doesn't address the issue I'm raising here.

In an Ember.js template, when using ember-cp-validations, you can execute validations and control the display of the relevant error message like this .

enter image description here

When focus-out fires a property showFirstNameError is updated. That property is subsequently used to control the display or otherwise of the error message.

This works perfectly well and is consistent with the ember-cp-validation demo.

But where is the property showFirstNameError actually defined ? I was expecting it be part of the validations property or in some way part of the component, controller or route but I can't find.

Can anyone help me with this please ?




vendredi 21 juin 2019

Ember-cli acceptance test times out on await click(); qunit error: Uncaught (in promise) Error: pushFailure()

I'm trying to create an acceptance test for the login page of a webapp. Everything is almost working, except the await click(element) promise never resolves:

import { module, test } from 'qunit';
import { visit, currentURL, fillIn, click, waitFor, getSettledState } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { invalidateSession } from 'ember-simple-auth/test-support';
import { setupMirage } from 'ember-cli-mirage/test-support';

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

  test('login page | login success', async function(assert) {
    assert.timeout(5000);

    console.log('start', getSettledState());

    await visit('/login');
    assert.equal(currentURL(), '/login');

    await waitFor('.btn-primary:disabled');

    await fillIn('input[type="text"]', 'mirage');
    await fillIn('input[type="password"]', 'password1234');

    await waitFor('.btn-primary:not([disabled])', 2000);
    console.log('btn enabled');

    let btnSubmit = document.querySelector('.btn-primary');
    assert.equal(btnSubmit.disabled, false);

    await click(btnSubmit);
    console.log('await btn click');

    await waitFor('.nav-tabs', 4000);
    console.log('nav complete');

    assert.equal(currentURL(), '/bid-search/planetbids-bids');
    console.log('finished', getSettledState());
  });
});

If I run this test as-is, "await btn click" doesn't log in the console, until it times-out. I also get the qunit error "Uncaught (in promise) Error: pushFailure() assertion outside test context, in ___ at internalStart" (underscores added by me)

HOWEVER, if I remove the await part of the click(btnSubmit) call, the test completes successfully BUT, the last check of getSettledState() returns this:

hasPendingRequests: true
hasPendingTimers: true
hasPendingWaiters: false
hasRunLoop: true
pendingRequestCount: 1

So it looks like if I run the test correctly with await click(btnSubmit), the test times out on the click(), but if I just call click(btnSubmit), the tests complete successfully, although testem or qunit doesn't know all the tests completed. What am I doing wrong?




Making a file protected with the same system than the endpoint available in an Ember app

The ember App run on top of a rails API.

For authentication It uses a token header (with devise server side)

I have an index action that return a CSV when the request add .csv to the URL :

        respond_to do |format|
          format.json {json_response @custormer_info_requests.page(@page).per(@size)}
          format.csv {send_data @custormer_info_requests.to_csv, filename: "demandes.csv"}
        end

The problem is that a direct link like this : <a href='/marketadmin_api/v1/customer_info_requests.csv?partner_id='>File</a>

Fails with a 401 because there is no auth header.

How do you allow users to download protected files ?




jeudi 20 juin 2019

Assigning value to a model in a handlebars template

I'm following this tutorial and any time it references an input element it defines them as so:



I'm told this is out of date and indeed the docs don't use that format, instead using this format:

<input type="text" 

I'm at the point of the tutorial where I'm saving data to the store. I've amended the tutorial to use angle brackets instead of curly braces like so:

<input type="text" value= class="form-control" placeholder="The name of the Library" />
<input type="text" value= class="form-control" placeholder="The address of the Library" />
<input type="text" value= class="form-control" placeholder="The phone number of the Library" />
<button type="submit" class="btn btn-default" >Add to library list</button>

My route looks like:

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

export default Route.extend({

  model() {
    return this.store.createRecord('library');
  },

  actions: {
    saveLibrary(newLibrary) {
      newLibrary.save().then(() => this.transitionTo('libraries'));
    },

    willTransition() {
      this.controller.get('model').rollbackAttributes();
    }
  }

});

When I call the route action saveLibrary and open the debugger, newLibrary doesn't have any data from the model properties. Whenever I change the handlebars template to use curly braces like the tutorial, it works fine; newLibrary contains name, address & phone.

What is the syntax for using angle brankets and having it propagate to route.js?




Invalid or illegal string was specified beforeModel

In a beforeModel hook of my route i want to check a window property and redirect to another url if it is set.

window.open(url, "_self")

I'm getting "An invalid or illegal string was specified beforeModel". Why am I getting this error and how do I achieve this ?




Ember.js delay in passing object properties to child component after setting them in parent

I'm working in Ember 3.1.4.

In keeping with the DDAU pattern, I have a set setProperty action in my controller, which simply accepts the property name and the value to set it to, and then does so.

I then pass the action into my component, and I can call it to set a property at the controller level, and then pass the property back down into the component.

When setting a property to a string, it works as expected and if I get the property immediately after calling the setProperty action, it returns the new value (As when setting simpleProp below).

Strangely, when I use setProperty to set a property to an empty object, or to set a child property on an object, the property returns undefined if I get it immediately after calling the action, but returns the new value if I use a setTimeout of 1 millisecond.

What causes this, and is there a way I can prevent this from happening?

Setting a property to an empty object

Controller

setProperty: function(property, value) {
  this.set(property, value);
},

my-component.js

didInsertElement() {
  this.setProperty('parentObject', {});
  console.log(this.get('parentObject')); // undefined
  setTimeout(() => {
    console.log(this.get('parentObject')); // {}
  }, 1);
  this.set('simpleProp', 'foo');
  console.log(this.get('simpleProp')); // 'foo'
}

Template



Setting a child property on an existing object

Controller

init() {
  this._super(...arguments);
  this.parentObject = {};
}
setProperty: function(property, value) {
  this.set(property, value);
},

my-component.js

didInsertElement() {
  this.setProperty('parentObject.childProp', 'bar');
  console.log(this.get('childProp')); // undefined
  setTimeout(() => {
    console.log(this.get('childProp')); // 'bar'
  }, 1);
  this.set('simpleProp', 'foo');
  console.log(this.get('simpleProp')); // 'foo'
}

Template






mercredi 19 juin 2019

How to implement a correct filtering in ember.js

I have a modelA, modelB, and modelC. modelA hasMany modelB, modelB belongsTo modelA, modelB belongsTo modelC.

Below is my computed property on my component.js and the code below is I want to get all the modelA where the modelC id is equal to the baz.id

foo: computed('modelA', 'baz.id', function() {
  return this.get('modelA').filter((a) => {
    return a.get('modelB').filter((b) => {
      let userId = b.get('modelC.id');
      let bazId = this.get('baz.id');

      if (userId === bazId) {
        return b;
      }
    })
  });
}),

Issue: I am not getting the correct response. The response is not equivalent to my expectations. Question: Did I implement the computed property correctly based on my desired scenario which is I want to get all the modelA where the modelC id is equal to the baz.id

Appreciate for any response. Thank you




How to get a nested routeName in the Parents route or controller in Ember JS

I have a nested route and I want to do something on that route. To do that I need to determine when I am on that route.

I'd like to do this from the Parents route or controller. I have tried using

routeName
fullRouteName

in the Parent route but these only return the Parents route name.

Is there a way to get a Child routes name in the Parent route?




How to update div element attribute value in ember js and tabulator

I am using tabulator api in ember js framework to display dynamic tables. where tab is not moving from 1st column to 3rd column because 2nd column is disabled. To do this I am trying to update the tabindex attribute as "-1"(by defaule all columns it is zero) for the second column. I have used jquery to do this but it didn't work out.

table = new Tabulator("#sample-table", {
            data:self.get('tableData'),
            selectable:true,
            columns:self.get('tableColumnData'),
            keybindings:true,            
            cellEdited:function(cell){                              
                var accnamecol = $("[tabulator-field=ACCNAME]").tabindex=-1;   
}

tabindex attribute need to modify in the below dom

<div class="tabulator-row tabulator-selectable tabulator-row-odd tabulator-selected" role="row" style="padding-left: 0px;">
<div class="tabulator-cell" role="gridcell" tabulator-field="number" tabindex="0" title="" style="width: 282px; text-align: center; height: 32px;">
11111
<div class="tabulator-col-resize-handle"/>
<div class="tabulator-col-resize-handle prev"/>
</div>
<div class="tabulator-cell" role="gridcell" tabulator-field="name" tabindex="0" title="" style="width: 282px; text-align: center; height: 32px;">
abcdefghi
<div class="tabulator-col-resize-handle"/>
<div class="tabulator-col-resize-handle prev"/>
</div>
<div class="tabulator-cell" role="gridcell" tabulator-field="AMOUNT" tabindex="0" title="" style="width: 282px; text-align: center; height: 32px;">
<div class="tabulator-col-resize-handle"/>
<div class="tabulator-col-resize-handle prev"/>
</div>
<div class="tabulator-cell" role="gridcell" tabulator-field="refno" tabindex="0" title="" style="width: 284px; text-align: center; height: 32px;">
<div class="tabulator-col-resize-handle"/>
<div class="tabulator-col-resize-handle prev"/>
</div>
</div>
}); 

enter image description here




How to use the `fill_options` with fill_in for ember acceptance test?

When you have the input with already existed text inside and try to fill_in new text, it is concatenating, against is replacing, how to fix it on ember?

I can provide an example with Capybara which works correctly:

fill_in '.div', with: 'text', fill_options: { clear: :backspace }

Any help is appreciated




Finding an Ember-Data row created with 'createRecord' and with null id value?

I am using the following pattern in an Ember 3.8 project ...

Situation

When the user navigates to the route foo/add the model function in the Route definition uses createRecord to generate an empty foo record in the Data Store.

The foo/add template uses a Component which implements a form to enter foo details into. The form, in turn, uses an instance of ember-power-select for which an onchange handler is defined in the foo form Component.

Once the form is displayed the user is free to use the power select.

When the onchange handler of the power select fires I want to update the record created initially by createRecord.

Issue

I can send an action to the foo/add Controller but how does the Controller find the row in the Data Store ? Because the row has not yet been inserted on the server it doesn't have the ID which will eventually be associated with it, the id value is in fact null.

Alternatives

I have read some references in old Ember material to being able to generate your own ID at the point of createRecord but I can't find a contemporary reference.

I'm open to a totally different approach so any suggestions welcome.

Finally, although I'm using the Data Store to hold data on the client side I'm not actually using Ember-Data to communicate with the server (not sure that makes any difference but I thought I would make it clear).




mardi 18 juin 2019

Ember development server appears to be running in test mode

When I run ember serve while logging out the environment variable in config/environment.js, I see three values logged:

  1. undefined
  2. development
  3. test

(This is in an inherited project.)

In a fresh app created using ember new my-app, I see three values also:

  1. development
  2. test
  3. development

Which leads me to believe my inherited project is running in test mode and a fresh project is running in development mode as I would expect.

Running ember serve --environment=development does not change the observed behavior in the inherited project.

My questions are why do I see three values logged when running ember serve and how can I figure out why my development environment is running in test?




lundi 17 juin 2019

Ember js LinkTo section in another route

I am trying to link to a section in another route. I looked online and cannot find a way to do this basic function in Ember JS.

I have tried:

href="someRoute#section" // does not work

and

<LinkTo @route="someRoute#section">Link</LinkTo> // someRoute#section route does not exist 

Does anyone know of a way of getting this to work. I am using Ember Octane so I can use anything available in there to help.




samedi 15 juin 2019

Why will my web app not send data to my google firebase database?

My web app using ember.js will not send data to the google firebase realtime database

I have viewed multiple tutorials and searched the web and cannot seem to find the answer to my problem. I am using ember v 3.10

actions: {

saveInvitation() {
  const email = this.get.emailAddress;

  const newInvitation = this.store.createRecord('invitation', { email });

  newInvitation.save().then(response => {
    this.set('responseMessage', `Thank you! id: ${response.get('id')}`);
    this.set('emailAddress', '');
  });

},

}

import DS from 'ember-data';

export default DS.Model.extend({

email: DS.attr('string'),

});




How can I access an element of an associative Array in handlebars with dynamic id?

I am currently trying to access an associative array inside of an emberjs handlebars file. Accessing through hardcoded values is no problem, but I want to get the element based on a dynamic "index".

The code I have so far is


  <Ambientsound @buttonActive= @sound= @updateFunction=/>


and the relevant section of the controller is:

soundPlayers: {"Bells":100,"Fireplace":30}

The code I have above works perfectly fine, but now I am trying to access the soundPlayers.[...] based on the value of sound.id, like so:


  <Ambientsound @buttonActive= @sound= @updateFunction=/>


The Value in sound.id is passed as a string and there's nothing I can do about that.

How can I cast sound.id into something that allows me to access the array, or phrase the handlebars query in a way so I can get the result from the array? I could also consider reshaping the array I have in my controller. Anything that helps is welcome!




How to handle a CSS property of clicked object in Ember?

Tell me please, how to handle onclick action by ID. For example, i’ve something in hbs template:

<button id="myButton"  >OK</button>

it has CSS:

button {color: "red";}

How to do two things by onclick action:

1. Set property to clicked object (only to clicked), eg to set CSS colour “green”,
2. Get some property of clicked (eg CSS colour), and console log or alert.

Thanks in advance!




How to pass data from different models to component in Ember?

I have a little question in Ember. There is several routes that receive data from several JSON files, and one component where the data is to be passed. Here is a JSON file named 'data':

[
  { "name": "Mike", "age": "15"},
  { "name": "John", "age": "25"},
  { "name": "Alex", "age": "30"}
]  

I have a route that get data from this JSON and retirns it:

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

export default Route.extend({
  model() {
    var data = fetch('/data/fbbmd.json').then(function (response) {
      return response.json();
    }); 
    return data;
  }
});   

and the component hbs template:

<h5><i></i></h5>        

And we have another JSON and another route, and a third JSON and a third route and so on, and the one component averywhere. Maybe my construktion is wrong, and I should'nt use the model in route, or another, so tell me please, how to pass data from JSON to component template?




vendredi 14 juin 2019

How to use functions, events and html DOM in ember?

I,m studying Ember, and I have a few questions to understand the basic principles. I believe that this concerns the key points. Let me show you a little code, which is the boilerplate for me with typical tasks. There is an onclick functions, data recieving from JSON, change an attributes of html using the received data. These are the tasks that I want to understand most of all, and I will be very grateful to you for any help! Please tell me how to implement all of this in the spirit of Ember? I need to get the same result that will be reused in several routes, that is, different JSON will be processed. Perhaps the code should be contained in the component, but I could be wrong. I really like Ember, everything is in its place here, and I really would like to figure out in which parts of Ember it needs to be separated (for example, the hbs template, the route and other parts that are needed), so what where should be placed. I find it difficult to explain, but I think you will understand me. Great thanks in advance for any help! Excuse me my french)

Here is listing:

    <!DOCTYPE html>
    <html lang="en">

    <body>
      <script src="data.json"></script>

      <div class="container">
        <div class="wrapper">
          <div id="items" style="display: flex; justify-content: space-between;">
            <div id="a" onclick="getData(this.id)" style="width: 100px; height: 100px; background-color: coral"></div>
            <div id="b" onclick="getData(this.id)" style="width: 100px; height: 100px; background-color: coral"></div>
            <div id="c" onclick="getData(this.id)" style="width: 100px; height: 100px; background-color: coral"></div>
            <div id="d" onclick="getData(this.id)" style="width: 100px; height: 100px; background-color: coral"></div>
            <div id="e" onclick="getData(this.id)" style="width: 100px; height: 100px; background-color: coral"></div>
          </div>

          <br><br>

          <select name="getValues" id="getValues" style="display: block;">
            <option value="first">First values</option>
            <option value="second">Second values</option>
          </select>

          <br><br>

          <button onclick="setData()" class="waves-effect waves-light btn-large xbutton">SELECT</button>
        </div>
      </div>


      <script> 
        function getData(clicked_id) {
          let selectValue = document.getElementById("getValues").value;
          alert("Value = " + parseFloat(data[selectValue][clicked_id]));
        }

        function setData() {
          let selectValue = document.getElementById("getValues").value;
          for (x in data[selectValue]) {
            let n = data[selectValue][x];
            if (n < 15)
              document.getElementById(x).style.backgroundColor = "red";
            if (n >= 15 && n < 50)
              document.getElementById(x).style.backgroundColor = "green";
            if (n >= 50 && n < 100)
              document.getElementById(x).style.backgroundColor = "blue";
            if (n >= 100)
              document.getElementById(x).style.backgroundColor = "yellow";
          }
        }
      </script>
    </body>

    </html>

Here is JSON file:

    var data = {
      "first": {
        "a": 14,
        "b": 37,
        "c": 117,
        "d": 893,
        "e": 11
      },
      "second": {
        "a": 89,
        "b": 777,
        "c": 9,
        "d": 3,
        "e": 57
      }
    };




jeudi 13 juin 2019

Ember: Assertion Failed: EmberObject.create no longer supports defining computed properties

I was on Ember version 2.16 and we upgraded to 3.8. After version upgrade I am seeing this error but not able to figure out from where the error is coming. In what scenarios will I get this error. I saw one of the post:

Dynamic computed properties in Ember.JS deprecated?

But couldn't figure out the same in my code. Please if anyone can help me with this. It's urgent and any leads will be appreciated.

enter image description here




How can I combine ember-bootstrap and ember-autoresize?

I would like to add the attribute autoresize=true to a textarea that is drawn using ember-bootstrap in order to use ember-autoresize.

As you can see here, this attribute is not bound, so I cannot simply add it to my template.

I've tried to manipulate the yielded control like so:


    
        
    


But this only works for classNames, not attributes.

What is the simplest way of achieving what I'm trying to do?




EmberJS template component suddenly not rendering on page

I'm following this Ember tutorial and I've suddenly run into an issue where my rental-listing.hbs template component stops rendering. It started when I began implementing the map service.

I don't understand where this could be happening. I've copied the code from parts of the GitHub repository that I thought were relevant but to no avail.

I have a rental.hbs template that looks like so:

<div class="jumbo">
  <div class="right tomster"></div>
  <h2>Welcome!</h2>
  <p>We hope you find exactly what you're looking for in a place to stay.</p>
  
    About Us
  
</div>


Which in turn has a template component called rental-listing.hbs:

<article class="listing">
  <a
    onclick=
    class="image "
    role="button"
  >
    <img src= alt="">
    <small>View Larger</small>
  </a>
  <div class="details">
    <h3></h3>
    <div class="detail owner">
      <span>Owner:</span> 
    </div>
    <div class="detail type">
      <span>Type:</span>  - 
    </div>
    <div class="detail location">
      <span>Location:</span> 
    </div>
    <div class="detail bedrooms">
      <span>Number of bedrooms:</span> 
    </div>
  </div>
  <LocationMap @location=/>
</article>

The only thing I have added to the above is the line <LocationMap @location=/> but it still doesn't work if I remove it.

The console shows me no errors and I can actually see I am getting the three dummy objects I want from Mirage:

Return

So I'm definitely getting the objects and from what I see I'm doing everything necessary in the templates to render it but they aren't. Should I be looking somewhere else?




mercredi 12 juin 2019

Ember Serializer works for either the model or the model through relationship, but not both

I have a Rails API connecting to Ember

I have a many-to-many relationship with Doctor has_many patients and Patient has_many doctors .

**Here is my doctor model

export default Model.extend({
  // Attributes
  name: attr('string'),
  address: attr('string'),
  patients: hasMany(‘patient')
});

**Here is my patient model

export default Model.extend({
  // Attributes
  name: attr('string'),
  issue: attr(‘string’),
  age: attr(’number’),
  visits: attr(‘number’),
  doctors: hasMany(‘doctor’)
});

The Doctor data displays perfectly when calling it.

Here is my issue based on the patient serializer

export default JSONAPISerializer.extend({

});

If I leave it blank like above Doctor.patients data displays great, but if I try to display all patients without Doctor it shows any attr number as undefined.

If I add a method to decamilze like this

export default JSONAPISerializer.extend({
     keyForAttribute: function(key) {
      return decamelize(key);
    },
});

When adding the decimalize - showing all patients data by themselves now works great, but Doctor.patients data does not display. Instead the number attr are now undefined.

Is there a way to only use decamilize for patients and not for the relationship through Doctor?




Is there a way to generate the original code when we only have the build files?

I have an old EmberJS project, I misplaced the code and now only have its build on the production server. Is there a way to revert the build to recover the code, if not completely then to some extent maybe.




Ember Octane and JQuery

For the past few weeks i've been playing with ember octane which in my opinion is awesome. I've tried a few ember plugins in order to test which plugins are working currently with ember octane, some of them require jQuery to work. So my question is: if it's possible to add jQuery to ember octane to make those plugins work?




mardi 11 juin 2019

How to use ember-apollo-client?

I am trying to use graphql through apollo-client. On frontend there is Ember, on backend we have django and graphql server, implemented on this tutorial (https://www.howtographql.com/graphql-python/0-introduction/). The Ember application is on 4200 port, the graphql server is proxied on 8000/graphql (ember s --proxy http://localhost:8000)

I tried to follow this guide (https://www.howtographql.com/ember-apollo/1-getting-started/), but without graphcool, because we have backend.

In a controller signup.js I have

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import Mutation from '../gql/mutation';

I have injected apollo this way

export default Controller.extend({
    apollo: Ember.inject.service(),

And the mutation is this

actions: {
    signUp() {
        let username = this.get('username');
        let password = this.get('password');
        let email = this.get('email');
        const credentials = { username, password, email };
        let mutation = Mutation.CREATE_USER;

        return this.get('apollo').mutate({mutation, credentials}, 'createUser').then(() => {
        this.set('username', '');
        this.set('email', '');
        this.set('password', '');
        console.log('user created successfully!');
    }).catch(error => console.log('ERROR!!!!111:', error));

After clicking submit button in a form, I got this message

POST http://localhost:4200/graphql 500 (Internal Server Error)
ServerParseError: Unexpected token < in JSON at position 0

What can I do?




EmberJS, Webstorm and Windows - Cannot run through Ember Serve configuration

I've created an ember-quickstart application from ember-cli and it loads successfully in my browser with ember serve. I've imported the project into WebStorm and tried to set up a configuration under option Ember Serve like so:

enter image description here

However, when I try to run the project I get the following error:

C:/DEV/nvm/v10.16.0/node C:/DEV/Projects/ember-quickstart/node_modules/.bin/ember serve
C:\DEV\Projects\ember-quickstart\node_modules\.bin\ember:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Process finished with exit code 1

Is there a way to fix this or do I have to run the server from the command line each time?




lundi 10 juin 2019

Grunticon cannot read cssRules when using svgLoadedCORSCallback

I am using grunticon in an ember-cli project. I am using an external stylesheet for the icons so I have followed the docs to get SVG Embedding across domains working.

The embedding does work on the first page load but it stops working when changing routes. I found some help here where they suggested adding

grunticon.embedIcons(grunticon.getIcons(grunticon.getCSS(grunticon.href)))

to didTransition in router.js but the throws this error:

Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
    at Function.i [as getIcons]

This works if I am using the CSS locally but when I change to cross domain this is the result.




Ember : Hook for css property change

I have to render a lot of divs into DOM. So, what I did is I render the first 5 elements into the DOM first after that I render every 10 divs with 300ms interval period.

The problem is when I change into display: block I need to change something in the component. So, I try to use didRender hook for that.

Code is below

didRender() {
   if(this.element.offsetParent) {
      this.set('myvar', true);
   }
} 

But it's not working perfectly. Anyone please suggest me which is the best way to do this.

_Thanks in Advance.




dimanche 9 juin 2019

How to handle a var / const in the EmberJS controller?

I have a game controller, there is a setPause method and there is const statusPause = true / false, how can I access const statusPause from other files, services, etc. To perform some checks depending on the state of the game? If you do this in any file, undefined is returned instead of bool.

let game = require('../controllers/game');
console.log(game.setPause.statusPause);




jeudi 6 juin 2019

paper-select showing behind bsmodal in Ember

I am rendering a form in a bs-modal where I have a paper-select with 5 items. When I click on the paper-select, the dropdown is appearing behind the bs-modal and is not useable.

I have attempted to give the specific paper-select a high z-index value, but it is still rendering behind the bs-modal.

How do I render a paper-select dropdown infront of a bsmodal?




Data corrupted when sending from template to component lifecycle method?

EMBER VERSION 3.10

DESCRIPTION

If I pass an array of objects from a template(after iterating the array in the template view) to a component and try to access the data in one of the lifecycle methods of the component. The data is corrupted.

CODE

controllers/application.js

import Ember from 'ember';

export default Ember.Controller.extend({
  users: [{name:1},{name:2},{name:3}]
});

templates/application.hbs


  <p></p>


<FilterUsers @users= />


templates/components/filter-users.hbs

empty file

components/filter-users.js

import Ember from 'ember';
export default Ember.Component.extend({
  init(){
    this._super(...arguments);
    console.log(this.get('users'));
  }
});

OUTPUT

with bug

enter image description here

without bug

If i removed each block from application.hbs which iterates the array. I get proper results.

templates/application.hbs

<FilterUsers @users= />


enter image description here

I'm new to ember, so is it a bug or am i not doing the ember way ?




mercredi 5 juin 2019

How do I deprecate a feature in my addon?

I am writing an Ember.js Addon, and I need to deprecate a feature. Can I use the same deprecation system that Ember uses? I want my users to be able to silence the warnings.

Ideally, I also need to be able to test that the deprecation message works under the right conditions, from within my test suite.

I'm using Ember 3.x.




Ember Data: Change model data in component and write it back to API

I'm learning ember.js right now and having trouble to understand how editing model data works. I have a simple model called singleitem:

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

There's a template singleitem.hbs that uses a template component interface_text.hbs containing this line:

<input type="text" value="" />

And a corresponding interface_text.js component:

export default Component.extend({
    change() {
        console.log(this);
    }
});

Whenever I change the content of the <input> tag, the change() method fires, so this works. But how do I update the model with the new value of the <input>?

(My ultimate goal is to write the changed data back to my API. Using this.test.save(); initiates a PATCH request to my API, but sends back the unaltered data. So I think I have to change the model first.)




mardi 4 juin 2019

How to play video with sound on user-initiated event before video element is added to DOM? iOS Safari/Chrome/Webkit

I have two elements in the DOM: 1) Viewer Window (shows a large image or video) 2) grid of thumbnails (representing videos or images).

When the user clicks on the corresponding thumbnail for a video, the video should load into the viewer window and begin playing with sound on mobile/ios/android. I am testing specifically on iOS safari.

I am aware of the webkit policies on user-initiated events, requiring videos to be muted unless the user explicitly clicks on things (which is the action I am doing here), but am having troubles understanding the specific implementation details.

A note about the user gesture requirement: when we say that an action must have happened “as a result of a user gesture”, we mean that the JavaScript which resulted in the call to video.play(), for example, must have directly resulted from a handler for a touchend, click, doubleclick, or keydown event. So, button.addEventListener('click', () => { video.play(); }) would satisfy the user gesture requirement. video.addEventListener('canplaythrough', () => { video.play(); }) would not.

I believe the issue for me is that the video element is not added to the dom until the next render loop. Even though the user is initiating the event by clicking on the thumbnail to play the video, webkit isn't recognizing it as a user-initiated event and blocking playing the video because it has sound.

User Click:

    updateCurrentItem(item) {
      set(this, "currentItem", item);

      this.videoManager.playWhenLoaded.perform(item);
    }

videoManager.playWhenLoaded is an ember-concurrency task. When a video is loaded to the dom, it registers itself with the videoManager service.

  playWhenLoaded: task(function*(item) {
    let id = item.id;
    while (this.videos.findBy("modelId", id) === undefined) {
      yield timeout(200);
    }

    let video = this.videos.findBy("modelId", id);
    video.player.muted = false;
    video.player.play();
  })

Could you please explain to me why this doesn't work? and what strategies might I attempt to get it to work for my use-case?




Auto-generated tests for an ember component fail for the block-form

(Ember 3.10) I have added the ember-drag-drop addon and then created a component as a wrapper for it, with a yield field that simply makes any content I pass to it draggable. However, the auto-generated test that was created using the 'ember generate component' command does not work with the component I created. The block form test fails because 'this.element.textContent.trim()' is empty and the assert expects the text written inside the block form.

The component works when I run the app, the component shows and it works just as expected. h However, I suspect I cannot access the textContent of the created element in the test function because of the nested structure of the components. I have attempted accessing the child element of the component, and it identifies a text object that has no text inside. I have also tried seeing what classes there are for the element, and it only sees 'ember-view' and nothing about the 'draggable-object' class I would expect to see if I use the draggable-object component from the addon. Maybe the thing that causes it to fail is the test not knowing about that addon, maybe I need to include it somehow? Although I expect it to be included if it can render a component that uses that addon without crashing.

The component I have generated is called "draggable", there is no JS functionality, just a handlebars template that looks like this:


  


The test for the block form looks like this:

await render(hbs`
      
        test
      
    `);

assert.equal(this.element.textContent.trim(), 'test');




lundi 3 juin 2019

In EmberJS how can you use transition data in a controller?

I am getting the transition data in the route js file like so:

beforeModel(transition) { console.log(transition)  }

And I want to use it in a function in my controller like this:

import Controller from '@ember/controller';

export default class ListingsController extends Controller {

    get pageTitle() {
        if (this.transition.targetName == 'foo') {
        return 'page title';

        }
      }

}

And then I want to display the result like this:

<h1></h1>

I cannot find a way to pass the transition data from the route to the controller. Any ideas?




dimanche 2 juin 2019

Is there any way to run ember acceptance test case in slow mode?

I have written some ember acceptance test cases. The thing is when I visit the URL http://localhost:4200/tests and filter module by Acceptance, the test cases are running lightning fast. Even though those were written in async await function.

I want to put a time delay for each line using ember run loop run.later or run.next. But that's not the solution.

Is there a way to add slow mode somewhere in the top of the application (or) Is there any test helpers which is already present? So I can see test cases running in action.