lundi 30 avril 2018

Redirecting in EmberJS

I'm relatively new to EmberJS, so any help is appreciated. I'm trying to do something I feel should be theoretically simple - I have a component and on one of the DOM elements, I want to have a click handler which redirects to a route, but I've been unable to figure out how to make that happen.

I have my component: //components/sample-card-header.js

import Component from '@ember/component';
export default Component.extend({
  actions: {
    goToSamples() {
      this.transitionTo('samples');
    }
  }
});

And my handlebars template:

//templates/components/sample-card-header.hbs

<div class="card_header" >Samples</div>

I know I can just do: <div class="card_header" onClick="window.location.href=('/samples')" > but I'd like to use the router paths.

Thanks in advance




Deployed Ember App uses 100%+ CPU

I use Ember for a number of my websites. Over the last several months, one of my websites started maxing out the CPU usage of Safari and Chrome web browsers, but not in Firefox.

enter image description here

I have both a staging and production deployment using ember-cli-deploy to an AWS S3 bucket. At first, the maxed CPU usage was only occurring on my production website. About a month ago, I changed my production build to run under a different environment name "prod" and the issue went away. However, this last week the issue has come back.

Note, this issue does not happen in my local environment.

Any help/guidance is greatly appreciated.




undefined UUID when import ember-cli-uuid

I have added ember-cli-uuid (0.4.1)in my package.json. here is a how my dependencies look like.

  "devDependencies": {
    "autoprefixer": "^6.5.0",
    "broccoli-asset-rev": "^2.4.5",
    "chai": "3.5.0",
    "chai-jquery": "^2.0.0",
    "ember-browserify": "1.1.13",
    "ember-can": "~0.8.1",
    "ember-cli": "2.12.3",
    "ember-cli-app-version": "^2.0.0",
    "ember-cli-babel": "^5.1.7",
    "ember-cli-chai": "0.4.3",
    "ember-cli-code-coverage": "0.3.12",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-dotenv": "^1.2.0",
    "ember-cli-frost-blueprints": "^5.0.2",
    "ember-cli-htmlbars": "^1.1.1",
    "ember-cli-htmlbars-inline-precompile": "0.3.12",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-mirage": "0.2.5",
    "ember-cli-mocha": "0.14.4",
    "ember-cli-page-object": "1.6.0",
    "ember-cli-sass": "7.1.1",
    "ember-cli-shims": "^1.0.2",
    "ember-cli-uglify": "^1.2.0",
    "ember-cli-uuid": "0.4.1",
    "ember-css-modules": "~0.5.0",
    "ember-data": "2.8.1",
    "ember-data-model-fragments": "~2.3.1",
    "ember-export-application-global": "^1.0.5",
    "ember-faker": "1.1.0",
    "ember-fetch": "1.6.0",
    "ember-load-initializers": "^0.6.0",
    "ember-pollboy": "^1.0.1",
    "ember-resolver": "^2.0.3",
    "ember-sinon": "^0.7.0",
    "ember-source": "~2.12.0",
    "ember-test-utils": "^8.1.1",
    "loader.js": "^4.2.3",
    "lodash-es": "4.17.4",
    "postcss-nested": "~1.0.0",
    "postcss-scss": "0.4.1",
    "pr-bumper": "3.2.3",
    "sinon-chai": "^2.14.0"
  },

and here is how my bower.json dependencies looks like:

  "dependencies": {
    "remodal": "1.0.7"
  },
  "devDependencies": {
    "Faker": "^3.1.0",
    "jquery-mockjax": "2.2.1"
  }

i tried to import it into my util file and use it in my polling

import {uuid} from 'ember-cli-uuid'

export function pollTask (generator, options = {}) {
...
  const id = uuid()
...
}

But i get the following error and uuid (window.uuid) is undefined.

    TypeError: Cannot read property 'v4' of undefined
     at pollTask (planning-ui.js:12556)
     at Module.callback (planning-ui.js:11185)
     at Module.exports (vendor.js:111)
     at requireModule (vendor.js:32)
     at Class._extractDefaultExport (vendor.js:342878)
     at Class.resolveOther (vendor.js:342575)
     at Class.superWrapper [as resolveOther] (vendor.js:60513)
     at Class.resolveRoute (vendor.js:25111)
     at Class.resolve (vendor.js:24955)
     at resolve (vendor.js:22354)

I am not sure what i am doing wrong. I appreciate if someone can help me. I am trying not to use ember-simple-uuid.




dimanche 29 avril 2018

Emberjs / ember-browserify : "X is not a constructor"?

This question relates to my earlier question.

Trying to use howler.js (https://github.com/goldfire/howler.js#documentation) in a Controller.

There is no addon for Howler but it exists as a npm package.

I've followed the instructions to use ember-browserify and then started the ember dev server (ember s).

The import looks like this :

import Howl from "npm:howler";

I've also tried this :

import {Howl as Howl} from "npm:howler" ;

and this :

import {Howl} from "npm:howler" ;

In all cases when I attempt to make use of Howler like this :

var sound = new Howl({
    src: ['https://example.com/foo.mp3']
});
sound.play();

I get an error in the console (first import shown above) :

Uncaught TypeError: _npmHowler.default is not a constructor

or (second and third import shown above) :

Uncaught TypeError: _npmHowler.Howl is not a constructor

The example code for Howler is here and as far as I can see what I'm doing is in line with those examples.

Any suggestions welcome.


FWIW: this is the same body of code as is mentioned here but since that question I've moved onto using ember-browserify




samedi 28 avril 2018

How do I keep website content translated even after navigating to another page? (ember.js ember-i18n)

I'm currently implementing multiple languages into a web app using ember-i18n and am looking for a way in which visitors and users can choose which language they want at any time.

I'm following a tutorial found here, creating a drop down menu which toggles the content's language on the web page that the menu is on. It manages to toggle the page's language without refreshing.

However, when I navigate to a new page or refresh the current one, the language reverts back to the default.

How can I configure the web app so that the selected language remains active while navigating the site? Do I need to add something extra like including cookies?

The menu and the current environment is setup is as follows:

config/environment.js

module.exports = function(environment) {
    var ENV = {
        ...

        i18n: {
            defaultLocale: 'en'}
        };
        ...
    }
}

app/app.js

App = Ember.Application.extend({
    locale: 'es',
    ...
});

app/components/language.js

import Ember from 'ember';

export default Ember.Component.extend({
    i18n: Ember.inject.service(),
    classNames: ['language-select'],

    locales: Ember.computed('i18n.locale', 'i18n.locales', function() {
        const i18n = this.get('i18n');
        return this.get('i18n.locales').map(function (loc) {
            return { id: loc, text: i18n.t('language-select.language.' + loc) };
        });
    }),

    actions: {
        setLocale() {
            this.set('i18n.locale', this.$('select').val());
        }
    }
});

app/templates/components/language-select.hbs

<select >
    
        <option value="" selected=>
            
        </option>
    
</select>

app/helpers/is-equal.js

import Ember from "ember";

export default Ember.Helper.helper(function([leftSide, rightSide]) {
    return leftSide === rightSide;
});

app/index.hbs

...
<p></p>
...

Additionally, I have my locales.




vendredi 27 avril 2018

Ember JsonApi Serialize override normalizeResponse. How to interpret the parameters

