jeudi 28 février 2019

How to show an image in a pop up screen with ember.js

I'm currently making a pop-up screen with mobiscroll and ember.js where you can select a photo from your on pc and I need to display them in the pop-up screen as a preview. currently I have that you can choose a photo from your pc and you get a message in the console log that is has been uploaded.

I have this in my .hbs file:

<div class="popup">
<div class="popup-header">

</div>
<div class="ember-view mdsc-comp" style="width: 100px">
<div class="col 16 m6 s12 blue-grey lighten-4" style="border-radius:3px; border: 1px solid #ADB8C0; padding-right: 22.5px;padding-top: 25px;  margin-left: 11.250px !important;  border-radius: 5px; width: 50px">

  <div ></div>
    <input id="img" multiple="true" onchange= accept="image/png,image/jpeg,application/" type="file"/>

    <p>(Upload .png .jpeg of .gif afbeeldingen)</p>

  <h5>Titel</h5>
  <div class="input-field col s12">
    
  </div>
</div>

and this in my .js file:

  import Ember from 'ember';
  import mbscPopup from "../mobiscroll/mbsc-popup";

  export default mbscPopup.extend({
  didRender(){
    this.set("headerText", "Nieuwe media toevoegen");
},

actions:{
    cancel(){

    },

    save()
    {

    },
    upload() {
        console.log('upload');
    },
    add() {
        this.$("input[type='file']").click();
    },
}
});

My question is how I can show the image in the pop up screen.




mercredi 27 février 2019

Why use this.get('serviceName') instead of this.serviceName?

In Ember.JS, Is there a good reason to be doing this:

import Service, { inject } from '@ember/service';

export default Service.extend({
ajax: inject(),
getAll() {
    return this.get('ajax').request(`api/users/`, {
        method: 'GET',
        contentType: 'application/json'
    });
}
});

As opposed to this?

import Service, { inject } from '@ember/service';

export default Service.extend({
ajax: inject(),
getAll() {
    return this.ajax.request(`api/users/`, {
        method: 'GET',
        contentType: 'application/json'
    });
}
});

The second method looks cleaner IMO, but I'm wondering if there's a good functional reason to be using .get() over just referencing the service directly.




Ember serializer - Issues mapping type returned by server

Im using Ember 3.2 with JSON API end points. Im stuck on how to map data the server provides me to my models.

I have the following models:

// Model Zoo
export default DS.Model.extend({
    animals: hasMany('animal', {polymorphic: true})
})

// generic animal model
export default DS.Model.extend({
})

// animal-mamal model
export default DS.Model.extend({
  ...
})

// animal-reptile model
export default DS.Model.extend({
  ...
})

When consuming the resource example.com/zoo/:id/animal Im getting the following response:

{
  "data" : [ {
    "id" : ":some-id",
    "type" : "mamal-animals",
    "attributes" : {
      ...
    },
    "relationships" : {
      ...
    },
    "links" : {
      ...
    }
  }, {
    "id" : ":some-id",
    "type" : "reptile-animals",
    "attributes" : {
      ...
    },
    "relationships" : {
      ...
    },
    "links" : {
      ...
    }
  }]
}

Without implementing anything in the serializer I get the following in the console:

Encountered a resource object with type 
"mamal-animals", but no model was found for 
model name "mamal-animals" (resolved model name 
using '(unknown mixin).modelNameFromPayloadKey("mamal-animals")').

My models do not map with the type the server gives me. After getting that message, I wrote some code in the method modelNameFromPayloadKey from the Application serializer.

It basically maps the types the server provides me with to the models I have in the frontend.

// Map Backend type to Frontend models
const PAYLOAD_KEY_TO_MODEL = {
  'mamal-animals': 'animal-mamal',
  'reptile-animals': 'animal-reptile'
 }

export default DS.JSONAPISerializer.extend({
  // Map payload keys return by API to corresponding models in our app
  modelNameFromPayloadKey(key) {
    if(PAYLOAD_KEY_TO_MODEL[key]){
      return this._super(PAYLOAD_KEY_TO_MODEL[key]);
    } else {
      return this._super(...arguments);
    }
  }
})

Now it crashes with the following error:

Assertion Failed: You tried to push data with a 
type 'mamal-animals' but no model could be found with that name.

It seems it is still trying to find the type returned by the server instead of the model I provided.

I thought that the model name would be taken by implementing the modelNameFromPayloadKey method.

Any solution or ways to debug issues with serializer?




lundi 25 février 2019

How to get the http request object in the application.js in ember [duplicate]

This question already has an answer here:

so I'm running EmberJs in the front-end and I want the request object first time the browser hit the front-end to get the headers from the request.

I need it in the application.js in the route.

How do I go about doing it?




Can I use a gradient in Chart.js without accessing the chart context when the chart is created?

In Chart.js, is it possible to create a chart with a gradient as a background color only by passing in data or options when creating the chart?

All the tutorials I see involve calling createLinearGradient on the chart context when creating the chart, and then passing in the gradient object via the backgroundColor option.

Ideally, I would like to be able to pass data to my chart by doing something like this:

datasets: [
  {
    data: myData,
    backgroundColor: "linear-gradient(#FF0000, #00FF00)"
  }
]

Or, if it's absolutely impossible to create a gradient without the chart context, then with something like:

datasets: [
  {
    data: myData,
    backgroundColor: (ctx) => {
      let gradient = ctx.createLinearGradient(0, 0, 100, 0);
      gradient.addColorStop(0, '#FF0000');
      gradient.addColorStop(0, '#00FF00');
      return gradient;
    }
  }
]

I am unable to touch the chart context (or at least, it would be quite difficult and rather hacky to do so) because I am using ember-cli-chart, which as far as I know does not provide a way to access the chart's context.

I'd also be happy just having a clean way to work around this in Ember, if there are suggestions there.




Simple Ember.js `has-many` relationship not working

I'm running into an issue of querying data against Ember data.

I have three models:

media: which multiple models inherit from image: which inherits from media note: which is a standard model.

I'm trying to get all of the notes of an image but the query I'm trying isn't working.


// imageModel.js
import Ember from 'ember';
import DS from 'ember-data';
import MediaModel from 'models/mediaModel';

export default MediaModel.extend({ 
    fileName: DS.attr('string'),
    fileExt: DS.attr('string'),

    url: DS.attr('string'),
});


// mediaModel.js
import DS from 'ember-data';

export default DS.Model.extend({
    notes: DS.hasMany('note', { inverse: 'noteable' }),
});


// noteModel.js
import DS from 'ember-data';
import Ember from 'ember';

export default DS.Model.extend({
    category: DS.attr('string'),
    text: DS.attr('string'),

    image: DS.belongsTo('image'),
    noteable: DS.belongsTo('media-model', { polymorphic: true }),
});

Once I have an image, I do image.get('notes.length'), but even if an image does have notes associated with it, I'm always getting back 0. Am I querying this the wrong way?

Does the fact that image belongs to media affect how I can query the hasMany of media?

Thank you




samedi 23 février 2019

Nested back-end resources in Ember

This question may be duplicative, but I haven't quite been able to find the answer.

I have a Rails API serving a URI like this:

/locations/1/visits

In Ember I have a route like this:

Router.map(function() {
  this.route('location', { path: '/locations/:location_id' }, function() {
    this.route('visits' , { path: 'visits' });
 });
});

..and a model like this:

export default DS.Model.extend({
  name:           DS.attr(),
  visits:         DS.hasMany('visit', { nested: true }),
});

When I hit /locations/1/visits in the browser, I expect Ember to likewise hit /locations/1/visits on the backend. Instead, it attempts /locations/1 (without visits).

Any ideas how to convince Ember to properly nest the association?

Thanks!




OmniSharp not functioning properly in one project but is in another

I have two identical projects that I am using to create a full stack Ember web-ui with .NET Core JSON API. I notice that in one project, OmniSharp is not providing the include using statement, but it does in the other project. Additionally, for the project where OmniSharp does not provide the include using statement, OmniSharp does provide an option to remove unused usings. When I select this option, it removes all but two using statements, which is incorrect because now the application will not build.

I tried uninstalling VSCode and deleting the .vscode folder in the C:\windows\users path, which contains the installed extensions, as well as deleting all temp files. However, this does not solve the problem.

Considering that OmniSharp works in one project, but not the other, then the only thing that I can think of at this point is that either OmniSharp is configured at the project level or there is a corruption in the given project. Has anyone ever experienced this problem? Any ideas on how I can address/fix this?

Note: I would hate to delete the project that OmniSharp does not work in because it would take about a week to rebuild it.

Update:

After additional research, I found the following error in the OmniSharp Log