I use the JsonApiSerializer in JSON and I want to override standard behavior. I want to behavior to be different for certain models. Therefore I would like check the paramter primaryModelClass, but how do I interpret that parameter. I have tried to inspect it but all I get is "unknown mixin".

I have looked at the documentation here:

https://emberjs.com/api/ember-data/3.0/classes/DS.JSONAPISerializer/methods/normalizeResponse?anchor=normalizeResponse

I have this piece of code

import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
    normalizeResponse: function(store, 
                                primaryModelClass, 
                                payload, id, requestType) {
    console.log(primaryModelClass.toString());
...

It outputs (unknown mixin)

How do I fint the model type in the normalizeResponse method?

I use Ember 3.0.




jeudi 26 avril 2018

How to dry route actions with component in EmberJS

(EmberJS 2.14)

I want to have DRY apps with ember, however, it seems it is impossible to do with route actions. When I try to use a component for the button triggering the action it fails :

new.js :

  export default Ember.Route.extend({
      model() {.....},
      actions: {
          saveStuff(newStuff) {
            newStuff.save().then(() => this.transitionTo('stuffs'));
          }

new.hbs



Error :

Assertion Failed: An action named 'saveStuff' was not found in (generated Stuffs.new controller)

I have the same problem with the delete action and the update action. I can't resign myself to have the same code and template lines in every routes and views that needs it.




how to find modal has scrolled to the end -EmberJS

i'm newbie to emberJS and i want to enable a button when it comes to the scroll end in a modal. so i tried several ways but it didn't work

View

<div class="modal--dialog--body">

    <div class="app_tour--section--terms_container" id="message-container">

      <ul class="app_tour--section--ul">
        <li></li>
           //so many lists to scroll
        <li></li>
     </ul>
</div>

Controller

 import Ember from 'ember';
export default Ember.Controller.extend({

  didTransition() {
    Ember.run.later('afterRender', () => {
      let objDiv = document.getElementById("message-container");
      if(objDiv.scrollTop == objDiv.scrollHeight)
      console.log(objDiv.scrollTop)
    }, 100);
    return true;
  },


  actions: {

    close: function() {

      this.send('closeModal');
    }
  }
});




mercredi 25 avril 2018

Ember Data query filtering doesn't work with Firebase

Suppose that I have the following data in Firebase Database

{
  "carros" : {
    "-LAy3Qqrvq_sIhyLJQED" : {
      "añoFabricacion" : 1932,
      "marca" : "toyota",
      "nombre" : "nombre1"
    },
    "-LAy3r-Gm_NWW9_VkGR3" : {
      "añoFabricacion" : 1931,
      "marca" : "audi",
      "nombre" : "nombre2"
    },
    "-LAy3v9L2wecTDZqpok9" : {
      "añoFabricacion" : 1934,
      "marca" : "toyota",
      "nombre" : "nombre3"
    }
  }
}

I want to print in console the attribute "nombre" of the objects whose "marca" attribute is equals to "toyota". I wrote a controller code as follows:

import Controller from '@ember/controller';

export default Controller.extend({
  actions: {
    mostrar() {
      this.get('store').query('carro', {
        filter: {
          marca: 'toyota'
        }
      }).then(function(carros) {
        carros.forEach(function(carro) {
          console.log(carro.get('nombre'));
        })
      });
    }
  }
});

And the corresponding code for the model "carro.js" is:

import DS from 'ember-data';

export default DS.Model.extend({
  nombre: DS.attr('string'),
  marca: DS.attr('string'),
  añoFabricacion: DS.attr('number')
});

The problem is that I am obtaining the following output:

nombre1
nombre2
nombre3

But the correct output must be:

nombre1
nombre3

Why I am getting this error?




mardi 24 avril 2018

Ember promise - accessing value

I am working on an Ember application..

I have a service that looks like this

let downloadMethod = this.get('service1')
  .fetch(id)
  .then(res => {
    console.log("res", res.agenda.method.value)
    res.agenda.method.value
 });

console.log("downloadMethod", downloadMethod);

when I try to access this -- the console log for downloadmethod shows a promise -- but inside the then -- res comes out as the string value I need.




lundi 23 avril 2018

How to import a custom library to Ember via npm

Despite what seems like a plethora of blog posts about it, I am still struggling to perfect using a custom library as a dependency for my ember application through npm.

I have written a WebGL library and currently have it importing into my Ember app by installing it via npm from a private repository. This currently works and is in production but the workflow is somewhat clunky. The library is written using NodeJS modules (require -> export.modules). Currently I am just using babel on my src files which results in a build folder with the ES5 versions of the files still separated.

I then have an index file that looks like this:

var Helper = require('./com/XXXX/utils/Helper');
module.exports = {
  Module1: require('./com/XXXX/media/Module1'),
  Module2: require('./com/XXXX/media/Module2'),
  Module3: require("./com/XXXX/media/Module3"),
  Module4: require('./Module4'),
  Module5: require('./com/XXXX/media/Module5'),
  Module6: Helper.Module6,
  Module7: Helper.Module7
};

Using npm I can install this build directory into my Ember app and import the modules I need using the following syntax:

import webglRenderLibrary from 'npm:webglRenderLibrary';
const { Module5 } = webglRenderLibrary;

Where Module5 is a class in the library exported like this:

class Module5 {
  //Magic rendering code
}
module.exports = Module5;

I didn't have to install any other plugins or import the library-files to the ember vendor file as so many blog posts say you have to in order to get this to work. I don't really understand why this method works but it does.

¯\_(ツ)_/¯

I've never really liked this setup/workflow though (and not knowing why it works) so I'm trying to improve it but the many knowledge gaps I have in Ember, JS modules and so on are making it difficult.

The first thing I wanted to do was move the library over to ES6 modules (import -> export). From what I understand ES6 modules are leaner and the future so I would rather use them for my library. Changing all the source code was a little labour intensive but it works nicely and allowed me to create a nice workflow for my library development.

Module5 now looks like this:

export default class Module5 {
  //Magic rendering code
}

In the package.json of the library I have a number of npm scripts now calling watchify so I can test my modules in demo files individually.

{
  "name": "webglRenderLibrary",
  "main": "dist/js/app.js",
  "version": "2.0.5",
  "author": "JibJab Media",
  "description": "WebGL Render Library",
  "repository": "private.git",
  "scripts": {
    "watch-sass": "sass --watch src/scss/app.scss:demo/css/app.css",
    "watch-js": "watchify src/js/index.js -t babelify -o dist/js/app.js -dv",
    "watch-module1": "watchify src/js/demos/Module1Demo.js -t babelify -o demo/js/Module1Demo.js -dv",
    "watch-module2": "watchify src/js/demos/Module2Demo.js -t babelify -o demo/js/Module2Demo.js -dv",
    "watch-module3": "watchify src/js/demos/Module3Demo.js -t babelify -o demo/js/Module3Demo.js -dv",
    "watch-module4": "watchify src/js/demos/Module4Demo.js -t babelify -o demo/js/Module4Demo.js -dv",
    "watch-module5": "watchify src/js/demos/Module5Demo.js -t babelify -o demo/js/Module5Demo.js -dv",
    "watch-module6": "watchify src/js/demos/Module6Demo.js -t babelify -o demo/js/Module6Demo.js -dv",
    "watch": "npm run watch-sass & npm run watch-module1 & npm run watch-module2 & npm run watch-module3 & npm run watch-module5 & npm run watch-module5 & npm run watch-module6",
    "build-sass": "sass src/scss/app.scss:dist/css/app.css --style compressed",
    "build-js": "browserify src/js/index.js -t [ babelify --presets [ \"env\" ] ] | uglifyjs -mc > dist/js/app.js",
    "build": "npm run build-js & npm run build-sass",
    "test": "mocha --require babel-core/register",
    "test-coverage": "nyc mocha --require babel-core/register"
  },
  "browserify": {
    "transform": [
      "babelify"
    ]
  },
  "dependencies": {
    "babel-preset-env": "1.6.1",
    "babelify": "^7.2.0",
    "opentype.js": "0.8.0"
  },
  "devDependencies": {
    "babel-cli": "*",
    "mocha": "5.0.5",
    "nyc": "11.6.0",
    "watchify": "3.11.0"
  },
  "bugs": {
    "url": "private/issues"
  },
  "homepage": "private#readme",
  "private": true
}

I bring this all up to point out that my conversion to ES6 modules has gone smoothly. My test Js files for the individual modules compile and babelify nicely; I can run them in test HTML files and the WebGL renders correctly.

Now, here is where my knowledge gets kind of fuzzy.

The library contains 7 modules I want to expose so that the Ember App can use them. So, I have an index.js file in the library which simply imports each of the modules then exports them. (Please let me know if this is not the way to do this)

import Module4              from './Module4';
import Module1              from './com/XXXX/media/Module1';
import Module2              from './com/XXXX/media/Module2';
import Module3              from './com/XXXX/media/Module3';
import Module5              from './com/XXXX/media/Module5';
import { Module6, Module7 } from "./com/XXXX/utils/Helper";

export { Module1, Module2, Module3, Module4, Module5, Module6, Module7 };

From my understanding, this allows me to have browserify/babelify transpile my ES6 module library into something that Ember can consume. In the libraries package.json I have a 'build' script which runs browserify, babel and uglify to mash my whole library into one minified file in dist/js/app.js which is the entry point under main in the libraries package.json.

I was thinking that this should really be the same code which is currently working in my Ember app. The only difference should be that it has been put into a single file by browseridy and minified with Uglify (Please correct me if I'm wrong, which I think I am). I thought I wouldn't have to make any changes to my Ember app but now I'm getting:

Uncaught TypeError: Module5 is not a constructor

while importing it the way I did before:

import webglRenderLibrary from 'npm:webglRenderLibrary';
const { Module5 } = webglRenderLibrary;

All of this being said leads me to several questions:

  1. Why does my original strategy of simply babeling my src code and importing it as described work while so many blog posts talk about using brocolli and importing it to the vendor file. Example
  2. If the original strategy worked, why didn't my change to the new library structure work as well. I'm guessing it's because browserify changes something about the NodeJS module exports but my knowledge here is fuzzy.
  3. For creating a library with multiple modules to export, is it correct/necessary to export them from a single index file as I have done? If not then how do other libraries expose their modules to Ember (example lodash)
  4. I've seen a number of plugins/packages which claim to allow the import of ES6 modules into ember. For example ember-cli-es6-transform. I could not get this to work with my library. Has anyone had success with something like this for a setup similar to mine? How did you make it work?
  5. If you were creating a custom library to import to an ember app, how would you do it?



Ember get data from MongoDB with NodeJS

I have a MongoDB server which has a NodeJS server to interact with it. I want Ember Store to get data from this server. A tutorial has led me until this point but it does not work for me (tutorial), I think it is outdated but I am not sure. This part of the backend server is about sending data:

app.get('/api/appointments', function(req, res){
    AppointmentModel.find({}, function(err, docs){
        if(err) res.send({error:err});
        else res.send({data:docs, "type":"appointment"});
    });
});

A curl request proves that it does work:

curl http://localhost:4500/api/appointments
{"data":[{"flags":[],"dates":[],"invited":[],"_id":"5adc8b6724a69f4327c4c7af","author":7,"title":"Does this work"}],"type":"appointment"}

This is the part of the ember code that makes the request to the server:

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

This is the error I get in the console of the webbrowser(chrome):

Error while processing route: index Assertion Failed: Encountered a resource object with an undefined type (resolved resource using (unknown mixin)) Error: Assertion Failed: Encountered a resource object with an undefined type (resolved resource using (unknown mixin))
    at new EmberError (http://localhost:4200/assets/vendor.js:24475:25)
    at Object.assert (http://localhost:4200/assets/vendor.js:24725:15)
    at Class._normalizeResourceHelper (http://localhost:4200/assets/vendor.js:85052:61)
    at Class._normalizeDocumentHelper (http://localhost:4200/assets/vendor.js:84993:25)
    at Class._normalizeResponse (http://localhost:4200/assets/vendor.js:85121:36)
    at Class.normalizeArrayResponse (http://localhost:4200/assets/vendor.js:86013:19)
    at Class.normalizeFindAllResponse (http://localhost:4200/assets/vendor.js:85873:19)
    at Class.normalizeResponse (http://localhost:4200/assets/vendor.js:85816:23)
    at normalizeResponseHelper (http://localhost:4200/assets/vendor.js:76037:39)
    at promise.then.adapterPayload (http://localhost:4200/assets/vendor.js:76889:19)

Because the error is something about types I checked and checked again the models but did not find anything that would give an error. Ember:

export default DS.Model.extend({
    author: DS.attr('number'),
    title: DS.attr('string'),
    description: DS.attr('string'),
    flags: DS.hasMany('number'),
    dates: DS.hasMany('date'),
    invited: DS.hasMany('number')
});

NodeJS/Mongo:

//The schema for appointments
var appointmentSchema = new mongoose.Schema({
    author: Number, //Userid of the owner of the appointment.
    title: String,
    description: String,
    flags: [Number], //Array of ids of flags that are set.
    dates: [Date],
    invited: [Number] //Array of user ids.
});
var AppointmentModel = mongoose.model('appointment', appointmentSchema);

In what special way does ember need the data in order to correcly handle it?

I have read some docs about store and ember but I am still new to the framework, any help is much appreciated.




dimanche 22 avril 2018

Looking for a work around for Ember Restriction "Error: Changing a view's elementId after creation

For our application , we have initial load with data. We use those data to generate dynamic id and classes. There are another api call we make to reload missing data. now the problem is if reload function bring different information, elementId complains that changing id is not allowed

like this(without api call) https://ember-twiddle.com/394755fd5b355dd93cd147d4610fbf5e?openFiles=controllers.application.js%2Ctemplates.components.my-component.hbs

now , is there a good work around for this issue keeping this logic?




Node.js Express Passthrough?

Hello ive got the following error:

 Failed to load https://site.eu.auth0.com/user/ssodata/: No 'Access- 
Control-Allow-Origin' header is present on the requested resource

In my development i used Ember.js with Mirage allowing me to do:

this.passthrough('https://site.eu.auth0.com/user/ssodata/');

Is there something similar in Node.js Express that will work how this.passthrough worked in Mirage? I am also using nginx.




Ember Calling method inside the controller

here is my code I have to call another method inside the Ember controller I was tried but this is not working I have confused in this...

please help me to what is wrong in this code?

export default Ember.Controller.extend({
....

getValue(){
var a = a * 2;
return a;
},

getResult(){
var result = this.getValue(); // result is not function 
}

});




vendredi 20 avril 2018

Linkedin Scrapping

I a begginer into scrapping and stuff, please be nice :^)

I´m using Python and seleniun to scrap data from Linkedin.

Problem: they use Ember and I am not able to click on "show more".

When I click on "show more", on the person skill or anything else, the XPATH have a dinamic id so the list will not appear. Example:

//*[@id="ember7924"]/button/span/li-icon/svg/path

But even the ones that dont use ember I am not able to use. Example:

//*[@id="org-about-company-module__show-details-btn"]/li-icon/svg/path

I tried using id, xpath class etc but it was not successful.

Does anyone have a clue? Thanks :)




How to redirect after Ember action completes inside component

So I'm brand new to Ember (using ember-cli 3.0.4), and trying to understand how to do what to me are normal things. I've a form, inside a component, where the user updates information, and clicks Save. I've built an action that the component calls when the Save button is clicked, and that action calls save() on the model object. So far, so good.

My problem is that I want to redirect to a different page when the save() promise completes. I can't figure out how to do that. The emberjs guide for actions doesn't once mention redirecting, and only the Routing module seems to have any mention of redirecting.

Obviously, there's an "embery" way of doing things that I don't know yet, but so far I can't figure out what that is. How are simple redirects after save done best in Ember?

Component code:

export default Component.extend({
actions: {
    saveCountry() {
        var self = this;
        if (this.country.get('hasDirtyAttributes')) {
            this.country.save().then(
                //???
            );
        }
    }
}

The Route code:

export default Route.extend({
model(params) {
    return this.get('store').findRecord('country', params.country_id);
}

});

Thank you!




Configure ember-cli version >= 3 to use native async/await and generators

How to configure ember-cli version >= 3 to use native async/await and generators without babel regenerator polyfill and async/await transpiling.




jeudi 19 avril 2018

Ember Cordova app stuck on loading screen in iOS 11.3

I have an app built with Corber for Ember-Cordova. Xcode version 9.3 cordova-ios@4.5.4 All dependencies updated to latest versions.

I'm testing on simulator as I don't have a development iPhone that can install iOS 11.

The app loads fine on iOS 11.2 and earlier - but on iOS 11.3 it gets stuck at the splash screen. After a while I see a loading icon, but the page never changes.

By analyzing with Safari as soon as the app starts loading, I can see that the the js scripts and the css are not being loaded from /www/index.html. This is what I see in the console log:

Cannot load script file:///Users/username/Library/Developer/CoreSimulator/Devices/07A01A47-573B-4D25-ABE3-AV9179985ABF/data/Containers/Bundle/Application/7976FE33-BLO3-21E9-A055-707AAC68468B/App%20Name.app/www/assets/vendor-e8t893cf6a6bg0f81f23d4a68ae6ffde.js. Failed integrity metadata check.

I've tried to find info on an 'integrity metadata check', and as far as I can see, it's being run by iOS to verify the checksum of the scripts being imported. In /www/index.html within Xcode I can see that the script tags have "integrity" properties, which are two checksums - one sha256, and one sha512. e.g.

<script src="assets/vendor-e8e903cf6a6bf0f81f23d4b68ae6ffde.js" integrity="sha256-MPm9fFc7ljuslonkMxW0TnQOAcy6KgJ4zLs+ptl/b58= sha512-oIqpQbUMPLBbSASoSCJ/+z55y2g6NlBzhTE3V+uDt8TNeJam5GAWoGT/D2u4ihIxE586JPu3c+r4GaUpjUWCAw=="></script>

So I guess what's happening is that somehow iOS 11.3 is checking the checksums of the files, comparing to their "integrity" property and not getting a match. Does anyone know what could be causing that to happen and how it could be fixed?

N.B. Although on the face of it this is about not being able to load resources, I don't think this is to do with the content security policy - I've tried several iterations of the content security policy in /www/index.html - most recently:

default-src * gap://ready file:; style-src 'self' 'unsafe-inline' *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *

None of those seem to have made a difference and I would expect to see an error related to content security policy if it was an issue.




Ember: modify model in a route

I am working on an Ember app and I am having issues. I have to filter out results at a certain point of app, say, in a controller or in a view, like this:

At view.hbs I am eliminating passed tests at ...:

<br>
    
        
    


I can do it at a controller that initially loads and can filter out in an input field:

import Controller from '@ember/controller';
export default Controller.extend({
    actions: {
        filterByTest: function (param) {
            if (param !== '') {
                return this.get('store').query('test', { name: param }).then((filteredTests) => {
                    return { query: param, tests: filteredTests.filterBy('passed', true) };
                });
            } else {
                return this.get('store').findAll('test').then((tests) => {
                    return { query: param, tests: tests.filterBy('passed', true) };
                });
            }
        }
    }
});

Now I need to filter out at a route level. model() in a route is can't be edited, if it can, then it has to be a path, which I don't want. How can I achieve that? How can I make model editable? At the moment I can get to the route model, but it can't be edited. Here's the way I talk to the model from view.hbs file and it works.

<br>
    


Please see below the model that returns file to above view.hbs template. Again, it is working:

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

export default Route.extend({
    model() {
        return this.get('store').findAll('test').then(tests => {
            return tests('passed', true);
        })
    }
});

How can I pass argument to the model and edit it, so that my UI gets changed as well?

This is my model I need to modify. At the moment the return works, but not modifiable.




Ember data bulk fetch async hasMany relationship records

I'd like to know whether it is possible to configure Ember data in a way that async hasMany relationships are loaded in a single request.

Given the following model:

// models/post.js
export default DS.Model.extend({
  comments: DS.hasMany()
});

// models/comments.js
export default DS.Model.extend({
  ...
});

When I reference the property comments somewhere in the template or controller, it will fetch the related comments of the post one-by-one in separate requests. This results in many requests and I'd like to combine those into a single request with a filter on id-property.




How to make template wait until route loads data controller depends on?

In a template i have a field:

Hello

And in the controller:

thisIsIt: function()
{
   return this.get("underdata").get("length") // 1
}.property('underdata')

And in router:

setupController: function(controller, model) 
{
   this.store.find('underdata', {id: 1 }).then(function(underdata) // 2
    {
        controller.set("underdata", underdata); // 3
    });
}

The order of call is: 2,1,3. So controller to satisfy template tries to get a length of underdata. But underdata is undefined, because 3 was not called yet. After throwing an error 3 is eventually called.

How to make controller wait until setupController gets the necessary data from underdata?




mercredi 18 avril 2018

Ember: How to get values of a file returned at Route->Model

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

export default Route.extend({
    model() {
        return this.get('store').findAll('rentals');
    }
});

The code above returns all rentals, say, 10 objects. Now, I want to get first, or last, or even multiple, but can't. Tried:

return this.get('store').findAll('rentals')[0];
return this.get('store').findAll('rentals').get(0);
return this.get('store').findAll('rentals').firstObject;
return this.get('store').findAll('rentals').slice(0, 2);
return this.get('store').findAll('rentals').splice(0, 2);




api response to model map in ember js

So I have a doubt regarding the ember data. My API returns a list of names (employee names), and when I make a query like this.get('store').query('employees') and try to see all the names returned, it is not getting printed. One of the possible reason which I thought was that ember is trying to map returned response to employee model and since returned response is just a list of strings, it is not able to map it correctly. Anyone has any idea what can be a possible fix for it, or is my understanding not correct?




mardi 17 avril 2018

Cannot call save a on an ember-data relation

I want to handle a relation in a component/form. It works fine when I create the relation, but it fails when I try to update

import Ember from 'ember';

export default Ember.Component.extend({
  store: Ember.inject.service(),
  init(){
    this._super(...arguments);
    var adresseField=this.get('adresseAttributeField');
    var parent=this.get('parent');
    if (parent.get(adresseField).content==null) {
      this.set('adresse',this.get('store').createRecord('adresse'));
    }else{
      this.set('adresse',parent.get(adresseField));
    }
  },
  actions:{
    saveAdresse(adresse){
      console.log(adresse);
      var parent=this.get('parent');
      var adresseField=this.get('adresseAttributeField');
      adresse.save().then(()=>{
        if(parent.get(adresseField)!=adresse){
          parent.set(adresseField,adresse)
          parent.save()
        }
      }),()=>{
      }
    }
  }
});

I think my problem is in the init when I retrieve the existing relation :

this.set('adresse',parent.get(adresseField));

However I cannot identify what's the problem exactly.




lundi 16 avril 2018

Ember: Route-Model returns all values, not filtered ones

This is the code:

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

export default Route.extend({
    model(param) {
        return this.get('store').findAll('rentals').then(results => {
            return results.filterBy('enabled', false);
        });
    }
});

When I do console.log(results.filterBy('enabled', false)); it returns filtered ones. But the return returns all values be the enabled true or false.

How to make it return filtered ones only?




ember + Could not find module `@ember/application`

I have a ember app, after start server, log this error in console:

Error: Could not find module @ember/application imported from app




Ember trigger action on wrapper component

I have a wrapper component that has an action that needs to be triggered from within, but I can't get rid of this:

    
        <button 
    

the above is the template of "componentA"; when I click the button I get an error saying that componentA does not have an action handler for "wrapper.myAction"; I can't get why it looks for the action on componentA instead of wrapper-component first. of course "myAction" is defined in "actions" on "wrapper-component"; the wrapper component has this template:






Emberjs : how do I know when all 'didInsertElement' have fired?

In Emberjs 3.0 I have a loop which renders a number of components. Once all of the components have been rendered I would like to do something but not before.

I have a didInsertElement handler on the component and that gets fired in response to each of the components rendering but how can the controller know when all of those have fired ?

BTW if this doesn't sound like best practice I do appreciate that but I'm dealing with a pre-existing backend and having to do certain things to accomodate that.




samedi 14 avril 2018

Authentification with ember-simple-auth in before model hook

I create a app thet need to implement authentification with email/password on all pages except one page (mobile_messages), where need to authenticate with refresh token. I extend from JWT authenticator and override authenticate method. So it looks like:

authenticate (credentials, headers) {
return new Ember.RSVP.Promise((resolve, reject) => {
  this.makeRequest('/auth/mobile_token', credentials, headers)
    .then((response) => {
      Ember.run(() => {
        try {
          const sessionData = this.handleAuthResponse(response)
          resolve(sessionData)
        } catch (error) {
          reject(error)
        }
      })
    }, (xhr) => {
      Ember.run(() => { reject(xhr.responseJSON || xhr.responseText) })
    })
})

}

On mobile_messages route I try to authenticate in before model hook.

beforeModel (transition) {
const authenticator = 'authenticator:api-token'
return this.get('session').authenticate(authenticator, {api_token: transition.queryParams.api_token}).then(() => {
  }, (reason) => {
  transition.abort()
  this.get('notifications').error('Permission denied.', {
    autoClear: true,
    clearDuration: 6200
  })
})

},

I need to stay on mobile_messages route if authenticate rejected. But when I enter to route with wront token I got next backtrase:

Preparing to transition from '' to 'mobileMessages'
index.js:169 generated -> controller:mobileMessages {fullName: 
"controller:mobileMessages"}
index.js:169 generated -> controller:aut`enter code here`henticated 
{fullName: "controller:authenticated"}
index.js:169 generated -> controller:loading {fullName: 
"controller:loading"}
router.js:300 Intermediate-transitioned into 'authenticated.loading'
index.js:169 generated -> route:messages-faxes {fullName: 
"route:messages-faxes"}
router.js:190 Transitioned into 'login'
jquery.js:9600 POST http://localhost:3000/auth/mobile_token 500 
(Internal Server Error)

It looks like I was redirected before got response from server. An I can't find who is redirect me from route. I try to check ApplicationRouteMixin but i got that sessionInvalidated method calls only if you click logout button. And sessionAuthenticated after success authentification.

If I push to route correct token, then I first redirect to login page and then sessionAuthenticated fires. After that i redirect to baseURL.

Hot to solve issue with redirection to login page?




vendredi 13 avril 2018

Ember service undefined when injected in route

When I inject a service in my route and I try to access it into the model or even in beforeModel, the service is not undefined but when I try to access a value of the service, everything is undefined.




Refresh Ember model when service method is executed

In a route, I would like my model ,where I called this.get('store'), to be dependent of a service. So when one of my value in the service changes, my model will be automatically refreshed.

I don't know if this is possible with a service and if it is a good practice.




Ember alternative to query params with service

So I have a route with this model:

model() {
   var self = this;
   return RSVP.hash({
    comptes : this.get('store').findAll('compte'),
    contrats: 
    this.get('store').findAll('contrat').then(function(contrats) {
      return contrats.filterBy("contrat_fk.id", 
         self.get('currentContract.contrat.id'));
      }),
    })
  }

My goal is to filter the model contrat with the value provided by my service currentContract.

It works fine when the page is reloaded, but when I change the route and comeback to this route, the model doesn't seem to be loaded and I have to reload the page to see it.

And I don't really wan't to use query params and put the contract id in the URL




Integrating Ember.js with Spring Framework

Integrating Ember.js with Spring Framework

I am trying to save firstname and lastname of customer but I am getting null values .I am using ember on Client side and server side Java aplication with spring framework

Web console :- WARNING: The server returned an empty string for POST, which cannot be parsed into a valid JSON. Return either null or {}.

Server code (Java Application):- @PostMapping(path="/createCustomer") public void createCustomer(@RequestBody EmberCustom createCustomer) { System.out.println("Firstname:"+ createCustomer.getFirstname() + ", Lastname: " + createCustomer.getLastname()); }

Output :- Tomcat started on port(s): 8080 (http) Firstname:null, Lastname: null




jeudi 12 avril 2018

Ember programmatically call controller action from hbs template

I have a defined action on my controller that makes a modal visible. In my hbs template, I am able to create a button and assign it the action. When I do this, I can make the modal appear by clicking the button.

I am trying to show the modal (call the controller action) without having to click anything. Is this possible? I want the modal to pop up based on a conditional on the model automatically.




mercredi 11 avril 2018

Ember template: Put code into another place

This is the template:


<div>
    <div>
        <div class="here">
        </div>
    </div>
    <div>
        
        
        
    </div>
</div>


I want to put first line here:

         <div class="here">
             
         </div>

But it breaks. How can I do that?




Ember CLI Mirage: How to filter out return value?

This is how I get all data in config.js:

this.get('/rentals', function (schema, request) {
    if (request.queryParams.value) {
        // The code should be here...
    } else {
        return schema.rentals.all();
    }

}

I looked at documentation, but there's no way to get filtered ones. Apparently there are commands like all(), find(), findBy(), create(), etc. But there's nothing that filters out and returns. Any help?




Ember: filter not working

Component is working, the data is getting rendered just fine. Here it is:

import Component from '@ember/component';

export default Component.extend({
  classNames: ['list-filter'],
  value: '',

  init() {
    this._super(...arguments);
    this.get('filter')('').then((allResults) => this.set('results', allResults.results));
  },

  actions: {
    handleFilterEntry(val) {
      let filterInputValue = this.get('value');
      let filterAction = this.get('filter');
      filterAction(filterInputValue).then((resultsObj) => {
        if (resultsObj.query === this.get('value')) {
          this.set('results', resultsObj.results);
        }
      });
    }
  }
});

This is controller:

import Controller from '@ember/controller';

export default Controller.extend({
    actions: {
        filterByName: function (param) {
            if (param !== '') {
                return this.get('store').query('rental', { name: param }).then((filteredResults) => {
                    return { query: param, results: filteredResults };
                });
            } else {
                return this.get('store').findAll('rental').then((results) => {
                    return { query: param, results: results };
                });
            }
        }
    }
});

What happens is that whenever I enter the data in the filter, it keeps getting the whole list of rentals, not part I want. handleFilterEntry is getting called. What am I doing wrong? Please let me know if additional info needed.




Handlebars reference component one directory up

I have the following code:


  <div class="tab-pane active" id="content-" role="tabpanel">
    //... Code
  </div>


However tabs-controls is a component that lives outside the directory of the component calling it.

-components
   -tabs-control
   -hotspots
       -hotspots-container
       -hotspots-content
              -template.hbs

I've tried:

 


Both again without the pound sign...All I get are compiler errors.

What is the right way to achieve this?




Selenium (Python) Finding all selectable windows on a webpage

So im trying to parse out all of the href links on a page here: https://data-wake.opendata.arcgis.com/datasets but Ive noticed that none of the links im looking for are returning from my python code which is here:

driver = webdriver.PhantomJS("C:\Users\Jlong\Desktop\phantomjs.exe")
driver.get(r"https://data-wake.opendata.arcgis.com/datasets")
pagesource = driver.page_source
bsobj = BeautifulSoup(pagesource,'lxml')
for line in bsobj.find_all('a'):
    print(line.get('href'))

Here is a snipit of the html from chromes inspect: Html Inspect

the expected result would be to return something like the following:

"/datasets/wakeforestnc::state-system-streets"

I have also noticed that there is something called Ember application.js running on the page and I think that maybe preventing me from accessing the href attributes that are deeply nested in the main ember tag. IM not familair with ember or how to parse complex pages like this, any help would be greatly appreciated!




Converting Travis.yml to circle.yml

I'm having a lot of trouble switching my build (EmberJS) from TravisCI to CircleCI. Here is my current travis.yml file, it's super simple, but does leverage some pull request info...any help is much appreciated.

# TravisCI deploy script for frontend Ember build.
---
language: node_js
node_js:
  - "6"

sudo: false
dist: trusty

addons:
  chrome: stable

cache:
  directories:
    - $HOME/.npm

deploy:
  - provider: script
    skip_cleanup: true
    before_script: cd frontend
    script: node_modules/.bin/ember deploy production --activate --verbose
    on:
      branch: frontend
  - provider: script
    skip_cleanup: true
    before_script: cd frontend
    script: node_modules/.bin/ember deploy staging --activate --verbose
    on:
      branch: frontend-staging

branches:
  only:
    - frontend
    - frontend-staging

# script:
#   - npm test
script:
  - if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then node_modules/.bin/ember build; fi
  - if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then npm install surge; fi

env:
  global:
    - JOBS=1

before_install:
  - npm config set spin false
  - cd frontend

after_success:
  - if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then chmod ugo+x frontend/pr_deploy.sh; fi
  - if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then frontend/pr_deploy.sh; fi




_renderNode is not a function in ember upgraded version to render first and last node of a component

I am upgrading from ember 2.5.0 to 2.18.0 but _renderNode is no more available. Is there any other function to get the same result?




url name is getting changed when I change the tab in my project?

I'm facing the struck on page in my localhost server link. when I refresh the page, url name is getting changed. That's the usual things for all Url. Here also the same. But when I refresh the page, it getting struck. Not even the console is running or getting close. Simply it got struck and I'll close on through task manager only.

I'm having two tabs in the page called "content" and "Admin". When I click on the Admin tab, url showing the below link

http://localhost:8080/core-cms/admin/Administration/License

I'm having lot of taskbars in that tab, When I'm clicked on taskbar name called "Managed Object Definitions". The url link is getting changed like below:

http://localhost:8080/core-cms/admin/Administration/ManagedObjects

After that when I go to "content" tab and come into again "admin" tab, the url link is getting changed like below:

http://localhost:8080/core-cms/(subclass%20of%20admin/Administration/ManagedObjects)

After that when we refresh the page, the page is getting struck. Console also not getting run.

Can anybody help me on this. What should be the problem. Your help would be appreciable.




mardi 10 avril 2018

How do you set variable in route and display in template?

I am looking to set a variable for each page that is set to text to display as a dynamic header sort of thing. How would I set a variable in a route and display it in the corresponding template? So far everything I have tried is not working.




iframe refresh failed in ambari web

I add a custom view to show something with iframe like below:

js:

var App = require('app');

App.CustomView = Em.View.extend({
  tagName: "iframe",
  classNames: ["views_sizes"],
  attributeBindings: ['src','height','seamless','allowfullscreen'],
  seamless: "seamless",
  height: "500px",
  allowfullscreen: "true",

  didInsertElement: function() {
    this.set('src','http://www.github.com');
  }
});

At first click, it shows github as expected, but when refresh, whole web break:

Uncaught Error: Cannot perform operations on a Metamorph that is not in the DOM.
    at K.Metamorph.checkRemoved (vendor.js:19469)
    at K.Metamorph.replaceWith (vendor.js:19448)
    at Object.<anonymous> (vendor.js:19769)
    at invoke (vendor.js:5036)
    at iter (vendor.js:5083)
    at Array.forEach (<anonymous>)
    at RunLoop.flush (vendor.js:5139)
    at RunLoop.end (vendor.js:5055)
    at Function.Ember.run.end (vendor.js:5247)
    at autorun (vendor.js:5313)

I am new about ember.js, and i can not search an useful solution until now, could someone know it?




lundi 9 avril 2018

Ember: correct way to render background image in an element

This is the html:

<div style="background-image: url();"></div>

This renders all good, but keep receiving this warning:

warn.js:48 WARNING: Binding style attributes may introduce cross-site scripting vulnerabilities; please ensure that values being bound are properly escaped. For more information, including how to disable this warning, see https://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes. Style affected: "background-image: url(https://www.userImage.com/cuautemok.png);"

Tried:

<div style=background-image: url();></div>

<div style="background-image: url('');"></div>

<div style="background-image: url("");"></div>

and many more... No luck yet.




Best way to upgrade ember babel

I installed an addon in my embr application. After that I receive the warning:

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

What's the best to go about upgrading this?




Ember dynamic routes with relative image path

Using a relative image path on a dynamic route, adds the route before the image, see here.

Why is this? And is there a way to user a relative image path with a dynamic route? Is this documented anywhere?




ember Error: Assertion Failed: fullName must be a proper full name

I got the following error while running a test with Ember.js:

Promise rejected before "...": Assertion Failed: fullName must be a proper full name

What is the meaning of this error?




Importing multiple functions from module without explicitly exporting object or named export

utils/mathlib.js

export function add(x, y) {
    return x + y;
}
export function subtract(x, y) {
    return x - y;
}

main.js

import add from "./../utils/mathlib"; //not working. but if I do default export like `export default function add(x, y)` it will work
import { add } from "./../utils/mathlib"; //working
import * as MathLib from "./../utils/mathlib"; //working

But I want to import all the functions available in the module with the same identifier without importing separately or through importing object. Something like the below,

import * from "./../utils/mathlib"

I should be able to use add, subtract function.

The reasoning behind this use case is, Whenever I add new functions in MathLib.js it should be available without modifying.(I took MathLib as sample use case only, in my real use case all the functions is necessary whenever I import the module).




dimanche 8 avril 2018

ember js query model for only certain params

If I have an ember model say Person with attributes like name, age, height, address etc, and I want to fetch all records in the model but only want name attribute in returned JSON (name is the only param needed, so no need to return all params of the model), then is there a way in Ember to do that? I searched for the query methods on Ember store but was not able to see any such example.

Thanks in advance.




Deploying Ember Apps to EC2

Hello could someone point me in the right direction on how to deploy an Ember.js app to EC2. I have written my backend code in Node.js Express so would need to deploy that too. Just need some guidance on how i should do it.

I attempted to use ember-cli-deploy and rsync but no luck. I have found tutorials for S3 but not EC2.




Starting a web application using Express and Ember

I want to write a simple CMS using Node.js (with Express) and Ember.js. I am totally new to Ember.js, but I am familiar with Angular. I see Ember.js is very close to Angular because it uses a CLI with "ember serve" command to run the client app. But in Node.js I also have to start the server using "npm start". As any CMS, there is a "public" part (the site pages) served by Express using Handlebars and an "admin" part (the reserved area, with administrative pages) that is the web app wrote in Ember.js. Is there a way to have both client and server routes from a single base domain and port (i.e. http://localhost:3000/ for public pages and http://localhost:3000/admin/ for the admin pages)? And there is a way to start the whole project with a single command, instead of typing "npm start" for the server and "ember serve" for the client? Maybe the only way is to render Ember.js templates server-side with Fastboot? I am very confused about the development of a web app like this.




How to check a property of an Object while writing test cases in Ember JS?

I have been doing a small project in Ember JS and with almost 90 percent of the task completed, I went on to write test cases. I wrote an Unit test to check the value of a property stored in the model object of a controller. So, The test is basically a Unit test for the controller.

I will not be able to show the complete code here. However, I will present the structure of the code.

controller.js

import sampleMixin from 'path/sampleMixin';

/* rest of the code goes here */

sampleMixin.js

const { Mixin } = Ember;

export default Mixin.create({
  let self = this;
  this.store.getJSON()
    // Promise goes here
});

The problem is when I run the test case, the test case failed at this.store.getJSON() saying, cannot read store of undefined. When I debugged using a debugger, I found that store was not present. My test case is as follows:

controller-test.js

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

moduleFor('controller:controller', 'Unit | Controller | controller', {
  needs: ['service:metaData']
});

test('it exists', function(assert) {
  let controller = this.subject();
  assert.ok(controller);
});

I am new to testing environments in Ember, Should I use Unit testing to check the properties of an Object?




vendredi 6 avril 2018

ember vendor js file does not seem to be working

I am trying to work an admin theme into an ember project. There is a custom.js file that has a lot of the javascript for the sidebar, header stuff etc. I have it in the vendor folder vendor/custom.js. I am including it in ember-cli-build as app.import('vendor/custom.js'); When I look in chrome at the vendor.js file I see the contents listed in it, but the javascript on the page does not work.

If I take some of the sections out of the custom.js and put them in the hbs file within tags the do run and work. I'm wondering why just including importing the file doesn't work.

Any thoughts on what could be wrong?

Here is a link to the custom.js file Custom.js Gist




Ember submit on an Icon

I have a working submit system when editing a company on my website. Currently I am submiting the data with which gives me a clickable text that handles the submit action, now I don't want a text I want the submit action on an Icon from Fontawesome.

This is the code in the .hbs file


  
  <div class="card-header bg-primary">
    <div class="row">
      <div class="col-sm-6">
        <a class="card-link text-white" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Übersicht</a>
      </div>
      <div class="col-sm-6 text-right d-block">
        
        <a class="card-link text-white"><i class="fa save"></i></a>
        <a onclick= class="card-link text-white"><i class="fa abort"></i></a>
        <a  class="card-link text-white"><i class="fa trash"></i></a>
        <a class="card-link text-white" data-toggle="collapse" data-parent="#accordion" href="#collapseOne"><i class="fa angle"></i></a>
      </div>
    </div>
  </div>
  <div id="collapseOne" class="collapse multi-collapse show border border-primary rounded-bottom">
    <div class="card-body">
        <div class="row">
          <div class="col-sm-12">
            
            
          </div>
        </div>
        <div class="row">
          <div class="col-sm-2">
            <img class="img-fluid" alt="FIRMENLOGO" src="img/puzzle_logo.png">
          </div>
          <div class="col-sm-10 row">
            <div class="col-sm-4">
              <table class="table-uebersicht">
                <tr>
                  <td></td>
                </tr>

I want to put the action from



onto the

 <a class="card-link text-white"><i class="fa save"></i></a>

element.

And this is the .js file behind it

import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
import CompanyModel from '../models/company';

export default Component.extend({
  store: service(),
  i18n: service(),
  router: service(),

  personPictureUploadPath: computed('company.id', function() {
    return `/company/${this.get('company.id')}/picture`;
  }),

  actions: {
    submit(changeset) {
      return changeset.save()
    .then(() => this.sendAction('submit'))
    .then(() => this.get('notify').success('Firmenübersicht wurde aktualisiert!'))
    .catch(() => {
      let company = this.get('company');
      let errors = person.get('company').slice(); // clone array as rollbackAttributes mutates

      person.rollbackAttributes();
      errors.forEach(({ attribute, message }) => {
        let translated_attribute = this.get('i18n').t(`company.${attribute}`)['string']
        changeset.pushErrors(attribute, message);
      this.get('notify').alert(`${translated_attribute} ${message}`, { closeAfter: 10000 });
    });
    });
    },
    deleteCompany(companyToDelete) {
      companyToDelete.destroyRecord();
      this.get('router').transitionTo('companies');
      window.location.reload(true);
    }
  }

});

Thanks for your answers!




Ember serve Build Error (EslintValidationFilter)

running ember serve i get the following error message

Build Error (EslintValidationFilter) in components/type-compte.js

Cannot read property 'body' of undefined

Stack Trace and Error Report: C:\...Temp/error.dump.d4e5703d56fd78302521e967efca5c25.log

the stack trace containe :

ERROR Summary:

  • broccoliBuilderErrorStack: TypeError: Cannot read property 'body' of undefined at CallExpression (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint-plugin-ember\lib\rules\require-super-in-init.js:92:60) at listeners.(anonymous function).forEach.listener (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\util\safe-emitter.js:47:58) at Array.forEach () at Object.emit (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\util\safe-emitter.js:47:38) at NodeEventGenerator.applySelector (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\util\node-event-generator.js:251:26) at NodeEventGenerator.applySelectors (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\util\node-event-generator.js:280:22) at NodeEventGenerator.enterNode (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\util\node-event-generator.js:294:14) at CodePathAnalyzer.enterNode (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\code-path-analysis\code-path-analyzer.js:608:23) at Traverser.enter [as _enter] (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\linter.js:865:28) at Traverser._traverse (C:\Users\PC\Desktop\dev\github\wikicours\node_modules\eslint\lib\util\traverser.js:132:14)
  • codeFrame: Cannot read property 'body' of undefined
  • errorMessage: Build Canceled: Broccoli Builder ran into an error with EslintValidationFilter plugin. 💥 Cannot read property 'body' of undefined
  • errorType: Build Error
  • location:
    • column: [undefined]
    • file: components/type-compte.js
    • line: [undefined]
    • treeDir: C:\Users\PC\Desktop\dev\github\wikicours\tmp\broccoli_persistent_filtereslint_validation_filter-input_base_path-QtE3OUt9.tmp
  • message: Build Canceled: Broccoli Builder ran into an error with EslintValidationFilter plugin. 💥



jeudi 5 avril 2018

How to specify "element(by.id" or "element(by.css" in Ember.js using Protractor

New to ember.js -- used http://yoember.com/ to create a Demo ember.js site. I'm trying to figure out how to use Protractor to test certain elements, but I'm encountering issues specifying them.

Most, but not all, elements (buttons, text areas, etc) have a serialized id value: id='ember###' that changes every time the page is reloaded, which makes it impossible to indicate some elements in Protractor (like, element(by.id('ember557')).sendKeys('foo');).

Running a command like the one above will return the error: Failed: No element found using locator: By(css selector, *[id="ember557"]), which is due to the 3-digit id value changing.

In my demo app, I was able to go into the /app/templates/components/ file for that page and manually add something like id='name' into the handlebars input and was able to successfully find and test that element in Protractor.

This isn't ideal though, and I'd like to find a way to test sites that I don't have the ability to modify the html of.

Can anyone help me wrap my head around this? Thanks.




Ember model access to belongsTo property return null

I have a model Person with this property : address_fk: DS.belongsTo('address') refering to an Address model.

In the adress model, there are several properties such as zip_code , building ...

My goal is to create a computed property in Person to display the full address by accessing this.get('address_fk.zip_code') but it returns me undefined

I'm surely missing something here but I really don't know what.




How to resolve a promise on a controller?

Hi I have a modelA and modelB

my modelA.js has something like this

  modelBs: DS.hasMany('modelB', { async: true })

and my modelB.js has something like this

  modelA: DS.belongsTo('modelA', { async: true })
  status: DS.attr('string'),

  statusOne: Ember.computed.filterBy('status', 'one'),
  statusTwo: Ember.computed.filterBy('status', 'two'),

However, I have a template that has a each loop for my modelA which looks something like this

 
   
   
 

My question is why does my returned 0 value whereas this user has more than 1 statusOne value




Create a alias property for a property inside an array

Consider the following array,

auth: [{
    username: "",
    password: "",
  },
  {
    username: "",
    password: "",
  }
]

I am not able to add alias to a property inside the array like the one described below

defaultUsername: Ember.computed.alias('deviceDetails.auth[0].username'),
username: Ember.computed.alias('deviceDetails.auth[1].username')

How to achieve this?




mardi 3 avril 2018

Ember Component handle jQuery event handlers

In an Ember app Component, what is the best hook within which to handle jQuery event handlers ? I want to handle a keyUp event on an input element.




Emberjs computed firing and logic running, but not updating the view

I have a computed property on a controller which I can see is being called when it should (when the route loads and when a button is pressed) however the newsItem record isn't being removed from the view.

  filteredNews: computed('user.read', function () {
    const newsItems = get(this, 'newsItems');
    const userClassifications = get(this, 'user.classification');
    const userRead = get(this, 'user.read');

    newsItems.forEach((newsItem) => {
      userClassifications.forEach(userClassification => {
        if (newsItem.get('classification').includes(userClassification)) {
          newsItem.unloadRecord();
        }
      });

      if (userRead.includes(newsItem)) {
        console.log("read: " + get(newsItem, 'title'));
        newsItem.unloadRecord();
      }
    });

    return newsItems;
  }),

The console.log(...) is being called each time, so I know the logic is correct.

Is there an obvious reason this isn't working as I expect?




lundi 2 avril 2018

Unexpected token P in JSON at position 0 when trying to return Excel spreadhsheet

I have an emberJS application where I can make a POST AJAX call to a Django backend. A function in Django creates an xlsx file for a bunch of queried items based on IDs coming in the POST request. It goes through the Django view function without any issues, but when the HTTP response is returned to ember, I get the error

SyntaxError: Unexpected token P in JSON at position 0
    at parse (<anonymous>)
    at ajaxConvert (jquery.js:8787)
    at done (jquery.js:9255)
    at XMLHttpRequest.<anonymous> (jquery.js:9548)
    at XMLHttpRequest.nrWrapper (base-content:20)

I'm setting the response content type to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, so I'm unsure as to why its trying to read the response as JSON.

Python Code

file_path = '/User/path_to_spreadsheet/content.xlsx'
fsock = open(file_path, "rb")

response = HttpResponse(fsock, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="content.xlsx"'
return response

EmberJS Code

export default Controller.extend({
  actions: {
    storeProductId(products) {
      let product_ids = []

      products.forEach(function(product){
        product_ids.push(product.id)
      });

      let adapter = this.store.adapterFor('product-export');
      adapter.export_products(product_ids).then(function(response){
        console.log(response)
      }).catch(function(response) {
        console.log('ERROR')
        console.log(response)
      })
    }
  }
});




dimanche 1 avril 2018

Add or change a value of JSON key with javascript in ember not working

In .hbs file I'm trying to open a popup and using the code which contains

1.
2 ....
3 ....<div class="mdl-cell mdl-cell-6-col ">
4 ........
5 ............<p>UPDATE ID Proof</p>
6 ........
7 ........
8 ............<p>ADD ID Proof</p>
9 ........
10 ....</div>
11

So, now I'm trying to change the value of id_update_status in corresponding JS file using something like this.adultJsonArr[0].id_update_status = 'updated' So, it's not working. Instead if I try to change any other attribute it works like this.adultJsonArr[0].id_update_status_check = 'Is it working?' it works. It's basically like the json attribute which is not used at line no 4 and 7 in popup can be updated but one being used can't.




How to push or update data with emberfire?

My guess was to put the model (in my case 'user') inside => type, but then it'll say "Assertion failed, you need to pass a model ..."

I do have a user.js in app/models

here's an excerpt from the router (after login function)

self.store.push({
                data: {
                    id: data.currentUser.uid,
                    type: 'user',
                    attributes: {
                        displayName: data.currentUser.displayName,
                        email: data.currentUser.email,
                        photoURL: data.currentUser.photoURL,
                        firebaseUID: data.currentUser.uid,
                        rank: "scorer",
                        status: "active",
                        loginCount: 0,
                        provider: provider,
                        timestamp: new Date().getTime()
                    }
                }
            });

and here's my model (user.js in app/models)

import DS from 'ember-data';

export default DS.Model.extend({
  displayName: DS.attr('string'),
  email: DS.attr('string'),
  photoURL: DS.attr('string'),
  firebaseUID: DS.attr('string'),
  rank: DS.attr('string'),
  status: DS.attr('string'),
  loginCount: DS.attr('string'),
  provider: DS.attr('string'),
  timestamp: DS.attr('number')
});

Please help :( thanks everyone in advance!