The project system 'OmniSharp.Script.ScriptProjectSystem' threw exception during initialization. System.IO.DirectoryNotFoundException: Could not find a part of the path 'd:...\tmp\broccoli_merge_trees-input_base_path-YLNtHXfX.tmp\1-private'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileSystemEnumerableIterator1.CommonInit() at System.IO.FileSystemEnumerableIterator1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler1 resultHandler, Boolean checkHost) at System.IO.DirectoryInfo.EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) at Microsoft.Extensions.FileSystemGlobbing.Abstractions.DirectoryInfoWrapper.<EnumerateFileSystemInfos>d__4.MoveNext() at System.Collections.Generic.List1.InsertRange(Int32 index, IEnumerable`1 collection) at Microsoft.Extensions.FileSystemGlobbing.Internal.MatcherContext.Match(DirectoryInfoBase directory, String parentRelativePath) at Microsoft.Extensions.FileSystemGlobbing.Internal.MatcherContext.Match(DirectoryInfoBase directory, String parentRelativePath) at Microsoft.Extensions.FileSystemGlobbing.Internal.MatcherContext.Match(DirectoryInfoBase directory, String parentRelativePath) at Microsoft.Extensions.FileSystemGlobbing.Internal.MatcherContext.Match(DirectoryInfoBase directory, String parentRelativePath) at Microsoft.Extensions.FileSystemGlobbing.Internal.MatcherContext.Match(DirectoryInfoBase directory, String parentRelativePath) at Microsoft.Extensions.FileSystemGlobbing.Internal.MatcherContext.Match(DirectoryInfoBase directory, String parentRelativePath) at Microsoft.Extensions.FileSystemGlobbing.Internal.MatcherContext.Execute() at Microsoft.Extensions.FileSystemGlobbing.MatcherExtensions.GetResultsInFullPath(Matcher matcher, String directoryPath) at OmniSharp.Script.ScriptProjectSystem.Initalize(IConfiguration configuration) at OmniSharp.WorkspaceInitializer.Initialize(IServiceProvider serviceProvider, CompositionHost compositionHost)




How do I upgrade ember-cli-babel?

The online NPM documentation does not explain how to upgrade ember-cli-babel. I tried following the accepted answer posted here Invalid Version: Ember-Cli-Babel, but that did not work.

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: library-ui -> ember-clean-tmp -> ember-cli-babel




vendredi 22 février 2019

How to bring data to another modal and delete from existing positon in Ember

I have an object called passengerStatus: attr("string") on passengerDetails.js model. I am using passengerDetail data in guest.js model. Now I want passengerStatus: attr("string") on guest.js level and be deleted on passengerDetails level.

EXISTING CODE: Request payload:

guests: [{
     passengerDetails: {
        passengerStatus: xyz,
     }
}]

EXPECTED CODE: Request payload:

guests: [{
     passengerStatus: xyz,
     passengerDetails: {
        other objects: abc
     }
}]

How can I achieve this.




Ember.js each loop : compare current index data with previous index data

In ember.js each loop, How can I access the data of the previous index inside the current loop?



   //compare current min with previous min

     <div>Something</div>

  



I know I can create a helper to store the previous index data inside the template scope, but is there any template only way? If not, what will be the most elegant way using a helper?




Can Ember helpers be used as utilities?

I was going through the codebase of an old project that uses Ember-CLI 1.13 and found something strange.

There are many helpers that are not directly used inside templates but are used in component js files by importing into them. One such example is

//..helpers/my-helper.js

export function func1 (param1, param2) {
   //return something;
}

export function func2 (param1, param2) {
   //return something;
}

export function func3 (param1, param2) {
   //return something;
}

export default Ember.Helper.helper(func1);
export default Ember.Helper.helper(func2);
export default Ember.Helper.helper(func3);

And inside a component js file, I could see the above helpers being imported and used.

//../components/my-component.js
import Ember from "ember";

import { func1 } from '../helpers/my-helper';
import { func2 } from '../helpers/my-helper';
import { func3 } from '../helpers/my-helper';

I have few questions:

  1. Shouldn't we create a utility instead of a helper in this case?
  2. Is it ok to include many functions in a single helper file?
  3. Inside the helper file, is it required to use export default Ember.Helper.helper(); , if we are not intending to use the helper inside templates direcly?
  4. Are the imports inside the component file necessary?



jeudi 21 février 2019

Strange error trying to run ember tests on debian linux

All our tests pass on multiple macOS machines, and on semaphore-ci, but when we try to build and run tests on a new debian box, we get this error in loader.js:143

not ok 1320 Chrome 72.0 - TestLoader Failures: zipbooks/tests/unit/utils/request-log-test: could not be loaded
    ---
        actual: >
            null
        stack: >
            TypeError: Cannot read property 'exports' of undefined
                at Module._reify (http://localhost:45371/assets/vendor.js:148:59)
                at Module.reify (http://localhost:45371/assets/vendor.js:135:27)
                at Module.exports (http://localhost:45371/assets/vendor.js:109:10)
                at Module._reify (http://localhost:45371/assets/vendor.js:148:59)
                at Module.reify (http://localhost:45371/assets/vendor.js:135:27)
                at Module.exports (http://localhost:45371/assets/vendor.js:109:10)
                at Module._reify (http://localhost:45371/assets/vendor.js:148:59)
                at Module.reify (http://localhost:45371/assets/vendor.js:135:27)
                at Module.exports (http://localhost:45371/assets/vendor.js:109:10)
                at requireModule (http://localhost:45371/assets/vendor.js:32:18)
        message: >
            Died on test #1     at TestLoader.moduleLoadFailure (http://localhost:45371/assets/test-support.js:11150:24)
                at TestLoader.<anonymous> (http://localhost:45371/assets/test-support.js:10463:16)
                at TestLoader.require (http://localhost:45371/assets/test-support.js:10451:27)
                at TestLoader.loadModules (http://localhost:45371/assets/test-support.js:10443:16)
                at loadTests (http://localhost:45371/assets/test-support.js:11174:22)
                at start (http://localhost:45371/assets/test-support.js:10857:33)
                at Module.callback (http://localhost:45371/assets/tests.js:20710:25): Cannot read property 'exports' of undefined
        Log: |
            { type: 'info',
              text: '\'Unit assertion failed and test has been paused for inspection.\'\n' }
            { type: 'error',
              text: '{ module: \'TestLoader Failures\',\n  name: \'zipbooks/tests/unit/utils/request-log-test: could not be loaded\',\n  result: false,\n  message: \'Died on test #1     at TestLoader.moduleLoadFailure (http://localhost:45371/assets/test-support.js:11150:24)\\n    at TestLoader.<anonymous> (http://localhost:45371/assets/test-support.js:10463:16)\\n    at TestLoader.require (http://localhost:45371/assets/test-support.js:10451:27)\\n    at TestLoader.loadModules (http://localhost:45371/assets/test-support.js:10443:16)\\n    at loadTests (http://localhost:45371/assets/test-support.js:11174:22)\\n    at start (http://localhost:45371/assets/test-support.js:10857:33)\\n    at Module.callback (http://localhost:45371/assets/tests.js:20710:25): Cannot read property \\\'exports\\\' of undefined\',\n  actual: null,\n  testId: \'8629d10a\',\n  negative: false,\n  runtime: 1,\n  todo: false,\n  source: \'TypeError: Cannot read property \\\'exports\\\' of undefined\\n    at Module._reify (http://localhost:45371/assets/vendor.js:148:59)\\n    at Module.reify (http://localhost:45371/assets/vendor.js:135:27)\\n    at Module.exports (http://localhost:45371/assets/vendor.js:109:10)\\n    at Module._reify (http://localhost:45371/assets/vendor.js:148:59)\\n    at Module.reify (http://localhost:45371/assets/vendor.js:135:27)\\n    at Module.exports (http://localhost:45371/assets/vendor.js:109:10)\\n    at Module._reify (http://localhost:45371/assets/vendor.js:148:59)\\n    at Module.reify (http://localhost:45371/assets/vendor.js:135:27)\\n    at Module.exports (http://localhost:45371/assets/vendor.js:109:10)\\n    at requireModule (http://localhost:45371/assets/vendor.js:32:18)\' }\n' }

We cannot find any information or have any guesses what might be causing this error.

ember-cli: 3.1.4
node: 8.5.0
os: linux x64

The pattern I'm seeing is that any test that uses setupTest, setupApplicationTest or setupRenderingTest is failing. Regular qunit tests that dont have any setup hooks pass fine.




EmberJS : JSON-API Errors for one field are included in other field's errors

I have a ticket model with only a subject and content field.

subject: DS.attr('string'),
content: DS.attr('string')

On a new wiew, submitting a new ticket with content but without a subject return the following error :

{"errors":[{"source":{"pointer":"/data/attributes/subject"},"detail":"doit être rempli(e)"}]}`

Here is the controller action :

saveTicket(ticket){
      let promise=ticket.save();
      promise.then(
        () => this.transitionToRoute('tickets')
      );
      return promise;
    }

ticket.errors.subject[0].subject correctly contain the detail from the server's answer, however, ticket.errors.subject[0].message also contain the error message.

Why is the error attached to every field ?




Ember: overriding property from imported mixin?

I have a simple mixin that uses a property to perform an action. I'm trying to model inheritance so that I can override this property in the Component that uses the mixin.

For the same benefit of overriding in any OO language.

I appreciate using extend may be preferable for modelling inheritance but I wonder if this is possible with a mixin.


I have tried using this.get('') to retrieve a property from my component that doesn't exist in the mixin. The idea being I can check if the programmer wants to specify the element to focus. If not, use a default. This returns nothing even when the property is defined on the implementing component.

import $ from 'jquery';
import Mixin from '@ember/object/mixin';

export default Mixin.create({
  didRender() {
    this._super(...arguments);
    $(this.get('elementToFocus') ? this.get('elementToFocus') : 'h1').focus();
  }
});

I have also tried using a property on the mixin and then duplicating the property in the component. This breaks everything and gives me random errors.

import $ from 'jquery';
import Mixin from '@ember/object/mixin';

export default Mixin.create({
  elementToFocus: 'h1',
  didRender() {
    this._super(...arguments);
    $(this.get('elementToFocus')).focus();
});

If you can see what I'm trying to achieve, what's the best way to do this?




Build and Release Ember App to Azure Service Fabric

currently our process works, but it takes too much time due that the fronend Ember app needs to be build into every single environment we have ( 5 environments ). because we never know which environment will be available when we release it. we intend to add even more environments because every developer should have his own working development environment. (because of the backend)

how we do it, is that we create a frontend build and a backend build which creates artifacts. now the frontent build takes around 2 minutes for every environment. ember build --env=test and ember build --env=acceptance and ember build --env=development ... and more

when the artifacts are created we then create the release picking the correct ones depending on which environment we release (this done via release pipeline).

my question is can we make a frontend ember build somehow not depending on the environment? i would like to note that we are using azure service fabric.

thanks!




mercredi 20 février 2019

How to include an ember js helper function inside a handlebar expression

I want to include a helper myHelper inside a link-to expression like below but it seems you cannot have an expression directly inside another expression.

"}} Some text

How could you include a helper function in this instance?




Cannot get eslint to throw warning for no jsDoc on Ember classes, props, actions

I am setting up eslint in my ember project. I want to enforce that all functions, classes, actions, and properties are documented with jsDoc.

The problem that I am facing is that I cannot seem to get the enforcement to work on actions, component declarations, or object properties.

I originally tried "require-jsdoc" but also noted that this rule is deprecated. I then installed eslint-plugin-jsdoc with the following config:

rules: [
  ...
  'jsdoc/check-examples': 0,
  'jsdoc/check-param-names': 1,
  'jsdoc/check-tag-names': 1,
  'jsdoc/check-types': 1,
  'jsdoc/newline-after-description': 1,
  'jsdoc/no-undefined-types': 1,
  'jsdoc/require-description': 1,
  'jsdoc/require-description-complete-sentence': 1,
  'jsdoc/require-example': 1,
  'jsdoc/require-hyphen-before-param-description': 1,
  'jsdoc/require-param': 1,
  'jsdoc/require-param-description': 1,
  'jsdoc/require-param-name': 1,
  'jsdoc/require-param-type': 1,
  'jsdoc/require-returns': 1,
  'jsdoc/require-returns-check': 1,
  'jsdoc/require-returns-description': 1,
  'jsdoc/require-returns-type': 1,
]

And still no luck. Any idea how to get the following working?

// throw eslint warning if not documented
export default Component.extend({
  someProp: false, // throw eslint warning if not documented
  actions: {
    someAction() {} // throw eslint warning if not documented
  }
});


All other natural function definitions are working as expected, just attempting to get these cases working. Thanks!




mardi 19 février 2019

Single page application js

I would like to know, for a single page application, which JS is most preferable and why?

Secondly, we have an application which calls the data every time from the 3rd party application, so it's a good idea to develop an app using a single page application?

Also, Is it possible to load a specific part of the page based on the user request and not to load the whole page every time?




Trying to send a zip from the backend to the frontend

At one point in my ember.js webapp the user is given the option to download a zip file. On clicking the button, an action is triggered that sends a request to the backend server, which generates the zip and returns it. Ideally the zip should then be downloaded automatically.

In my backend endpoint I return with

return Response
        .ok(FileUtils.readFileToByteArray(new File(tmpZipFilename))) // tmpZipFilename is a String
        .type("application/zip")
        .header("Content-Disposition", "attachment; filename=\"" + finalZipFilename + "\"")
        .build();

In the frontend I have (adapted from here)

submit() {
  var formData = new FormData(this);
  let token = this.get('session.data.authenticated.token');
  jquery.ajax({
    url: `myUrl`,
    data: formData,
    processData: false,
    contentType: false,
    beforeSend: function(xhr) {xhr.setRequestHeader('Authorization', `Bearer ${token}`)},
    type: 'POST',
    success: function(data) {
      var blob = new Blob([data], {type: 'application/zip'});
      let a = document.createElement("a");
      a.style = "display: none";
      document.body.appendChild(a);
      let url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = 'myFile.zip';
      a.click();
      window.URL.revokeObjectURL(url);
    },
    failure: function() {
      // other stuff
    }
  })
}

The response headers are the following:

HTTP/1.1 200 OK
X-Powered-By: Undertow/1
Cache-Control: no-store
Date: Tue, 19 Feb 2019 16:34:35 GMT
Server: WildFly/10
Content-Type: application/zip
Content-Disposition: attachment; filename="filename.zip"
Connection: close
Transfer-Encoding: chunked

I have confirmed that tmpZipFilename in the backend section does correctly point to a proper zip file. And when the user clicks the download button a file called myFile.zip is indeed downloaded. However, the file downloaded is not unzippable and is a different size than the correct file pointed to by tmpZipFilename. What am I doing wrong?




lundi 18 février 2019

How can I modify my Ember Addon build based on the template contents?

I'm working on the @fortAwesome/ember-fontawesome addon. I'd like to be able to find the icons that have been used in templates and include the necessary JS into the final build. Template:

I can use

setupPreprocessorRegistry(type, registry) {
  registry.add('htmlbars-ast-plugin', {
    name: 'font-awesome-detect-static-icons',
    plugin: staticIconDetector,
  });
},

This works to discover the icons, but the preprocessors don't do their work until all the other hooks like postprocessTree or treeForVendor have already run. Is there another way to get at the AST of the templates before the other hooks run? Or another way to get at this information?




Will my ember app work in IE browser if I update it from 2.18 to 3.4?

The current version of my ember app is 2.18.0 and the app is working to IE browser as well and if I upgrade it to 3.4 would it not run to IE? If not, what are the versions of IE that it won't run?




Javascript infinite scrolling & multiple AJAX Promises

I am trying to implement infinite scrolling in my app. So I want to make multiple AJAX calls as user scrolls. So I want to get a new set of records from server on scroll. I have an action 'infiniteScrolled' which gets invoked by my custom component on scrolling.

My question is when I try to invoke this.get('handleGridPromise') again, it does not get fired again (probably because the promise was resolved by the 1st call) How can I fix the same ?

handleGridPromise: function() {
    var self = this;
    var request = self.get('serverParams');
    return new Ember.RSVP.Promise(function(resolve, reject){
        var promise = self.updateRequest(request);
        promise.then(function(updateRequest){
            var deferred = self.doXhrPost(updateRequest, self.get('gridURL'), true, false);
            deferred.then(function(response){               
                self.gridDataLoaded(response);
                resolve(self.get('model.gridData'));
            });
        });
    });
}.property('attr1', 'attr2'),


infiniteScrolled(record, index) {
    Ember.set(this.get('serverParams'), 'recordstartindex', index);
    Ember.set(this.get('serverParams'), 'recordendindex', index+50);
    this.get('handleGridPromise').then((records) => {
    const until = Math.min((index + 50), (this.get('model.gridData.length') - 1));
        Ember.run.later(() => {
            for (index; index < until; index++) {
                if (records[index].id === undefined) {
                    records.replace(index, 1, this.get(`model.gridData.${index}`));
                }
            }
        }, 500);
    });
}




dimanche 17 février 2019

Ember renders html via link-to, but json via typing url in browser

This doesn't happen locally in development, but after deploying to Heroku, if I navigate to my app's root page it loads fine and if I click the "posts" link it loads all my posts in html. But if I navigate to the same page by typing the url in the browser's url input, or even if I simply click the refresh button, it loads json instead of html. Inspecting the request, I see that it sends no query params (so the json is not paginated) and there is no Content-Type in the request headers.

Hoping this is a telltale sign of some obvious problem. If not, I could provide more info about my ember/rails setup.




samedi 16 février 2019

Is it possible to create a private or internal ember.js addon?

My Use Case

I work for a company that maintains multiple (like 7 or 8) different websites using Ember.js. Most of these sites have an almost identical navigation bar at the top. The very few changes are things that could easily be inputted as if it were a component or add-on. In order to increase the modularity of our code, I think it would be really cool to import most of our navigation bar code into an add-on and use it across all of our sites.

One of the problems with this approach, however, is that our navigation bar is too internal to want to publish it as a public add-on (only my company would ever need to use it). And so I would rather not post it as a public add-on.

Is this a possible use case for Ember Addons? If so, how might we consider implementing this.




What is the '@' sign used for in Ember.js?

This is a generic question and one that may have even been asked on other forums, such as the Ember forums. But I wanted to add this into StackOverflow.

But my question is why does Ember so often use an @ in front of it's libraries. A quick example, using an Ember component in Ember 3.4:

import Component from '@ember/component';

While at the same time, I had an old project from the 2.0 days that was structured like the following:

import Ember from 'ember';

Why does Ember now include an @ sign?




Different ways of writing module imports

What is the difference exactly between the following 2 ways of writing import statements ?

import Ember from 'ember';

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

Is it like the 2nd way is more efficient or is there something more to it ?




vendredi 15 février 2019

What is the recommended way to shim Object.entries in Ember.js?

Some of my users use Internet Explorer 11 which doesn’t support Object.entries. I’d like to still support that browser but I’m using Object.entries in multiple places within my codebase.

I see that there’s a shim available. Where would be the best place to place this shim within Ember?

Thanks!




Remove meta tag created for ember engine in index.html

I can see meta tag about the config information of the app can be removed from being stored in index.html through this answer.

I need the same to be done for my ember-engine. Currently, this is how my index.html looks. It contains the two meta tags: one about the engine's environment.js and the other about the asset-manifest.json.

<meta name="inventory/config/environment" content="%7B%22modulePrefix%22%3A%22inventory%22%2C%22environment%22%3A%22development%22%7D" />
 <meta name="app/config/asset-manifest" content="%7B%22bundles%22%3A%7B%22inventory%22%3A%7B%22assets%22%3A%5B%5D%7D%7D%7D" />




Ember Data: When do I use findAll() over query()?

This is the pattern I find myself running into:

I start making an app, and I use findAll() to get a list of [something random].

Once the app is being tested with serious data, the number of random resource instances will grow. I need to limit the number of resource instances on screen. I need to start paginating them. For this I need query string support. E.g. page[offset].

So findAll(criteria) is replaced by query(criteria, querystring).

This is a pattern so much that findAll() is starting to look like a development placeholder for query() to be used later.

I'm probably misunderstanding the use for findAll(). Is it true findAll() cannot use pagination at all (without customizing adapter code)? Can someone explain in what cases findAll() should be used?




jeudi 14 février 2019

Where and how to specify initializer for an ember engine?

In my application, I have used initializers to inject services to routes, controllers and components. I am trying to use ember engine now. I have shared my application services to my engine, but I need to inject the shared application services to the engine's routes, controllers and components using an initializer.

In my application, I can generate an initializer and inject the services. How to do that in my engine?




Why does findAll() with ember-pouch return nothing?

Nothing returned from findAll() with ember-pouch

I'm trying to use ember-pouch with an Ember project. Sync from the remote pouchdb is working, but findAll('name_of_db') still returns nothing.

I made a demo app to hopefully make this question easier to answer.

Demo App

  • git clone git@github.com:chroaster/ember-pouch-cant.git
  • cd ember-pouch-cant
  • npm install
  • ember serve



Closure actions in Ember

I'm rewriting some old Ember code to use closure actions, but I'm new to Ember and I can't seem to figure out how to change a sendAction that hasn't got parameters.

This is the code in the component row.js:

 click: function() {
        this.sendAction();
      }

The row.hbs as well as the parent templates are just



so I can't add anything there it seems. Does anyone know how to solve this?




mercredi 13 février 2019

Detect when a socket io connection has been changed with ember

Im using ember with socket.io and I want a computed property that changes to if the socket io connection is connected or disconnected.

I am using ember-websockets and here is what I have tried:

socketIOService: service('socket-io'),
socketRoute:     'http://localhost:8080/',

connected: computed('socketIOService',
function()
{
    console.log('changed!');
    //return (this.get('socketIOService').socketFor(this.get('socketRoute').socket.connected));
}),

startConnection()
{
    this.get('connected');
    const socket = this.socketIOService.socketFor(this.get('socketRoute'));

    socket.on('initialised', this.initialised, this);
},

So this doesnt work because im guessing the service doesnt change. I would like to be able to computer a value from the following...

this.socketIOService.socketFor(this.get('socketRoute'));

But I cant get the sockerFor property in a computed property.




How to deal with transitionTo in FastBoot and Nginx?

I run up FastBoot on port 3443 and use nginx as the reverse proxy. There are the next lines in nginx config file:

proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-NginX-Proxy true;

When in some place called transitionTo FastBoot tries to redirect to host myhost.com:3443 but port 3443 isn't public. How can I make FastBoot doesn't add the port to my host?




How To Use Packery with Ember

I just started ember and want to use packery as layouting library. The ember app has been created via ember new wep-app. Packery has been installed via npm install packery. According to ember dependency management, I can load Packery via app.import('node_modules/packery/js/packery.js')

How do I use packery now? The application.hbs looks like this

<div class="grid">
   <div class="grid-item">cdsc</div>
   <div class="grid-item grid-item--width2">...</div>
   <div class="grid-item">...</div>
</div>

But it seems not to work. In a similar question, someone mentions the creation of a component ember g component packery-grid, which should be filled accordingly

import Component from '@ember/component';

export default Component.extend({
   classNames: ['grid'], 
   didInsertElement() {
   this.$('.grid').packery({
       // options
       itemSelector: '.grid-item'
       });
   }
 }); 

Using a component, the application.hbs template should look like this:


<div class="grid-item">cdsc</div>
<div class="grid-item grid-item--width2">...</div>
<div class="grid-item">...</div>


However, this does not work either. What shall I do to have packery integrated into ember? I use ember 3.5.1.

EDIT: There is an ember component for packery as well, which does not work as well.




mardi 12 février 2019

how to dynamically change app.scss value in ember js

I have a situation where the api is providing me with a colour and the colour of some parts of the site should be based on the colour provided by the api, right now the value is hard coded in app.scss file, is there a way where i can dynamically change the value of it?

consider this case, i am on user route, and user model is providing me with a colour yellow, now how do i apply this colour to the body tag, the footer etc? and there are other addons whose colors needs to be changed, right now i have hard coded the color of the addon in app.scss

is there a way i can change the color of app.scss based on the color supplied by the api?




Initialize a service on app startup without initializer

I have a service in Ember 2.18 named testing. e.g.

export default Service.extend({ //some code })

I need to be able to initialize this testing service in the app from within the service if possible. Essentially want to inject the service across the app globally from within the service without using an initializer. Is this possible?




Mobile Safari aborts Get requests

We have a complex webapplication which works without problems on crossplatform desktop and mobile devices except Safari Mobile on different ios devices.

On slower connection settings like 3g but also DSL (set in the Network Link Conditioner) Get requests are arbitrary aborted. The aborted requests are Get requests to image resources (mostly loaded by THREE.js for Aframe) and XHR requests to a rest backend.

The requests does not reach the server, there are no logs in the nginx access.log files. The Access-Control-Allow-Origin Header is set to * and we also created an environment with the same domain for all resources. But this did not solve the abortions.

We build an ios App with Cordova and in xCode NSURLErrorDomain -999 errors are thrown.

In the Network Tab of the Safari Web Inspector we get following logs:

enter image description here

enter image description here




lundi 11 février 2019

EmberJS 2.15.1 Could not find module `fullcalendar`

So I've recently updated my app to Ember 2.15.1 and I'm attempting to switch everything over to NPM from Bower. I have been playing around trying to get fullcalendar to cooperate, but have not had much luck (last one to switch over too). Figured it could have been a cache issue so both NPM/Bower cache and reinstalled both. Below is the error and the code for importing it.

I have import 'fullcalendar'; at the top of the calendar component.

Uncaught Error: Could not find module `fullcalendar` imported from `name/components/calendar`
    at missingModule (loader.js:247)
    at findModule (loader.js:258)
    at Module.findDeps (loader.js:168)
    at findModule (loader.js:262)
    at requireModule (loader.js:24)
    at Class._extractDefaultExport (index.js:389)
    at Class.resolveOther (index.js:109)
    at Class.superWrapper [as resolveOther] (ember-utils.js:423)
    at Class.resolve (resolver.js:164)
    at resolve (container.js:873)

When the import is removed I get a standard "fullCalendar is not a function" error. Removing/adding import $ from 'jquery'; does not change either of these. Here's the part of the code it errors out on, though removing it just moves down to the next mention of fullCalendar.

 didInsertElement: function(){
      $('.sample-calendar').fullCalendar({
        header: {
          left: '',
          center: '',
          right: 'title prev,next'
        },
        events: [],
        theme: true,
        aspectRatio: 0
      });
    },

The imports from ember-cli-build.

app.import('node_modules/fullcalendar/dist/fullcalendar.min.js');
app.import('node_modules/fullcalendar/dist/fullcalendar.min.css');
app.import('node_modules/fullcalendar/dist/plugins/gcal.min.js');

And then my package.json.

"devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^3.0.0",
    "ember-cli": "~2.15.1",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-babel": "^6.3.0",
    "ember-cli-datepicker": "wesm87/ember-datepicker#master",
    "ember-cli-dependency-checker": "^2.0.0",
    "ember-cli-eslint": "^4.0.0",
    "ember-cli-htmlbars": "^2.0.1",
    "ember-cli-htmlbars-inline-precompile": "^1.0.0",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-moment-shim": "~3.5.0",
    "ember-cli-qunit": "^4.0.0",
    "ember-cli-shims": "^1.1.0",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "~2.15.0",
    "ember-export-application-global": "^2.0.0",
    "ember-fetch": "3.4.0",
    "ember-load-initializers": "^1.0.0",
    "ember-moment": "~7.5.0",
    "ember-resolver": "^4.0.0",
    "ember-source": "~2.15.0",
    "eslint-plugin-ember": "~4.1.2",
    "fullcalendar": "^4.0.0-alpha.4",
    "loader.js": "^4.2.3",
    "pikaday": "~1.4.0",
  },




How to retrieve the same model from another REST url in EmberJS

The models tree of my emberJS app match the tree of my API however, I have 2 different routes returning the same type of data :

/products/ and /users/:id/supported_products/ both return products data.

When I need to have the products of the app there is no problem :

 this.store.query('product',params);

However I am not sure how to query products from the user path. The place to do so would be the adapter, but I need to define a secondary adapter that I would call when I need supported products,and I have no idea how to do so.




samedi 9 février 2019

Cannot create a controller in ember, I am met with an error every time

To generate the component, I use

$ ember generate component my-component-name

But I am met with this long error:

ENOENT: no such file or directory, lstat 'C:\Users\admin\AppData\Local\Temp\broccoli-3688mdxntFeSoJd5\out-114-broccoli_merge_trees_full_application/tests/index.html' Expand stack frames Broccoli Plugin: Funnel ENOENT: no such file or directory, lstat 'C:\Users\admin\AppData\Local\Temp\broccoli-3688mdxntFeSoJd5\out-114-broccoli_merge_trees_full_application/tests/index.html' at Funnel (Funnel (test index)) -~- created here: -~- at Funnel.Plugin (C:\Users\admin\datatable\node_modules\broccoli-plugin\index.js:7:31) at new Funnel (C:\Users\admin\datatable\node_modules\broccoli-funnel\index.js:57:10) at DefaultPackager.processTestIndex (C:\Users\admin\datatable\node_modules\ember-cli\lib\broccoli\default-packager.js:944:17) at DefaultPackager.packageTests (C:\Users\admin\datatable\node_modules\ember-cli\lib\broccoli\default-packager.js:906:26) at EmberApp._legacyPackage (C:\Users\admin\datatable\node_modules\ember-cli\lib\broccoli\ember-app.js:1729:46) at EmberApp.toTree (C:\Users\admin\datatable\node_modules\ember-cli\lib\broccoli\ember-app.js:1766:27) at module.exports (C:\Users\admin\datatable\ember-cli-build.js:23:14) at Builder.readBuildFile (C:\Users\admin\datatable\node_modules\ember-cli\lib\models\builder.js:52:14) at Builder.setupBroccoliBuilder (C:\Users\admin\datatable\node_modules\ember-cli\lib\models\builder.js:66:22) at new Builder (C:\Users\admin\datatable\node_modules\ember-cli\lib\models\builder.js:32:10) -~- (end) -~- Error: ENOENT: no such file or directory, lstat 'C:\Users\admin\AppData\Local\Temp\broccoli-3688mdxntFeSoJd5\out-114-broccoli_merge_trees_full_application/tests/index.html' at Object.lstatSync (fs.js:863:3) at symlinkWindows (C:\Users\admin\datatable\node_modules\symlink-or-copy\index.js:126:25) at Function.symlinkOrCopySync [as sync] (C:\Users\admin\datatable\node_modules\symlink-or-copy\index.js:83:5) at Funnel._copy (C:\Users\admin\datatable\node_modules\broccoli-funnel\index.js:494:19) at Funnel.processFile (C:\Users\admin\datatable\node_modules\broccoli-funnel\index.js:477:8) at Funnel.applyPatch [as _applyPatch] (C:\Users\admin\datatable\node_modules\broccoli-funnel\index.js:390:12) at Funnel. (C:\Users\admin\datatable\node_modules\broccoli-funnel\index.js:344:10) at Array.forEach () at Funnel.processFilters (C:\Users\admin\datatable\node_modules\broccoli-funnel\index.js:343:11) at Funnel.build (C:\Users\admin\datatable\node_modules\broccoli-funnel\index.js:259:10)

My code works perfectly before generating a controller.

I am using broccoli-builder@2.0.1, node@v11.6.0, running on Windows 7

Add ons:

amd-transform (unknown version) Couldn't find find info about this package

tests-server-middleware (unknown version) Couldn't find find info about this package

history-support-middleware (unknown version) Couldn't find find info about this package

live-reload-middleware (unknown version) Couldn't find find info about this package

broccoli-watcher (unknown version) Couldn't find find info about this package

broccoli-serve-files (unknown version) Couldn't find find info about this package

proxy-server-middleware (unknown version) Couldn't find find info about this package

testem-url-rewriter (unknown version) Couldn't find find info about this package

@ember/jquery (0.5.2) The default blueprint for ember-cli addons.

@ember/optional-features (0.6.4) The default blueprint for ember-cli addons.

ember-addons-inspector (1.1.0) Inspect the addons included in your Ember application or Ember addon

ember-ajax (3.1.3) Service for making AJAX requests in Ember applications.

ember-cli-app-version (3.2.0) Adds App version number to Ember Inspector Info Tab

ember-cli-babel (7.2.0) Ember CLI addon for Babel

ember-cli-dependency-checker (3.1.0) Ember CLI addon for detecting missing npm and bower dependencies before executi g ember commands

ember-cli-htmlbars (3.0.1) A library for adding htmlbars to ember CLI

ember-cli-htmlbars-inline-precompile (1.0.5) Precompile inline HTMLBars templates via ES6 tagged template strings

ember-cli-uglify (2.1.0) JavaScript minification for Ember-CLI

broccoli-asset-rev (2.7.0) broccoli asset revisions (fingerprint)

ember-cli-sri (2.1.1) SRI generation for Ember CLI

ember-cli-template-lint (1.0.0-beta.2) Lint your handlebars templates.

ember-data (3.7.0) A data layer for your Ember applications.

ember-export-application-global (2.0.0) Sets window.MyAppName up as the application instance upon boot.

ember-load-initializers (1.1.0) A tiny add-on to autoload your initializer files in ember-cli.

ember-maybe-import-regenerator (0.1.6) The default blueprint for ember-cli addons.

ember-resolver (5.0.1) The default modules based resolver for Ember CLI.

ember-source (3.7.0) A JavaScript framework for creating ambitious web applications

ember-welcome-page (3.2.0) Welcome page for Ember CLI applications

loader.js (4.7.0) loader.js =========

ember-qunit (3.5.3) QUnit helpers for testing Ember.js applications

qunit-dom (0.8.4) High Level DOM Assertions for QUnit

I am also getting a message that ember-cli-babel 5.x has been deprecated. Not sure if its related.




vendredi 8 février 2019

Should I always include this._super(...arguments) when overwriting an Ember member function

In Ember.js, there are a lot of functions that require you to call this._Super(...arguments) before calling them. A quick example from the documentation:

import Component from '@ember/component';

export default Component.extend({
  didRender() {
    this._super(...arguments);
    console.log('I rendered!');
  }
});

Are there ever cases in Ember where we do not need to call this._super()? The reason I ask is because often times, I will write some hooks for either my controllers or routes where I simply forget to call this._super(...arguments) and, as far as I can tell, everything works the same.

Should I always include a super() method before overwriting any member function in Ember?




Passing the value of an html element as a parameter in ember

I am sorry if this is a dumb question, but I just can't seem to figure it out. I need to pass the value of the row element to the function it calls, but I can't seem to access the value. I can't give the row a unique id, because my process of adding rows to the table involves duplicating the row and altering its value. Here is my code:

    <tr value = "0" onmouseover=>

          //     ^ This is the value I am trying to pass      ^ This is how I am trying to pass it

I have tried this.value, value="target.value", value, etc. but all come out to undefined. The only way I have got the parameter to be undefined is if I just sent "0" as the parameter instead of this.value.




Can you make a module visible in an Ember unit test?

My boss says we should use a unit test. I have to test the functionality of a calendar module with click functions, is it possible to make a module visible in a unit test so I can run click() methods on it to test features or are unit tests always invisible in Ember?

I've tried making a unit test with similar syntax to an integration test but it doesn't work. I need to see the module to run click methods on it to test basic functionality, is this possible?

module('Unit | Mixin | eg picker/calendar single')

test('it works', function (assert) {
let EgPickerCalendarSingleObject = 
EmberObject.extend(EgPickerCalendarSingle);
let subject = EgPickerCalendarSingleObject.create();
assert.ok(subject);
});




Is there a hook in either the controller or router to be called after all DOM elements have been rendered?

Let's say I want to do some jQuerry Stuff

// Do jQuery Stuff
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});


And I want to include this code in either the route or the controller, I'm quite sure I cannot implement this because there's no hook function (I.E. model(), renderTemplate(), etc. that I can use that guarantees that all the elements in the DOM have safely been rendered.

Now, if I were doing this in a component, I know I could call the didInsertElement hook and that could would allow me to run the code above.

My Use Case

I want to use a library called ScrollMagic which would require jQuery to configure. Someone other than me has already written a lot of code in the route and controller. We could easily just move this to a component (and we probably will), but I still wanted to ask this for my own curiousity.

Question

Is there any hook in either the route or the model that guarantees all the elements of that template have been rendered in the DOM? If not, why is that? After all, you have that hook available in a component.




How to implement a login page with JSON Web Token in Ember app with express api

I added authentication for my Express API following this guide and after testing my secret-routes everything seems to work properly. Now my question is how can this be used in an Ember app login page. After receiving the secret token after a successful login how does the browser know you are signed in. How would one log out? How does the ember application know who is signed in? Is there any thing in particular security wise that I should be at tentative to while working on this?




ember-simple-auth and Implicit Grant authentication: use authenticateSession test helper

If a User is not authenticated, I redirect him to a corporate login page:

https://super-secret-gateway/authorization.oauth2?client_id=XXXX&redirect_uri=http://localhost:4200/callback&response_type=token&scope=profile%20openid

Once he is authenticated after entering his username and password, he is redirected back with the following URL

https://myapp/callback#access_token=2YotnFZFEjr1zCsicMWpAA&type=Bearer&expire_in=3600&state=myAppRandomState

I can't figure out how to use authenticateSession test helper in this case. The ESA docs have no detailed example about that and the way I do it is not working:

module('Acceptance | Dashboard', function(hooks) {
  setupApplicationTest(hooks);
  setupMirageTest(hooks);

  test('Authenticated users can visit /dashboard', async function(assert) {
    let shop = this.server.create('shop');
    this.server.create('user', { shop });

    await authenticateSession({
      token: 'abcdDEF',
      token_type: 'Bearer'
    });

    await visit('/dashboard');

    assert.equal(currentURL(), '/dashboard', 'user is on dashboard page');
  });
});

What am I missing ? Thank you.




Emberjs watching for variable changes passed from parent component?

I have the following code on child component to listen to changes

import Component from '@ember/component';
import Ember from 'ember';

export default Component.extend({

  coordinates: Ember.computed("mouse_x", "mouse_y", function () {
    let val = ` ${mouse_x},${mouse_y}`;
    console.log(val);
    return val;
  }),

  coords_change_observer: Ember.observer('coordinates', function () {
    console.log(this.coordinates);
  })
});

The values mouse_x and mouse_y are set properly as i verified that from the view. I am passing that to this component from another component using




The basic goal being listening to changes on the variables passed through parent and process them. The issue being neither the computed nor the observer method is being invoked. Where am i going wrong with this ?

Note that both of them are components and one of them being a child component inside another. Any help is appreciated




jeudi 7 février 2019

Ember component POST to Express API gives error

When trying to do a post from a component in my ember app to my express api I am receiving

SyntaxError: Unexpected token V in JSON at position 0

When checking what response I'm receiving in the network inspector on chrome I see

ValidationError: body: Path `body` is required., title: Path `title` is required. undefined



The blogpost.title and .body both return the correct values but the blogpost gives me

adapterError: SyntaxError: Unexpected token V in JSON at position 0 at parse

EmberApp/App/Components/create-new-post/Component.js

export default Component.extend({
  blogpost: null,
  router: inject('-routing'),
  actions: {

    save: function (blogpost) {
      console.log(blogpost.title);
      console.log(blogpost.title);
      console.log(blogpost);

      blogpost.save()
          .then(
            (value) => {
              Ember.Logger.info(value);
              this.get('router').transitionTo('index')
            }
          )
          .catch(
            (err) => {
              Ember.Logger.info('failure to save');
              console.log(err);
            }
          )

    }
  }
});

EmberApp/App/Components/create-new-post/template.hbs

<form  >
  <p>
    
  </p>
  <p>
    
  </p>
  <p>
    <button class="btn btn-primary btn-block" type="submit" value="Save">Publish</button>
  </p>
</form>

EmberApp/App/routes/createpost.js

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

export default Route.extend({
  model() {
    return this.store.createRecord('blogpost');
  }

});

EmberApp/App/templates/createpost.hbs

<div class="container">
  <div class="col-sm-12 pull-left">
    
  </div>
</div>

I have confirmed that the api route for post is working with postman so I'm not sure what the issue is with ember.




EmberJS hasMany doesn't fetch relationships

I have a problem with serializing my response which looks like:

{
"data": [
    {
        "id": 930,
        "uniqueId": "0d3a04cb-231c-4998-b4d3-9436a0a3138e",
        "name": "DRINKI",
        "lastEditDate": "2018-02-12T13:30:32",
        "lastEditDateUTC": "2018-02-12T12:30:32",
        "deleted": false,
        "discountable": true,
        "productCategoryPointOfSales": []
    },
    {
        "id": 921,
        "uniqueId": "5fbf423a-4932-47ca-b32f-5d3612dd73ee",
        "name": "BALOTYNKI SOLO",
        "lastEditDate": "2019-02-07T14:20:15",
        "lastEditDateUTC": "2019-02-07T13:20:15",
        "deleted": false,
        "label": "",
        "color": "#a0a5a9",
        "discountable": true,
        "productCategoryPointOfSales": [
            {
                "id": 142,
                "pointOfSaleUniqueId": "98e370f2-9d37-4473-9446-d82e442593fe",
                "directionId": 54,
                "directionUniqueId": "f0c986c0-ef85-4a46-86ea-cd997981fe8a",
                "kitchenUniqueId": "f0c986c0-ef85-4a46-86ea-cd997981fe8a",
                "inactive": false
            }
        ]
    }
],
"total": 0
}

And the error I get:

Encountered a relationship identifier without a type for the hasMany relationship 'productCategoryPointOfSales' on <category:5fbf423a-4932-47ca-b32f-5d3612dd73ee>, expected a json-api identifier with type 'product-category-point-of-sale' but found '{"id":"142","pointOfSaleUniqueId":"98e370f2-9d37-4473-9446-d82e442593fe","directionId":54,"directionUniqueId":"f0c986c0-ef85-4a46-86ea-cd997981fe8a","kitchenUniqueId":"f0c986c0-ef85-4a46-86ea-cd997981fe8a","inactive":false}'. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.

Models:

export default DS.Model.extend({
productCategoryPointOfSales: DS.hasMany('product-category-point-of-sale'),

uniqueId: DS.attr('string'),
name: DS.attr('string'),
label: DS.attr('string'),
color: DS.attr('string'),
discountable: DS.attr('boolean')
});

export default DS.Model.extend({
category: DS.belongsTo('category'),

pointOfSaleUniqueId: DS.attr('string'),
directionId: DS.attr('string'),
directionUniqueId: DS.attr('string'),
kitchenUniqueId: DS.attr('string'),
inactive: DS.attr('boolean')
});

And my serializer:

export default DS.RESTSerializer.extend(EmbeddedRecordMixin, {
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
payload = {
  category: payload.data,
};

return this._super(store, primaryModelClass, payload, id, requestType);
},
primaryKey: 'uniqueId',

attrs: {
  productCategoryPointOfSales: {embedded: 'always'}
}
});

I'm very new to EmberJS and have no idea how to solve this problem. It looks like root tags for my embedded object are missing. I followed some tutorials and tried with EmbeddedRecordMixin but it didn't help me. Could you please help me figuring this out?




How to keep data synchronized in ember using ember-apollo-client?

I have an app built using Ember and ember-apollo-client.

// templates/collaborators.hbs

// opens an ember-bootstrap modal
Create collaborator
// submit button in modal triggers "createCollaborator" in controller    


     


// routes/collaborators.js
import Route from '@ember/routing/route';
import { RouteQueryManager } from 'ember-apollo-client';
import query from '../gql/collaborators/queries/listing';

export default Route.extend(RouteQueryManager, {
    model() {
        return this.get('apollo').watchQuery({ query }); 
    }
});

// controllers/collaborator.js
export default Controller.extend({
  apollo: service(),

  actions: {
    createCollaborator() {
      let variables = { 
        firstName: this.firstName, 
        lastName: this.lastName, 
        hireDate: this.hireDate 
      }

      return this.get('apollo').mutate({ mutation, variables }, 'createCollaborator')
        .then(() => {
          this.set('firstName', '');
          this.set('lastName', '');
          this.set('hireDate', '');
      });
    }
  }
});

Currently, after creating a collaborator the data is stale and needs a browser refresh in order to update. I'd like the changes to be visible on the collaborators list right away.

From what I understood, in order to use GraphQL with Ember, I should use either Ember Data with ember-graphql-adapter OR just ember-apollo-client. I went on with apollo because of its better documentation.

I dont think I quite understood how to do that. Should I somehow use the store combined with watchQuery from apollo? Or is it something else?




How would i know which object has been updated on model.@each EmberJS

Im trying to change an object property in a list of object and would like to get that object right after it was changed.

My approach is to observe property changes on that list through model.@each.property_1

export default Ember.Controller.extend({

  onModelProperty1Change: function(){
    // How can i get that particular object after one of it 
    // property was changed inside here?
    //
    // do some database action to the object...

  }.observes('model.@each.property'),

});

I wonder if this is a right approach. Or should I go for change event on element instead? Either way I need to know it is possible to get that object inside observes helper.




How to reload route model from controller in Ember?

I am currently struggling with a task that I expected to be quite easy or common: I'd like to initiate a reload of the route model in the controller. As far as I can see, there is no easy way of doing this? Yes, I can access a RouteInfo object by the target property of the controller, but from there I see no way to refresh the model.

A little background about the task I try to solve: I have a route with a model that provides the last object from a collection that has a certain flag not set (e.g. "not indexed" in route /index-object). Now the user works on this object an triggers an action in the controller which set this flag (to "indexed"). So if I reload the route by navigating back and forth the next object is shown. But I want to trigger this reload directly in the action (without reloading the whole page, of course).

My question: Is this possible or is there another/right way of accomplishing what I try to achieve?




how to access ENV variables in index.html in ember.js

I am using ember.js, there is a requirement for us where we have to show a script tag(index.html file) only in production and not in development. Is there a way to achieve this?




mercredi 6 février 2019

How to fix "stretched view" of camera stream on some devices

I stream my "environment" camera to a video element on my DOM using navigator.mediaDevices.getUserMedia. The issue is that on my test-device (Samsung Tab) this video seems to be stretched. I'm not using any constraints other than facingMode: "environment", during my tests. I don't have this problem on my mobile device.

I already tried setting width and height constraints, this only works if I staticly set the values of my tablet cam, but my application has to support all devices. Note: my application is locked to portrait. built for android using cordova.

//code streaming

setup() {
    const constraints = {
      video: {
        facingMode: "environment",
        //tablet
        //width: {min:1280, ideal: width},
        //height: {min:720, ideal: height}
      },
      audio: false
    };

    navigator.mediaDevices.getUserMedia(constraints)
      .then(function (s) {
        video.srcObject = s;
        video.play();
      })
      .catch(function (err) {
        console.log("An error occured! " + err);
      });

    if(!this.get('streaming')) {
      video.addEventListener("canplay", function () {
        _this.set('videoReady', true);
        _this.processMedia();
      }, false);
    }
}
processMedia() {
    let _this = this;
    let video = document.getElementById('videoInput');
    if (!this.get('streaming')) {
      video.width = video.videoWidth;
      video.height = video.videoHeight;
      this.placeIndicators(video.width, video.height);
    }
   //process functionality//
}

Expected behaviour: to get a video element with my environment camera stream with a correct aspect ratio on all devices.

Actual behaviour: on my tablet my video stream is "stretched when the device is held landscape and "squeezed" when held portrait




mardi 5 février 2019

Force coverage increase in gitlab PRs

In an effort to increase test coverage by requiring unit tests for every pull request on my EmberJS project hosted on gitlab, I want pipelines to fail if the coverage doesn't increase.

I can get the coverage output using istanbul and get the coverage badge displaying correctly using the following regex:

Gitlab CI screenshot

And using this gitlab-ci.yml:

image: sergiolepore/ember-cli

before_script:
  - yarn --ignore-engines
  - bower --allow-root install

"Ember Unit Tests":
  script:
    - COVERAGE=true npm test -- --filter=Unit
    - grep -o '"pct":\d*\.\d*' coverage/coverage-summary.json | head -1

How can I get the next pipeline to fail if the coverage is decreased in a PR?




Ember: Run-loop: How to know if a job is scheduled or complete

scheduleOnce('afterRender', function x() {
    // Do something
});

Let's say I've scheduled a job (function x) like this and go to some other function (an event callback). Inside that, how do I know the above job's status (eg., scheduled, completed)?




Getting Emberjs data from an Express Api

I built an express api connected to an ember app following this guide. I verified that my api routes are working correctly with postman. The issue arises when I try to call a GET from ember.

MEENApp/app/routes/routes.js

    router.get('/blogposts',(req, res) => {
console.log("API GET REQUEST");
BlogPostSchema.find({}, (err,blogpost) => {
    if(err) {
        res.send(err);
    }
    console.log(blogpost);
    res.json(blogpost);
})});

When being called from the ember app the console.log(blogposts) outputs the correct information to the console

    [ { _id: 5c588e1bc23c5e5620c59b4e,
    title: 'Helloooo',
    body: 'teeest',
    datePosted: 2019-02-04T19:10:19.422Z,
    __v: 0 },
  { _id: 5c589c1f773a76461cf1e4be,
    title: 'titletest',
    body: 'bodytest',
    datePosted: 2019-02-04T20:10:07.790Z,
    __v: 0 },
  { _id: 5c58becee53d4925a88c20fb,
    title: 'titletest2',
    body: 'titletest2',
    datePosted: 2019-02-04T22:38:06.660Z,
    __v: 0 },
  { _id: 5c58cf647d0a52086c5aac5d,
    body: 'rere',
    title: 'rerere',
    datePosted: 2019-02-04T23:48:52.477Z,
    __v: 0 } ]

Ember however does not show this data once called.

MEENAPP/EmberApp/App/routes/Index.js

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

export default Route.extend({
  model() {

    var code = this.store.findAll('blogpost');
    console.log(code);
    return this.store.findAll('blogpost');
  }
});

Console in chrome shows

{isFulfilled: false, isRejected: false, _objectsDirtyIndex: 0, _objects: null, _lengthDirty: true, …}

But it works if I were to manually enter the data into ember that the api gave me like

MEENAPP/EmberApp/App/routes/Index.js

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

    let blogposts = [
      {
        "_id": "5c588e1bc23c5e5620c59b4e",
        "title": "Helloooo",
        "body": "teeest",
        "datePosted": "2019-02-04T19:10:19.422Z",
        "__v": 0
      },
      {
        "_id": "5c589c1f773a76461cf1e4be",
        "title": "titletest",
        "body": "bodytest",
        "datePosted": "2019-02-04T20:10:07.790Z",
        "__v": 0
      },
      {
        "_id": "5c58becee53d4925a88c20fb",
        "title": "titletest2",
        "body": "titletest2",
        "datePosted": "2019-02-04T22:38:06.660Z",
        "__v": 0
      },
      {
        "_id": "5c58cf647d0a52086c5aac5d",
        "body": "rere",
        "title": "rerere",
        "datePosted": "2019-02-04T23:48:52.477Z",
        "__v": 0
      }
    ];


    export default Route.extend({
      model() {
        return blogposts;
      }
    });

The way I'm displaying this is through a view-post component that shows a post and I loop through the model in the index page to display the posts.

MEENAPP/EmberApp/App/models/blogpost.js

import DS from 'ember-data';

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

MEENAPP/EmberApp/App/Components/view-post/template.hbs

  <p> - </p>

MEENAPP/EmberApp/App/templates/index.hbs


  


I'm confused on which part is incorrect. As far as I can see the API works and ember correctly made the call to it.




lundi 4 février 2019

EmberJS - Can't find NPM package in 'registry' when vendor loader looks for modules

I have been running an EmberJS app and I just installed a new package using Yarn graphql@0.13.0. For sanity, I checked my package.json file and it is in there. Also when I run yarn list --depth=0, I can see that the package was successfully installed.

├─ graphql-tag@2.10.1
├─ graphql-tools@2.24.0
├─ graphql@0.13.0

I start my Ember app and I get this error straight away.

Uncaught Error: Could not find module graphql imported from `ember-cli-mirage-graphql/related-records

I checked ember-cli-mirage-graphql to see if it was a dependency version issue, but the graphql dependency of ember-cli-mirage-graphql is 0.13.0. I went into the stack trace where the exception is happening, to debug the issue at /assets/vendor/loader/loader.js. There is a function that takes a dependency name, in this case I could see it was 'graphql', and uses that as a key to a registry dictionary to find and load the package. I looked into the registry and could see that a lot of other packages I expected to find were in fact there and it was only that package that was missing.

function missingModule(id, referrer) {
    throw new Error('Could not find module `' + id + '` imported from `' + referrer + '`');
  }

  function findModule(id, referrer, pending) {
    var mod = registry[id] || registry[id + '/index'];

    while (mod && mod.isAlias) {
      mod = registry[mod.id] || registry[mod.id + '/index'];
    }

    if (!mod) {
      missingModule(id, referrer);
    }

    if (pending && mod.state !== 'pending' && mod.state !== 'finalized') {
      mod.findDeps(pending);
      pending.push(mod);
    }
    return mod;
  }

I looked online, but couldn't find anything helpful. What registry is this and why isn't it updated with the new package I installed? Is there a way I can reset the registry?




dimanche 3 février 2019

GET http://bit.ly/2UwVxWi net::ERR_ABORTED 404 (Not Found)

I'm serving my local ember app in https. Followed the example which was given in https://github.com/ember-cli/ember-cli-inject-live-reload. It was working fine in ember 2.18.0

.ember-cli:

{
...
 "liveReloadPort": 37531,

  // This `liveReloadOptions` property becomes `window.LiveReloadOptions`
  "liveReloadOptions": {
    "port": 37631,
    "https": true,
    "host": "livereload.app-name.local"
  },

  "liveReloadJsUrl": "https://app-name.local/livereload.js"
}

after updating ember to 3.7.1 and ember-cli-inject-live-reload to 2.0.1 getting error in browser console

GET https://app-name.local/livereload.js net::ERR_ABORTED 404 (Not Found)
(anonymous) @ ember-cli-live-reload.js:14
(anonymous) @ ember-cli-live-reload.js:15

ember-cli-live-reload.js:

(function() {
  window.LiveReloadOptions = {"port":37631,"https":true,"host":"app-name.local","snipver":1};
  var srcUrl = 'https://app-name.local/livereload.js';
  var host= location.hostname || 'localhost';
  var liveReloadPort = 37531;
  var defaultPort = location.protocol === 'https:' ? 443 : 80;
  var port = liveReloadPort || location.port || defaultPort;
  var path = '&path=_lr/livereload';
  var prefixURL = (location.protocol || 'http:') + '//' + host + ':' + 37531;
  var src = srcUrl || prefixURL + '/_lr/livereload.js?port=' + port + '&host=' + host + path;
  var script    = document.createElement('script');
  script.type   = 'text/javascript';
  script.src    = src;
  "line 14" document.getElementsByTagName('head')[0].appendChild(script);
}());

Even after changing liveReloadJsUrl and liveReloadOptions.host to same name throws error

GET https://livereload.app-name.local/livereload.js net::ERR_ABORTED 404 (Not Found)

.ember-cli

{
  /**
    Ember CLI sends analytics information by default. The data is completely
    anonymous, but there are times when you might want to disable this behavior.

    Setting `disableAnalytics` to true will prevent any data from being sent.
  */
  "disableAnalytics": true,
  "liveReloadPort": 37531,

  // This `liveReloadOptions` property becomes `window.LiveReloadOptions`
  "liveReloadOptions": {
    "port": 37631,
    "https": true,
    "host": "livereload.app-name.local"
  },

  "liveReloadJsUrl": "https://livereload.app-name.local/livereload.js"
}

Here are my nginx config files nginx/servers/app-name_local.conf

upstream app {
  server localhost:4200;
}

server {
  listen       80;
  server_name app-name.local;
  return 302 https://$server_name$request_uri;
}

server {
  listen 443 ssl;
  server_name app-name.local;
  ssl_certificate <path_to_ssl_cert>;
  ssl_certificate_key <path_to_ssl_cert_key>
  #create assess and error log files 
  access_log /usr/local/var/log/nginx/app-name/access.log;
  error_log /usr/local/var/log/nginx/app-name/error.log;
  try_files $uri /index.html $uri @app;
  #change path here
  root <path_to_ember_app>;
  #the following code is only for dev
  location ~ ^/livereload.js {
    rewrite  ^/(livereload.js)  /$1 break;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";   
    proxy_pass http://localhost:37531;
  }
  #end of dev only code
  location @app {
    proxy_pass http://app;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
  }
}

nginx/servers/livereload_app-name_local.conf

upstream livereload {
  server localhost:37531;
}

server {
  listen 37631 ssl;
  server_name livereload.app-name.local;
  ssl_certificate <path_to_ssl_cert>;
  ssl_certificate_key <path_to_ssl_cert_key>;
  access_log /usr/local/var/log/nginx/app-name/access.log;
  error_log /usr/local/var/log/nginx/app-name/error.log;
  try_files $uri /index.html $uri @livereload;
  root <path_to_ember_app>;
  location /{
    proxy_pass http://localhost:37531;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   html;
  }
}




samedi 2 février 2019

"Cannot read property 'formatTime' of undefined" error in array.sort() function

I have an array.sort() function that sorts times, however, it keeps returning this error. Here is my code:

  sortTime(columnIndex, sortingAZ){
  var rowArray = this.get('tableArr').slice(0); //gets array of arrays
    rowArray.sort(function(a,b) {
        var time1 = this.formatTime(a[columnIndex]); //formats time into military time
        var time2 = this.formatTime(b[columnIndex]);
        return time1 - time2;
        });

and here is the formatTime function that is called:

   formatTime(time){

//seperates time into hours and minutes
var colonIndex = time.search(":");
var hour = parseInt(time.substring(0, colonIndex));
var minute = time.substring(colonIndex+1, time.length);
if(time.search("pm")>=0&&hour!=12){ //if it is pm, add 12 to convert to military time (except 12 pm)
    hour+=12;
}
else if(time.search("am")>=0&&hour==12){ //if it is 12 am, set hour to 0
hour = 0;
}
var milTime = hour.toString()+minute.toString(); //recombine hour and minute
milTime = parseInt(milTime);
return milTime;
}

I have tested the formatTime() function by calling console.log(formatTime(rowArray[0][columnIndex])), and it executes correctly, no error. The error seems to be local to the rowArray.sort() function.

Also, I am relatively new here, so let me know if you need any more information or if there is something wrong with my post.




Ember: Add objects to an Array

I have an array

ABC =  [
0: {class: "x", rank: 12}
1: {class: "y", rank: 13}
2: {class: "z", rank: 10}
]

and I have gender object/property to be added to ABC in a loop

I need the result like

ABC =  [
0: {class: "x", rank: 12, gender: "male"}
1: {class: "y", rank: 13, gender: "female"}
2: {class: "z", rank: 10, gender: "female"}
]