mardi 31 octobre 2017

Ember generated service raising error on injection

I am brand new to EmberJS, and am going through a tutorial. I am at the part of the tutorial that starts talking about creating services and injecting them into your controllers (I'm not 100% sure if its a controller, but I'm coming from AngularJS, and it seems pretty similar).

In the terminal in my Ember project, I run the command ember g service authentication. I can see that the service was created in the services directory of my app in the file authentication.js. When I try injecting it into my controller however, I get this issue in the browser when I serve up the app locally,

Error: Assertion Failed: Attempting to inject an unknown injection: 'service:authentication

Could this be because I am using a version of Ember that is newer than in the tutorial, and there is a different way to inject services now? I ask that because this is the syntax of the service in the tutorial

import ember from 'ember'

export default Ember.Service.extend({
  records: []
});

and this is the syntax of what I have now, auto-created when the project was built with ember new

import Service from '@ember/service';

export default Service.extend({
  records: []
});

org.js "Where service is being injected"

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

export default Route.extend({

  authentication: Ember.inject.service(),

  setupController(controller) {
    this._super(...arguments);
  }
});




Ember error:Ember is not defined no-undef

Hi I am following through with Plural sight course "Getting started with Ember 2"; I am stuck with this error: 'Ember' is not defined no-undef;




Ember Unexpected Token (In JSON at position 0)

Error:

Error while processing route: about Unexpected token < in JSON at 
position 0 SyntaxError: Unexpected token < in JSON at position 0

I have a feeling I know what's causing this error, but I can't seem to figure out how to serialize the data. Here is my data when I hit my API in postman:

[
  {
    "site_id": 1,
    "site_name": "example.com",
    "view_id": 136791757,
    "project_manager_id": 2,
    "created_at": "2017-10-19 02:52:15",
    "updated_at": "2017-10-19 02:52:15"
 },
 {
   "site_id": 2,
   "site_name": "example2.com",
   "view_id": 136903606,
   "project_manager_id": null,
   "created_at": "2017-10-19 04:12:58",
   "updated_at": "2017-10-19 04:12:58"
 }
]

Is the error I'm getting related to the fact that this response is in array form?? Do I need to serialize? If so, how?!

I did some Googling and this seems to be a somewhat common error, but could not find any Ember specific answers, so this could be helpful for others.

Thanks!!




When I use ember.js and rails, nginx conf how to work?

My project design like this, /team url and /team/* will use ember.js. The other also use rails, and I set nginx conf:

upstream project {
  server unix:///tmp/project.sock;
}

server {
  listen 80;
  server_name www.project.io;
  root /home/deploy/www/project_backend/current/public;

  location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_redirect off;

    if (-f $request_filename/index.html) {
      rewrite (.*) $1/index.html break;
    }

    if (-f $request_filename.html) {
      rewrite (.*) $1.html break;
    }

    if (!-f $request_filename) {
      proxy_pass http://project;
      break;
    }
  }

  location /team {
    alias /home/deploy/www/project_frontend;
    try_files $uri $uri/ /index.html?/$request_uri;
  }
}

But this had some problems, when I use /team/ and will go to project_frontend index and /team/check/ or /team/project/check will go to rails page.

I don't know what's wrong with my .conf, Can you help me? Thanks.




how to learn ember js?

Why Ember JS?

Ember is an evolving JavaScript framework for creating “ambitious web applications”, it tries to maximize developers’ productivity using a set of conventions in a way that they don’t need to think about common idioms when building web applications. Using Ember in conjuntion with Ember CLI, allows you to reduce big amounts of glue code, giving you the opportunity to focus on what is most important for you: building your application. Glue code refers to those things that are not related to your application but that every project requires. For example, you need to test your code, compile your assets, serve your files in the browser, interact with a back-end API, perhaps use third party libraries, and so on. All those things can be automated and, as it is done in other frameworks, some conventions can provide a common ground to begin building your applications. Having a tool that does that for you not only eases the process of writing your app but also saves you time and money (you don’t have to think about problems that are already solved). Ember CLI aims to be exactly that tool. Thanks to Broccoli⁵, waiting time is reduced while your assets compile. QUnit⁶ allows you to write tests, which can then be run with Testem⁷. If you need to deploy your build to production, you’ll get fingerprint, compression, and some other features for free. Ember CLI also encourages the use of ES6(ECMAScript 6)⁸. It provides built-in support for modules and integrates easily with other plugins, allowing you to write your applications using other ES6 features. Next time you consider wasting your day wiring up all those things we just mentioned, consider Ember CLI. It will make your life easier and you will get support from a lot of smart people who are already using this tool

I really like ember js and now i have one project work with ember js but i want know more ember js. anyone here can help me?




lundi 30 octobre 2017

Not able to sort, getting error

I am trying to sort my model. But getting a error as

Cannot read property 'sort' of undefined

any one help me to sort this out? I guess that model is not existing in Computed methods.

here is my code :

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return [{"name":"fruit"},{"name":"flowers"}]
  },
  sortingByKey:['date'],
  sorter:Ember.Computed.sort("model","sortingByKey"), 
  init(){
    var sort = this.get("sorter");
  }
});

Twiddle Here




Session-Roles are not working properly in Ember-Rails application

I am using below gems for implementing session and role functionalities in my App.

  • ember-rails (0.18.3)
  • devise (3.5.1)
  • rolify (4.0.0)
  • authority (3.0.0)
  • rails (4.1.16)
  • ember-source (~> 1.6.1)
  • Ember - 1.8.0

Problem: I can handle the sessions and roles accurately in one tab. However, if I open the app in another window or tab, my session/role functionalities fail in the original tab. I can see all the buttons and fields as a user role which should be visible to the admin role only. This problem is resolved when I click the refresh button on the original tab, however the other tabs fail in this situation.

This is a code snippet in my upload.js.hbs.hamlbars.erb file

%li
  = hb 'if session.isOcuser' do
    = hb 'link-to "file_uploads"' do
      %i.fa.fa-lg.fa-upload
      File Upload

This is a code snippet in my simple_auth.js.coffee file

MyInventoryApp.CustomAuthenticator = Ember.SimpleAuth.Authenticators.Base.extend(
  authenticate: (credentials) ->
    _this = @
    return new Ember.RSVP.Promise((resolve, reject) ->
      data = {}
      return Ember.$.ajax({
        url:        '/api/v1/sessions',
        type:       'GET',
        data:       data,
        dataType:   'json',
        beforeSend: (xhr, settings) ->
          xhr.setRequestHeader('Accept', settings.accepts.json)
      }).then( (response) ->
        roles = (r.name for r in response.user.roles)
        Ember.run( ->
          resolve (
            uid: response.user.uid
            roles: roles
            isadmin: roles.contains('admin')
            isuser: roles.contains('user')
          )
        )
      , (xhr, status, error) ->
        Ember.run( ->
          reject(xhr.responseJSON || xhr.responseText)
        )
      )
    )
  restore: (data) ->
    return new Ember.RSVP.Promise( (resolve, reject) ->
          if !Ember.isEmpty(data.uid)
            resolve(data)
          else
            reject()
    )

)




Mirage `passthrough` is not working

I'm trying to use passthrough for a POST request in this Ember project

this.passthrough('/thirdeye/entity?entityType=ANOMALY_FUNCTION');

This is what the call looks like in app/mirage/config.js. I got the following error:

Mirage: Your Ember app tried to POST '/thirdeye/entity?entityType=ANOMALY_FUNCTION',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?

Clearly, I've added that call to the config file, but it's not being picked up. I read that passthrough only works for >= jquery 2.x, which my project is.

Does anyone know what else could cause this?




ember serve on a new cloned project

I am brand new to ember and am having a hard time getting ember to kick off. I have ember installed on my local machine. I cloned a client project from git into my local projects folder. I cd to the project folder and then ember serve and it says there is no ember cli to serve. If I try to install bower it says no such file or directory, open C:\Users\mjr23\package.json'.

I am at a loss on this stuff. I cant find any direct answers to jumping into a live project and getting to work. Any guidance on this would be very appreciated.

I feel like I am missing something very obvious, this really cant or shouldnt be that difficult...




Ember-Build - How config for local host running?

I require to run my ember application after I do the ember build -prod for testing purpose. I am using xaamp local server. But I am not able to run my app.

I am getting the following errors:

localhost/:13 GET http://localhost:8080/assets/vendor-67b1c7f5f2eb1b051649864903c92044.css 
localhost/:14 GET http://localhost:8080/assets/rdc-ui-servicerequest-csd-9635212553537ffc063efb35021419f0.css 
Navigated to http://localhost:8080/Ember/
localhost/:22 GET http://localhost:8080/assets/rdc-ui-servicerequest-csd-718fc0f8bad1138cf9007d42e5ab2fff.js 
localhost/:21 GET http://localhost:8080/assets/vendor-0e6b914827a8308d459cf96ddc1a551e.js 
localhost/:14 GET http://localhost:8080/assets/rdc-ui-servicerequest-csd-9635212553537ffc063efb35021419f0.css 
localhost/:13 GET http://localhost:8080/assets/vendor-67b1c7f5f2eb1b051649864903c92044.css 
localhost/:22 GET http://localhost:8080/assets/rdc-ui-servicerequest-csd-718fc0f8bad1138cf9007d42e5ab2fff.js 

How to fix this? any how can i run my build in localhost of my system. any one please help me to configure?

Thanks in advance




samedi 28 octobre 2017

ember - load model from ajax is undefinded

Well, its that, i need to load my model after ajax request complete.

when ajax complete I pushdata into store and after that i need to return these data and render on template but is empty.

model(params)
    {
        const _this = this;

        const controller = this.controllerFor('users.profile');

        return controller.get('session').authorize('authorizer:devise', (headerName, headerValue) => {

                    var url = '/api/users/profile/'+this.get('session.data.authenticated.user.id');

                    return Ember.$.ajax({
                            method: 'GET',
                            url: controller.get('backendURL')+url,
                            dataType: 'json',
                            //data: ,
                            contentType: 'application/json',
                            beforeSend:  function(xhr) {
                                xhr.setRequestHeader(headerName, headerValue);
                            },
                            success: function(

                                _this.store.pushPayload('user',data);

                                //in this point i view ther user info in emebr inspector addon.


                                return Ember.RSVP.resolve(data);//return usr;

                            },
                            error: function(data){
                                controller.get('flashMessages').danger('ERROR, '+ data);
                                Ember.$("#loading").hide("slow");
                                controller.set('seeTable',false);
                            }
                    });
        });

Any suggestions, whats is wrong on my route?




Ember Template Not showing in page

I'm trying to create a simple blog with Ember. I'm following this tutorial http://ift.tt/2gReaWR

I've created a model and generated a template.bhs and component.js for 'create-new-post'. I've created a route for 'posts' and also 'posts/new'. However, when loading 'app.com/posts/new' in the browser, I don't see the content from new.hbsI just see my header and footer as per application.hbs.

No doubt I'm missing something very basic here.

templates/posts/new.hbs



components/create-new-post/template.hbs

<h3>Create a new post</h3> <form>   <p>

   </p>   <p>
   </p>   <p>
<span >Publish</span>   </p> </form>

routes/new.js

import Ember from 'ember';

export default Ember.Route.extend({
});

models/post.js

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  snippet: DS.attr('string'),
  createdDate: DS.attr('date'),
  text: DS.attr('string')
});

router.js

import Ember from 'ember';
import config from './config/environment';

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

Router.map(function() {
  this.route('posts', function() {
    this.route('new');
  });
});

export default Router;




vendredi 27 octobre 2017

Ember.js - Learning dynamic segments, link-to, nested routes

I'm trying to learn how to do dynamic segments in Ember. I thought I understood but obviously it's not working. Are my corresponding file structure and model queries correct?

router.js

Router.map(function() {
  this.route('photos', function() {
    this.route('photo', { path: '/:photo_id' }, function() {
      this.route('comments');
      this.route('comment', { path: '/comments/:comment_id' });
    });
  });
});

Creating dynamic link list somewhere in the app using the photos model:


  


Does everything line up with my file stucture?

File structure:

app
├── controllers
|   └── photo
|   |   └── comment
|   |   |   └── index.js
|   |   ├── index.js
|   |   └── comments.js
|   └── photos.js
├── routes
|   └── photo
|   |   └── comment
|   |   |   └── index.js
|   |   ├── index.js
|   |   └── comments.js
|   └── photos.js
└── templates
|   └── photo
|   |   └── comment
|   |   |   └── index.hbs
|   |   ├── index.hbs
|   |   └── comments.hbs
|   └── photos.hbs
└── router.js

routes/photos.js

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

Lets say I want to display all the photos with comments, I can get the model below.

routes/photo/index.js

model(params) {
  return this.store.findRecord('photo', params.photo_id, {include: 'comments'});
}

Unsure about the next 2 models.

routes/photo/comments.js

model(params) {
  return this.store.query('comment', { photo: photo_id })
}

routes/photo/comment/index.js

model(params) {
  return this.store.findRecord('comment', params.comment_id);
}




Error when running ember server: bower packages missing

Hi I am brand new to Ember . following a course in Plural-sight I was able to run cli and create new project after a lot of fighting. Then I tried ember server and I get error :missing bower packages : ember ,ember-shim There as also warning node v8.7.0 has not been tested against ...etc and unexpected results can happen...and a message like migrate-away-from-bower So how can troubleshoot this problem




jeudi 26 octobre 2017

Difference between and

I have a simple component that I would like to test with integration test (ember-cli-qunit 4.0.0).

    this.render(hbs``);
    input1 = this.$('input')[0];
    await fillIn(input1, 'first');
    await fillIn(input1, '');

Let's assume that dynamicUpdate just do a console.log('foo') as it is not important for this question. The issue is that dynamicUpdate() is called just at the first change. After the change of render line to:

<input value= oninput= />

The function is executed twice as I have expected.

I'm aware of basic differences between and but I believe that it should not have impact in this case. Do you have ideas what could be a difference?




How does a query from the route handler and ember data communicate?

How can a model() request find all data from 'rental' or ../models/rental.js?

model() {
    return this.get('store').findAll('rental'); // 'rental' refers to ../models/rental.js?
}

A model() call will fetch data from /api/rentals defined in the adapter. But how does /models/rental.js talk to the data store and work alongside api calls?

In the quick start tutorial, it says

The store service is injected into all routes and components in Ember.
It is the main interface you use to interact with Ember Data.

I'm just trying to wrap my head around how the route handler and ember data communicate from a to z.




.htaccess rewrite subdirectory refresh

I have an emberjs project that I posted and everything is working thus far except for when I go to refresh a subdirectory of the domain.

something.com                    <- working  
http://ift.tt/2iCiZne            <- working  
http://ift.tt/2z9tvJO  <- not working 

The above pages load fine via links in the navbar but when refreshing or going directly to them, they do not load.

Here is the contents of my .htaccess which is in the root of the www/

#########################################
# REWRITE RULES                         #
#########################################
<IfModule mod_rewrite.c>
       RewriteEngine On
       RewriteBase /
       RewriteCond %{REQUEST_FILENAME} !-d
       RewriteCond %{REQUEST_FILENAME} !-f      
       RewriteCond %{SERVER_PORT} !^443$

       RewriteRule ^(.*)$ index.html\?p=$1 [QSA,L] 
</IfModule>

What else do I need to add so that subdomain refreshing works?
I do not know or think I even can add additional .htaccess files as the folder structure is autocompiled thanks to the ember build.




Set focus on component after modal close

I would like to know what is recommended way to focus on component from outside the component. I am trying to focus on a input field when the person closes the modal window.




What are the different patterns used developing a client side web application today?

Mine is not a technical question but I would like to read different opinions in one of the hottest topic of the web development nowadays.

I'm a frontend software engineer and I work with Ember.js (I didn't take this decision, it was already there when I started). In the old versions, it had an MVC approach and, up as it was being updated, the team behind it, left this pattern to embrace "Data down &actions up" (kind of Flux).

Actually, my question is: today, what are the most common patterns of the web development and, for each pattern, what are the frameworks that adopt it? I'm interested in a discussion that compares different patterns with their frameworks, and what should be the best situation to use each of them.

I hope the question is interesting for you as well (sorry if I did a O(n^2) complexity question due to the fact that we have to compare N patterns and N framework...😅 I'm joking 😛) looking forward to read what you think.

Thanks.




Ember: the brocolli plugin failed

enter image description here

I'm trying run an Ember project locally : http://ift.tt/2gEgEri. I'm using pycharm 2017 using git-bash as my terminal in win7. I have npm , node and ember installed . In pycharm my project looks like the screenshot. I'm running everything on a USB key (E:) portably.

After switching to the cosmic-real-estate folder:

  $ ember build

  Running without permission to symlink will degrade build performance.
  See http://ift.tt/1r0dnSM for details.

  cleaning up...
  Build failed.
  The Broccoli Plugin: [Funnel: Funnel: index.html] failed with:
  Error: EISDIR: illegal operation on a directory, symlink 'e:\ember-real-estate-website\cosmic-real-estate\app' -> 'e:\ember-real-estate-website\cosmic-real-estate\tmp\funnel-input_base_path-ZStiRJkX.tmp'
      at Error (native)
      at Object.fs.symlinkSync (fs.js:1069:18)
      at symlinkWindows (e:\ember-real-estate-website\cosmic-real-estate\node_modules\symlink-or-copy\index.js:123:18)
      at symlinkOrCopySync (e:\ember-real-estate-website\cosmic-real-estate\node_modules\symlink-or-copy\index.js:63:5)
      at e:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-plugin\read_compat.js:86:11
      at tryCatch (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:539:12)
      at invokeCallback (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:554:13)
      at publish (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:522:7)
      at flush (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:2414:5)
      at _combinedTickCallback (internal/process/next_tick.js:73:7)

  The broccoli plugin was instantiated at:
      at Funnel.Plugin (e:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-plugin\index.js:7:31)
      at new Funnel (e:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-funnel\index.js:58:10)
      at EmberApp._rawAppIndex (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:694:12)
      at EmberApp.index (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:678:20)
      at EmberApp.toArray (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:1661:12)
      at EmberApp.toTree (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:1684:38)
      at module.exports (e:\ember-real-estate-website\cosmic-real-estate\ember-cli-build.js:26:14)
      at Builder.setupBroccoliBuilder (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\models\builder.js:56:19)
      at new Builder (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\models\builder.js:30:10)
      at BuildTask.run (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\tasks\build.js:15:19)

I have tried running this in powershell with admin rights but got :

  PS E:\ember-real-estate-website\cosmic-real-estate> ember build
  cleaning up...
  Build failed.
  The Broccoli Plugin: [Funnel: Funnel: index.html] failed with:
  Error: EISDIR: illegal operation on a directory, symlink 'E:\ember-real-estate-website\cosmic-real-estate\app' -> 'E:\ember-real-estate-website\cosmic-real-estate\tmp\funnel-input_base_path-x8c6C
  Icw.tmp'
      at Error (native)
      at Object.fs.symlinkSync (fs.js:1069:18)
      at symlinkWindows (E:\ember-real-estate-website\cosmic-real-estate\node_modules\symlink-or-copy\index.js:120:16)
      at symlinkOrCopySync (E:\ember-real-estate-website\cosmic-real-estate\node_modules\symlink-or-copy\index.js:63:5)
      at E:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-plugin\read_compat.js:86:11
      at tryCatch (E:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:539:12)
      at invokeCallback (E:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:554:13)
      at publish (E:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:522:7)
      at flush (E:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:2414:5)
      at _combinedTickCallback (internal/process/next_tick.js:73:7)

  The broccoli plugin was instantiated at:
      at Funnel.Plugin (E:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-plugin\index.js:7:31)
      at new Funnel (E:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-funnel\index.js:58:10)
      at EmberApp._rawAppIndex (E:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:694:12)
      at EmberApp.index (E:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:678:20)
      at EmberApp.toArray (E:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:1661:12)
      at EmberApp.toTree (E:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:1684:38)
      at module.exports (E:\ember-real-estate-website\cosmic-real-estate\ember-cli-build.js:26:14)
      at Builder.setupBroccoliBuilder (E:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\models\builder.js:56:19)
      at new Builder (E:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\models\builder.js:30:10)
      at BuildTask.run (E:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\tasks\build.js:15:19)




What module loader ember.js is using?

I am wondering what module loader ember.js is using?

I check the docs in ember-cli, it mentioned the compiled module is AMD(RequireJS). But what is the module loader library? Like angular is using webpack.




Error by ember test in ember engine

When i try a ember test in a ember engine, i became the following error:

Build failed. The Broccoli Plugin: [BroccoliMergeTrees: TreeMerger (otherAssetTrees)] failed with: Error: ENOENT: no such file or directory, scandir '/Users/danielmertgen/workspace/corona/patients/patients-frontend/tmp/funnel-input_base_path-http://ift.tt/2yRJtak' at Object.fs.readdirSync (fs.js:914:18) at _walkSync (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/walk-sync/index.js:64:18) at Function.entries (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/walk-sync/index.js:40:10) at Funnel.processFilters (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/broccoli-funnel/index.js:298:26) at Funnel.build (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/broccoli-funnel/index.js:236:10) at /Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/broccoli-plugin/read_compat.js:93:34 at tryCatch (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/rsvp/dist/rsvp.js:538:12) at invokeCallback (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/rsvp/dist/rsvp.js:553:13) at publish (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/rsvp/dist/rsvp.js:521:7) at flush (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/rsvp/dist/rsvp.js:2373:5)

The broccoli plugin was instantiated at: at BroccoliMergeTrees.Plugin (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/broccoli-plugin/index.js:7:31) at new BroccoliMergeTrees (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/node_modules/broccoli-merge-trees/index.js:16:10) at Function.BroccoliMergeTrees [as _upstreamMergeTrees] (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/node_modules/broccoli-merge-trees/index.js:10:53) at mergeTrees (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/lib/broccoli/merge-trees.js:85:33) at EmberAddon._mergeTrees (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1832:12) at EmberAddon.otherAssets (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1507:17) at EmberAddon.toArray (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1691:12) at EmberAddon.toTree (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1711:38) at module.exports (/Users/danielmertgen/workspace/corona/patients/patients-frontend/ember-cli-build.js:17:14) at Builder.setupBroccoliBuilder (/Users/danielmertgen/workspace/corona/patients/patients-frontend/node_modules/ember-cli/lib/models/builder.js:56:19)

Anybody a idea why?

My package.json dependencies:

"dependencies": {
    "ember-cli-babel": "^6.8.2",
    "ember-cli-htmlbars": "^2.0.3",
    "ember-cli-sass": "^7.0.0",
    "ember-data": "2.16.0",
    "ember-file-upload": "^2.1.2",
    "ember-truth-helpers": "^1.3.0",
    "node-sass": "^4.5.3"
  },
  "peerDependencies": {
    "ember-engines": "0.5.0-beta.6"
  },
  "devDependencies": {
    "broccoli-asset-rev": "^2.6.0",
    "ember-ajax": "^3.0.0",
    "ember-cli": "^2.15.1",
    "ember-cli-app-version": "^3.1.0",
    "ember-cli-dependency-checker": "^2.0.1",
    "ember-cli-head": "^0.4.0",
    "ember-cli-htmlbars-inline-precompile": "^1.0.2",
    "ember-cli-qunit": "^4.0.1",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^2.2.0",
    "ember-cli-uglify": "^2.0.0",
    "ember-cookies": "^0.0.13",
    "ember-engines": "^0.5.14",
    "ember-export-application-global": "^2.0.0",
    "ember-i18n": "^5.0.2",
    "ember-ionicons": "^0.1.1",
    "ember-load-initializers": "^1.0.0",
    "ember-resolver": "^4.5.0",
    "ember-source": "^2.15.1",
    "loader.js": "^4.6.0"
  }




mercredi 25 octobre 2017

How to put routes in a sub folder without changing the URL in Ember

I have links that currently are in my main path. I would like to group them in a sub folder without changing the urls. For example I have /income-statement and I want to put the files in a reports directory. With the nested routes the url becomes /reports/income-statement. I tried setting the path on the reports level to be {path: ''} but it conflicts with my main route

this.route('reports', function() {
  this.route('accounts-receivable')
  this.route('income-statement')
})




Ember build failed

enter image description here

I'm trying run an Ember project locally : http://ift.tt/2gEgEri. I'm using pycharm 2017 using git-bash as my terminal in win7. I have npm , node and ember installed . In pycharm my project looks like the screenshot.

After switching to the cosmic-real-estate folder:

  $ ember build

  Running without permission to symlink will degrade build performance.
  See http://ift.tt/1r0dnSM for details.

  cleaning up...
  Build failed.
  The Broccoli Plugin: [Funnel: Funnel: index.html] failed with:
  Error: EISDIR: illegal operation on a directory, symlink 'e:\ember-real-estate-website\cosmic-real-estate\app' -> 'e:\ember-real-estate-website\cosmic-real-estate\tmp\funnel-input_base_path-ZStiRJkX.tmp'
      at Error (native)
      at Object.fs.symlinkSync (fs.js:1069:18)
      at symlinkWindows (e:\ember-real-estate-website\cosmic-real-estate\node_modules\symlink-or-copy\index.js:123:18)
      at symlinkOrCopySync (e:\ember-real-estate-website\cosmic-real-estate\node_modules\symlink-or-copy\index.js:63:5)
      at e:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-plugin\read_compat.js:86:11
      at tryCatch (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:539:12)
      at invokeCallback (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:554:13)
      at publish (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:522:7)
      at flush (e:\ember-real-estate-website\cosmic-real-estate\node_modules\rsvp\dist\rsvp.js:2414:5)
      at _combinedTickCallback (internal/process/next_tick.js:73:7)

  The broccoli plugin was instantiated at:
      at Funnel.Plugin (e:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-plugin\index.js:7:31)
      at new Funnel (e:\ember-real-estate-website\cosmic-real-estate\node_modules\broccoli-funnel\index.js:58:10)
      at EmberApp._rawAppIndex (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:694:12)
      at EmberApp.index (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:678:20)
      at EmberApp.toArray (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:1661:12)
      at EmberApp.toTree (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\broccoli\ember-app.js:1684:38)
      at module.exports (e:\ember-real-estate-website\cosmic-real-estate\ember-cli-build.js:26:14)
      at Builder.setupBroccoliBuilder (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\models\builder.js:56:19)
      at new Builder (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\models\builder.js:30:10)
      at BuildTask.run (e:\ember-real-estate-website\cosmic-real-estate\node_modules\ember-cli\lib\tasks\build.js:15:19)

There is a new node_modules folder visible as well:

enter image description here

How can I get this working?




How to use fixture with reflexive relation in ember-cli-mirage?

I have an article model that is reflexive to itself through a related_articles fields. In order to have a finer control of the context in my tests, I want to use fixture.

model

// app/models/article.js
export default Model.extend({
  featured: attr('boolean'),
  related_articles: hasMany('article', { inverse: null })
});

fixture

// mirage/fixtures/articles.js
  export default [{
    id: 2,
    featured: true,
    related_articles: [1, 2]
  }];

scenario

// mirage/scenarios/default.js
export default function(server) {
  server.createList('category', 10);
  server.loadFixtures('articles');
}

Test

test('has related-articles block', function(assert) {
  authenticate(this.application);
  server.loadFixtures('articles');

  visit('/app/articles/2');
  andThen(function() {
    let relatedArticlesBlock = document.querySelectorAll('.related-articles');
    assert.ok(relatedArticlesBlock.length);
  });
});

Error

Mirage: Your GET handler for the url /api/v2/employee/articles/2 threw an error: model.hasInverseFor is not a function

Question

There is no related articles in the related_articles key returned by mirage. What's the matter?




Why does an import make that my template is not rendered

I have been facing an issue yesterday and can't resolve it since. I am trying to do a web app using ember.js and ember data in Webstorm on Windows 10. The web app is going to be used by users so I want to 'hash' a part of the data before sending it to my database (Firebase).

To do this, I searched a bit and found bcrypt. I installed it using the "npm install bcrypt --save-dev" command. No issues on install so I tried to use it.

BUT when importing bcrypt in my controller add-device.js (I tried "bcrypt = require('bcrypt');" and "import bcrypt from 'bcrypt';") the data inside the template corresponding to the controller is not being displayed anymore and I don't understand why.

I have submitted the 'project' on github: http://ift.tt/2zODl0V so it can be easier to see everything.

I feel like the bcrypt module is installed at the right place and that the dependencies are ok (node-gyp, nodeJS..) but.. maybe not, I don't really know as I come from C and started coding webapp 2 weeks ago.

Here are the versions of npm, nodeJs, node-gyp and bcrypt (maybe useful):

npm: v5.5.1

nodeJs: v6.11.3

node-gyp: v3.6.2

bcrypt: v1.0.3

I already tried to uninstall and re-install bcrypt but wihtout succes..

Please let me know if you have any suggestions or additional questions! :)




No ember-cli-build.js found

enter image description here

I'm trying run an Ember project locally : http://ift.tt/2gEgEri. I'm using pycharm 2017 using git-bash as my terminal in win7. I have npm , node and ember installed . In pycharm my project looks like the screenshot.

I've been advised to build the project (Emberjs: Failed to find a valid digest in the 'integrity' attribute , although this is not discussed in the instructions):

$ ember build

Running without permission to symlink will degrade build performance.
See http://ift.tt/1r0dnSM for details.

- BuildingNo ember-cli-build.js found.

You can see the file in the screenshot. What am I doing wrong?




ember how to open external link from a button click

In Ember 2.12, Is it possible to call an action on a button click which navigates the user to an external link (like bbc.com for example). I thought the transitionTo will only know the routes declared in router.js




can i call javascript code to close window from Ember button or link

Sorry javascript/ember noob question, I have an Ember page with a link and a button. Is it possible when i click on either of them to call javascript code to close the browser tab in which the ember page is opened.




Set value to input dynamically in ember

i am trying to set variable name to input value so the datatest selector value is same when value is entered in input box. if i currently use value=item.name

it displays the name in input box. i juzt want value to be set as variable name when value in input entered it is also assigned to data-test-selector. like old code as shown below.

Trying to use dynamically using each


        <input id= maxlength="15" class="form-control" data-test-License=  value=item.name/>


old code






trees:{ mergetrees(['src',external js file])} in ember-cli-build.js is not working

In glimmer application, I want to bundle the app.js file with external js file. In ember-cli-build.js file, I added the

trees:{
 mergetrees(['src',externalJs})
}

But it not working.




mardi 24 octobre 2017

Set directory for NPM

I'm working with git-bash on win 7. I want to develop an ember project and I am working on a thumb drive. I have set installed node on my E drive and added the path to the env vars.

 $ npm install -g ember-cli
  C:\Users\me\AppData\Roaming\npm\ember -> C:\Users\me\AppData\Roaming\npm\node_modules\ember-cli\bin\ember
  C:\Users\me\AppData\Roaming\npm\� -> C:\Users\me\AppData\Roaming\npm\node_modules\ember-cli\bin\ember
  + ember-cli@2.16.2
  updated 553 packages in 89.25s

  $ which npm
  /e/nodejs/npm

  $ which node
  /e/nodejs/node

  $ ember build
  sh.exe": ember: command not found

So I think whats happening is that npm is installing the packages on the c drive. I need to set a folder on my e drive, to make this portable. How can I do this?




Handling errors in ember

How I can read error message and HTTP error status in catch callbcak?

Error handling in Ember Data: 2.16.2 a little bit confusing.

Problem appear when query return HTTP 401 Unauthorized with data {error: "Not authorized"}. err does't contain error and http code (in my case err == true)

this.store.query('user', {
            someParam: val
          }).then((model) => {
            ....
          }).catch((err) => {
             console.log(err)
          });




Emberjs: Failed to find a valid digest in the 'integrity' attribute

enter image description here

I'm trying run an Ember project locally : http://ift.tt/2gEgEri. I'm using pycharm 2017 using git-bash as my terminal in win7. I have npm and node installed along with the jetbrains emberjs plugin.

I can start the server using :

  $ COSMIC_BUCKET=your-bucket-slug npm start

  > cosmicrealestate@1.0.0 start C:\ember-real-estate-website
  > node server.js

When I open the browser I see nothing. In the console:

Failed to find a valid digest in the 'integrity' attribute for resource 'http://localhost:3000/assets/vendor-969213113bf8ce8653053cf775905b0d.css' with computed SHA-256 integrity 'X3XPwk5BB1JgnemiDQkQoHJwfotEk8I6G1p+XYvKfiw='. The resource has been blocked.

How can I fix this?




How to clear a route URL when transitioning away from a route with query params?

The files route has three possible views:

  1. Shows all the files.
  2. Shows an overlay that shows matching files that were detected.
  3. Show an individual file using a query parameter.

Current issue is that when the third scenario occurs - accessing a specific file using query params like url/files?fileId=6 - and you got to another route and come back to files, the files route is now url/files?fileId=6 instead of /files.

Hunch is that this should be address using deactivate() or resetController() but haven't had much luck. Any help is appreciated!

redirect(){
    const deal = this.get('session.deal');
    if (!this.get('session.isViewer') &&
      this.get('session.matchedFiles.length') > 0){

      if(!this.get('router.url').includes('?fileId=')) {
        if(deal.get('creationStatus') === 'ready') {
          this.transitionTo('files.matches');
        }
      }

    } else {
      if (!this.get('session.isViewer') &&
        this.get('session.matchedFiles.length') === 0) {
        if(deal.get('creationStatus') === 'ready') {
          this.transitionTo('files');
        }
      }
    }
  },




Observer not working on page back / front button use

In my component I have a observer which is setting the max amount as a value. when I load the page it sets and all are fine.

In case if I use back of the browser and come again to page, I am getting default select value instead of the sorted one.

how can i force my observer to re-calculate on back transitions? ( back / front button )

here is my code :

onValueChange:Ember.observer('selectedCreditCard.requestAmount', function(){

        var value = Number(this.get('selectedCreditCard.requestAmount'));
        var that = this;


this.get("selectedCreditCard.tenureDetails").forEach(function(item,index){

            if(value >= Number(item.min) && value <= Number(item.max)){

                console.log("item.tenures", JSON.parse(JSON.stringify(item)) );

                that.set('selectedCreditCard.matchingTenure', item.tenures );
                that.set('selectedCreditCard.handlingFee', item.handlingFee );
                that.set('selectedCreditCard.minAmount', 1500 );
//first time works. on page shuffle not works!!
                that.set('selectedCreditCard.selectedTenure', 
                    that.get('selectedCreditCard.matchingTenure').get('lastObject') );//setting value
//works based on above settings. so fails!!
                that.monthlyInstalment();
            }
        })

    }),




lundi 23 octobre 2017

Ember Powerselect data format

I am looking the documentation of the format of the how it needs to be. But I am wondering how I could add the id of the options.

groupedNumbers: [
    { groupName: 'Smalls', options: ['one', 'two', 'three'] },
    { groupName: 'Mediums', options: ['four', 'five', 'six'] },
    { groupName: 'Bigs', options: [
        { groupName: 'Fairly big', options: ['seven', 'eight', 'nine'] },
        { groupName: 'Really big', options: [ 'ten', 'eleven', 'twelve' ] },
        'thirteen'
      ]
    },
    'one hundred',
    'one thousand'
  ]

Here is what I am looking to do

groupedNumbers: [
    { groupName: 'Smalls', options: [{
        id: 1,
        name: 'one'
    },
    {
        id: 2,
        name: 'two'
    }]
  ]

I thought I could override the optionsComponent but that did not work. Thoughts?




npm WARN No repository field

enter image description here

I'm trying to start work on a project I found: http://ift.tt/2gEgEri. I want to set it up to run locally following the directions in the screenshot, but I don't know much about node/npm. I'm trying to set this up to run emberjs in pycharm 2017 using git-bash as my terminal in win7. I have npm and node installed along with the jetbrains emberjs plugin. When I run :

npm i

I see:

....
-- mime@1.4.1
    +-- serve-static@1.13.1
    +-- setprototypeof@1.1.0
    +-- statuses@1.3.1
    +-- type-is@1.6.15
    | `-- media-typer@0.3.0
    +-- utils-merge@1.0.1
    `-- vary@1.1.2

  npm WARN cosmicrealestate@1.0.0 No repository field.

I don't know what to regarding the next line:

 COSMIC_BUCKET=your-bucket-slug npm start

What does this mean? does it have anything to do with "npm WARN No repository field" ?




ember-simple-auth for React/Redux world

Is there something like ember-simple-auth for React/Redux?

Especially for JWT authentication?

I tried a lot of way to authenticate in my application, but always not a "standard", community driven (and tested) way as with ember-simple-auth.

What do you suggest?




How reload the data in the page using EmberJS

I have a search results page, which is developed using EmberJS. I use Ember.Route to load data through from API. The search API which i was using is very slow. So we decided to load the data from a cache API. But the problem is that, the cache might have some old data. So we decided to re-load data in the already loaded page using search API.

My existing Route code would look like this

define(‘search’,  ['jquery'], function($) {
  var route = Ember.Route.extend({
    model: function() {
        return searchApiCall( someParameter );
    },
    setupController: function(controller, model) {
        controller.set('model', model);
    }
  });
  return route;
});

In the above code, am just calling the search API and returning the json response. But, what i want is something as below.

define(‘search’,  ['jquery'], function($) {
    var route = Ember.Route.extend({
    model: function() {
      setTimeout(function(){
        return searchApiCall( someParameter );
      }, 10);
      return cachedSearchResult( someParameter );
    },
    setupController: function(controller, model) {
      controller.set('model', model);
    }
  });
  return route;
});

So what am looking in the above code is to pass the cached result at first and then somehow load the result from actual search api when its available.

Please let me know, whats the best way for this in EmberJS.




Highcharts misbehaving while trying to render dashed line/colored markers for points

I have created an Ember JS component which uses Highcharts 6 library to create different types of charts based on data and configuration provided to the component. However, when I am trying to use "dashStyle" or "marker: { fillColor: "#FFFF00"}" for any series(to get dashed line) or data point(to get colored marker based on point data) respectively, am not getting the desired results. However, on pasting the same config on jsfiddle, am able to get the desired chart output. Any help would be sincerely appreciated. Pasting the component code below:

    import Ember from 'ember';

    export default Ember.Component.extend({
      chartId: undefined,
      chartData: undefined,
      selectedChartType: undefined,
      chart: undefined,
      allowedChartTypes: undefined,
      customSlider: false,
      slider: false,
      showChartTypeSelector: false,
      chartTypes: [
    {label: 'Bar chart', value: 'bar', stacked: false, id: 'bar1', group: 1},       
    {label: 'Stacked Bar chart', value: 'bar', stacked: true, id: 'bar2', group: 1},
    {label: 'Bar Range chart', value: 'columnrange', stacked: false, inverted: true, id: 'bar3', group: 2},
    {label: '3D Bar chart', value: 'bar', stacked: false, threeD: true, id: 'bar4', group: 1},

    {label: 'Column chart', value: 'column', stacked: false, id: 'column1', group: 1},
    {label: 'Stacked Column chart', value: 'column', stacked: true, id: 'column2', group: 1},
    {label: 'Column Range chart', value: 'columnrange', stacked: false, id: 'column3', group: 2},       
    {label: '3D Column chart', value: 'column', stacked: false, threeD: true, id: 'column4', group: 1},

    {label: 'Area chart', value: 'area', stacked: false, id: 'area1', group: 1},
    {label: 'Stacked Area chart', value: 'area', stacked: true, id: 'area2', group: 1},
    {label: 'Area Range chart', value: 'arearange', stacked: false, id: 'area3', group: 2},

    {label: 'Line chart', value: 'line', stacked: false, id: 'line', group: 1},
    {label: 'Spline chart', value: 'spline', stacked: false, id: 'spline', group: 1},

    {label: 'Pie chart', value: 'pie', stacked: false, id: 'pie1', group: 3},       
    {label: '3D Pie chart', value: 'pie', stacked: false, threeD: true, id: 'pie2', group: 3},

    {label: 'Donut chart', value: 'pie', stacked: false, donut: true, id: 'donut1', group: 3},
    {label: '3D Donut chart', value: 'pie', stacked: false, threeD: true, donut: true, id: 'donut2', group: 3},

    {label: 'Scatter plot', value: 'scatter', stacked: false, id: 'scatter', group: 4},
    {label: 'Bubble chart', value: 'bubble', stacked: false, id: 'bubble', group: 4},

    {label: 'Progress chart', value: 'solidgauge', stacked: false, id: 'progress', group: 5}
],
chartDataObserver: Ember.observer('chartData', function(){
    this.setChartType();
    if(this.selectedChartType !== undefined){
        this.drawChart();
    }
}),
init() {
    this._super(...arguments);
    if(this.chartId === undefined){
        this.set('chartId', `chart_${this.generateUUID()}`);
    }
    this.setChartType();
    if(this.chartData.customTheme !== false){
        this.setChartsTheme();
    }
    else {
        this.removeTheme();
    }
},
didInsertElement() {
    this._super(...arguments);
    if(this.selectedChartType !== undefined){
        this.drawChart();
    }
},
generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxxxxxxyy45'.replace(/[xy]/g, function(c) {
        return Math.floor((d+Math.random()*16)%16).toString(16);
    });
    return uuid;
},
removeTheme() {
    let stylesheet = document.getElementById('custom-chart-styles');
    if (stylesheet) {
        stylesheet.remove();
    }
},
setChartsTheme(){
    let colors = ['#234EA1', '#FCBC06', '#EC2027', '#70BE44', '#C1D331', '#C979CB', '#32CD9F', '#0099FF', '#87A1FF', '#9C7ACB'];
    if(this.chartData.colors !== undefined && this.chartData.colors.length > 0){
        colors = Ember.copy(this.chartData.colors);
    }
    this.addCustomColorStyles(colors);
    Highcharts.setOptions({
        colors: colors
    });
},
addCustomColorStyles(colors) {
    let stylesheet = document.getElementById('custom-chart-styles');
    if (!stylesheet) {
        stylesheet = Ember.$('<style id="custom-chart-styles">').appendTo('head')[0];
    }
    let html = '';
    colors.forEach((c,i)=>{
        html += `\n.highcharts-color-${i} { fill: ${c} !important; stroke: ${c} !important; } `;
    });
    stylesheet.innerHTML = html;
},
setChartType(){
    if(this.chartData.type !== undefined){
        this.chartTypes.every(t=>{
            if(t.id === this.chartData.type){
                this.set('selectedChartType', t);
                return false;
            }
            return true;
        });
        if(this.selectedChartType !== undefined){
            this.set('allowedChartTypes', this.chartTypes.filter(type=>{
                return this.selectedChartType.group === type.group;
            }));
        }
        if([1,2,4].indexOf(this.selectedChartType.group) > -1){
            if(this.chartData.customSlider === null){
                this.set('slider', false);
                this.set('customSlider', false);
            }
            else {
                if(this.chartData.customSlider !== undefined){
                    this.set('customSlider', this.chartData.customSlider);
                }
                this.set('slider', !this.customSlider);
            }
        }
        if(this.chartData.showChartTypeSelector !== undefined){
            this.set('showChartTypeSelector', this.chartData.showChartTypeSelector);
        }
    }
},
getAxisObject(axis) {
    let self = this, axisObject = {
        type: axis.type,
        categories: axis.categories,
        description: axis.description,
        max: axis.max,
        min: axis.min,
        title: {
            text: axis.title
        },
        stackLabels: {
            enabled: false,
            style: {
                fontWeight: 'bold',
                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
            }
        },
        opposite: axis.opposite
    };
    if(axis.type === 'datetime'){
        axisObject.events = {
            afterSetExtremes: function(){
                self.sendAction('onRangeChanged', this);
            }
        };
    }
    return axisObject;
},
processSeriesInformation(){
    let series = [];
    this.chartData.series.forEach((s,i)=>{
        if(typeof s === 'string'){
            series.push({
                name: s,
                data: this.chartData.data[i],
                yAxis: 0
            });
        }
        else {
            series.push({
                name: s.name,
                data: this.chartData.data[i],
                yAxis: s.yAxis !== undefined ? s.yAxis : 0,
                colorIndex: s.colorIndex,
                dashStyle: s.dashStyle
            }); 
        }
    });
    if(this.chartData.customSeries !== undefined){
        if(this.chartData.customSeries.constructor === Array){
            series.push(...this.chartData.customSeries);
        }
        else {
            series.push(this.chartData.customSeries);
        }
    }
    if(this.selectedChartType.group !== 3){
        series.forEach(s=>{
            if(s.data.length > 0){
                if(s.data[0].constructor === Array) {
                    s.data.sort((a,b)=>{
                        return a[0] > b[0] ? 1 : b[0] > a[0] ? -1 : 0;
                    });
                }
                else {
                    let sort = s.data[0].sort === 'x' ? 'x' : 'y';
                    s.data.sort((a,b)=>{
                        return a[sort] > b[sort] ? 1 : b[sort] > a[sort] ? -1 : 0;
                    });
                }
            }
        });
        if(series.length > 0 && series[0].data.length > 0 && series[0].data[0].constructor === Array){
            series.sort((a,b)=>{
                return a.data[0][0] > b.data[0][0] ? 1 : b.data[0][0] > a.data[0][0] ? -1 : 0;
            });
        }
    }
    return series;
},
drawChart() {
    let self = this;
    if(Ember.$(`#${this.chartId}`)){
        let series = this.processSeriesInformation(), stackTotalFormat = '', tooltipFormat = {}, config, axes = {},
        legend = {
            enabled: true,
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        };          
        if(this.selectedChartType.stacked){
            stackTotalFormat = '<br/>Total: {point.stackTotal}<br/>';
        }
        if(this.chartData.legend !== undefined){
            if(this.chartData.legend === false){
                legend = false;
            }
            else if(this.chartData.legend === 'left' || this.chartData.legend === 'right') {
                legend = {
                    enabled: true,
                    layout: 'vertical',
                    align: this.chartData.legend,
                    verticalAlign: 'middle'
                };
            }
            else {
                legend = {
                    enabled: true,
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: this.chartData.legend
                };
            }
        }
        if(this.chartData.tooltipFormat !== undefined){
            tooltipFormat = this.chartData.tooltipFormat;
        }
        if(this.chartData.axes === undefined || this.chartData.axes.x === undefined || this.chartData.axes.y === undefined){
            axes = {x: [{}], y: [{}]};
        }
        else {
            axes.x = [];
            axes.y = [];
            if(this.chartData.axes.x.constructor === Array){
                this.chartData.axes.x.forEach(x=>{
                    axes.x.push(this.getAxisObject(x));
                });
            }
            else {
                axes.x.push(this.getAxisObject(this.chartData.axes.x));
            }
            if(this.chartData.axes.y.constructor === Array){
                this.chartData.axes.y.forEach(y=>{
                    axes.y.push(this.getAxisObject(y));
                });
            }
            else {
                axes.y.push(this.getAxisObject(this.chartData.axes.y));
            }
        }
        config = {
            chart: {
                renderTo: this.chartId,
                type: this.selectedChartType.value,
                borderColor: '#EBBA95',
                borderWidth: 2,
                borderRadius: '10px',
                backgroundColor: '#FFF',
                zoomType: 'xy',
                inverted: this.selectedChartType.inverted,
                options3d: {
                    enabled: this.selectedChartType.threeD,
                    alpha: 40
                },
                height: this.chartData.height,
                width: this.chartData.width
            },
            credits: {
                enabled: false
            },
            title: {
                text: this.chartData.title
            },
            exporting: false,
            series: series,
            subtitle: {
                text: this.chartData.subtitle
            },
            legend: legend,
            xAxis: axes.x,
            yAxis: axes.y,
            tooltip: {
                borderRadius: 10,
                delay: 500,
                headerFormat: tooltipFormat.header !== undefined ? tooltipFormat.header : '<b>Category: {point.x}</b><br/>',
                pointFormat: tooltipFormat.point !== undefined ? tooltipFormat.point : `Series {series.name}: {point.y}<br/>`,
                formatter: tooltipFormat.formatter,
                split: tooltipFormat.split,
                shared: !tooltipFormat.shared
            },
            plotOptions: {
                column: {
                    stacking: this.selectedChartType.stacked ? 'normal' : false,
                    dataLabels: {
                        enabled: true,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'gray'
                    }
                },
                columnrange: {
                    dataLabels: {
                        enabled: true,
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'gray'
                        }
                    }   
                },
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        }
                    },
                    showInLegend: true,
                    innerSize: this.selectedChartType.donut ? this.chartData.innerSize ? this.chartData.innerSize : 70 : 0,
                    depth: this.selectedChartType.threeD ? 30 : 0
                },
                solidgauge: {
                    dataLabels: {
                        enabled: false,
                        style: {
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        }
                    },
                    stickyTracking: false,
                    rounded: false
                },
                series: {
                    marker: {
                        enabled: this.chartData.markersEnabled
                    },
                    stacking: this.selectedChartType.stacked ? 'normal' : false,
                    dataLabels: {
                        enabled: false,
                        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'gray'
                    },
                    point: {
                        events: {
                            click: function(e) {
                                self.sendAction('onChartClicked', this);
                            },
                            legendItemClick: function () {
                                return false;
                            }
                        }
                    },
                    turboThreshold: 10000,
                    cursor: 'pointer'
                }
            },
            rangeSelector: {
                enabled: this.chartData.rangeSelector ? this.chartData.rangeSelector : false
            },
            navigator: {
                enabled: this.slider
            },
            scrollbar: {
                enabled: this.slider
            }
        };
        if(this.selectedChartType.value === 'solidgauge'){
            config.pane = {
                startAngle: 0,
                endAngle: 360,
                background: [{
                    outerRadius: '100%',
                    innerRadius: '63%',
                    backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0.3).get(),
                    borderWidth: 0
                }]
            };
            config.tooltip.positioner = (labelWidth) => {
                return {
                    x: 200 - labelWidth / 4,
                    y: 180
                };
            };
            config.yAxis.max = 100;
            config.yAxis.min = 0;
            config.series.forEach(s=>{
                s.data = s.data.map(d=>{
                    return {
                        color: Highcharts.Color(Highcharts.getOptions().colors[0]),
                        outerRadius: '112%',
                        innerRadius: '63%',
                        y: d
                    };
                });
            });
        }
        this.set('chart', Highcharts.stockChart(config));
        if(this.customSlider && this.chartData.rangeConfig === undefined){
            this.chart.axes.forEach(axis=>{
                if(axis.isXAxis){
                    Ember.set(this.chartData, 'rangeConfig', { min: axis.min, max: axis.max, type: this.chartData.axes.x.type === 'datetime' ? 'datetime': 'numeric', start: [axis.min, axis.max] });
                }
            });
        }
    }
},
actions: {
    selectChartType(event, type){
        this.set('selectedChartType', type);
        this.drawChart();
    },
    rangeChanged(newRangeValues){
        Ember.set(this.chartData.axes.x, 'min', newRangeValues[0]);
        Ember.set(this.chartData.axes.x, 'max', newRangeValues[1]);
        this.drawChart();
        this.sendAction('onRangeChanged', this.chartData.axes.x);
    }
}

});




Issue with a belongsTo relationships in an ember-engines

I will try to explain the situation.
I have three models, lets call them: room, furnitures, chair.

Now, lets see how the models are declared. room, located in lib/room/app/room.js

export default DS.model.extend({
    name: DS.attr('string'),
    mostPreciousFurniture: DS.belongsTo('furniture')
});

furniture, located in lib/furniture/app/furniture.js

 export default DS.model.extend({
        name: DS.attr('string'),
        type: DS.attr('string') // type of the furniture(chair, table, etc...)
 });

chair, located in lib/chair/app/chair.js

import Furniture from 'web/models/furniture'

export default Furniture.extend({
          material: DS.attr('string')
     });

So we have three model, room with a belongsTo relationships to furniture, chair who is a 'member' of furniture, and furniture who is a basic model.

Now I can set the value of room.mostPreciousFurniture with chair for example(in a form), and when I save my model, my backend server receive the id of the furniture.
But when I try to fetch this relationships in the store, it is not found. This is a problem, because if I want to edit my room model, I cannot access to the previous value of mostPreciousFurniture.

I set the value of mostPreciousFurniture in a components,

setMostPrecious(params)
        {
            let type = params.type; // type here is chair for example
            this.get('store').find(type, params.id).then((furniture) => {
                this.get('room').set('mostPreciousFurniture', furniture);
            });
        }

If I console.log my relationships here, I will say that it is filled, which is a good start. But as I already say, once I refresh my page I can access to the data of room except the mostPreciousFurniture.

I may have missed some information, if you need more please tell me. Any tips is appreciated.




dimanche 22 octobre 2017

Emberjs Getting array property returns undefined

I want to define a reactive array property in a component so that every time the array is updated, it auto-updates necessary HTML content.

I thought this was going to be straightforward, but it didn't work as I expected. Every time I retrieve the property via this.get('array'), it returns undefined.

// components/test-component.js
export default Ember.Component.extend({
  _array: [],

  array: Ember.computed('_array',{
    get(key) { return this.get('_array'); },
    set(key,value) { this.set('_array', value); }
  }),

  isEmpty: Ember.computed('array', function() {
    // Here, this.get('array') returns undefined. Why?
    return this.get('array').length;
  }),

  actions: {
    addNew() {
      this.get('array').push(Date.now());
    }
  },

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

    this.set('array', [1,2,3]);
  },
});

I also noticed that in the init method, if I retrieve the array property right after setting it, it also returns undefined. Why is this happening?

Here is a twiddle. It is supposed to iterate the array, and show a list of all items, but it is currently crashing because it returns undefined.




samedi 21 octobre 2017

Ember.js - Uncaught SyntaxError: Unexpected identifier

I can't seem to correct the error in the console. My code searches the text files for a query term. If the query term is present, I want the query term in the text to be highlighted. Not able to figure out this.

  var App = Ember.Application.create();   
    App.Router.map(function() {
      // index route is created by default
    });

    App.IndexController = Em.Controller.extend({
        actions: {
            doSearch: function() {
                var self = this;
                self.set('results', null);
                Em.$.get('/patients/search?query='+this.get('searchText')).then(function(data) {
                    for (var i=0;i<data.length;i++) {
                        var docs = data[i].documents;
                        var newDocs = [];
                        for (var j=0;j<docs.length;j++) {
                            parts = docs[j].split(":::");
                            newDocs.push({
                                title: parts[0],
                                date: parts[1],
                                contents: parts[2]
                            });
                        }
                        data[i].documents = newDocs;
                    }
                    self.set('results', data);
                });     
            }
        },

                var queryTerm = this.get('searchText');      //ERROR IN THIS LINE
                Ember.Handlebars.helper('highlightSearchTerm', function (text, queryTerm) {
                    var highlightedText = text.replace(new RegExp(queryTerm, 'gi'), function (str) {
                    return '<mark>' + str + '</mark>';
                });
            return new Ember.Handlebars.SafeString(highlightedText);
            });  
    });




emberfire: this._ref.push is not a function

The Issue

I seem to be getting the following error with emberfire, I followed the documentation yet still get the error:

Uncaught TypeError: this._ref.push is not a function
    at Class.generateIdForRecord (firebase.js:75)
    at Class._generateId (-private.js:10359)
    at Class.createRecord (-private.js:10325)
    at Class.test (home.js:13)
    at Class.send (action_handler.js:32)
    at action.js:141
    at exports.flaggedInstrument (ember-metal.js:3730)
    at action.js:140
    at Backburner.run (backburner.js:537)
    at run (ember-metal.js:4267)

The following code is where the error comes from, the code is simply placed in an action in a controller called home:

var newGlobal = this.store.createRecord('global', {
  about: 'test',
});
newGlobal.save();

The rules on the database are set up as:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

and the database is empty.

I have also setup config/environment.js

Any ideas please?

Thank you in advance

Helpful Links

emberfire

Emberfire guide

Found these issues but they didn't help with my issue




Is it a good idea to not use ember-data for performance reasons

Below are a couple of performance tests of Ember object creation.

Ember v2.3.1 with jQuery Snapshot of Ember v2.3.1 jsperf results

Ember v2.16.0 (latest as of the writing of this post) enter image description here

A couple of take-aways:

  1. Creating Ember objects is much slower than creating plain JS objects (about 100 times slower for Ember v2.3.1, and about 300 times slower for Ember v2.16.0)
  2. Ember v2.16.0 is slower than Ember v2.3.1 in terms of Ember object creation

I ran the perf tests repeatedly. The two above points were consistent across all my runs.

Now, suppose I want to create a new complex web UI using Ember. The UI needs to exchange a fair amount data (say, 100KB per http call) with backend frequently. Based on above performance results, and my assumption that ember-data needs to call a number of Ember.Object.create() per model, is it a good idea to not use ember-data in the app? One alternative will be just make ajax calls in model hook manually, and only create Ember object when it is necessary?

BTW, let's assume we have to use Ember in this scenario. The interesting question here is whether we can get performance gains by not using ember-data? Or, if we need to use ember-data for it's advantages, what are the usual optimizations we can do?




vendredi 20 octobre 2017

Converting backend `pdf-stream` to pdf and save to local system

I am getting a pdf-streat as a response from backend server. I require to convert this stream to pdf file and require to allow the user to save on their local machine. how to do that?

here is the response i receive:

    "pdf-stream": "JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9MZW5ndGggMzcwL0ZpbHRlci9GbGF0ZURlY29kZT4+c3RyZWFtCniclZPNUsIwFIX3eYq7xAXxJmn6s1SQwVHHUfsCxYaCQ9OhpAvf3pLbgYJ1hFXTycm535yTbNl9ylQIMYaQ5kxK5BrGwv/czgQkkC4ZggCEumCjd7NtzM7BR7Mo186Z/Cb9arcLNqaT6E10wmPVupCJBCH3LiPYi8fdLillyFXcnxf7eTzSMgng/EsES1Mb+2nANuXC1D0A70W+GHGhjr4HBBFhLEIhVTLXGGFARKT+zT5ELALeul5H7DMzOTxXmYW7smqsO2KTIZkr5EEygD1/mrZLJSTxkOwyXql4y3EN76PduWxTGutg2tSZW1e2F7K362g1F3ooZHyprFvtOlivugwWY9q/HNZP2nxDD/o8YDKlAYE8aa8fsEDiIUlXdsTxuvBerYF0XRqYZzbfrG0BM2N6ZXvDQ3x/lZ3goWp9rFqJ07f5L8xkldVFy1PBJKt7T9UbdddD8CAa7LC9ZUkcBTpUREJKf+ohZW/sB0yn86gKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8L1R5cGUvUGFnZS9NZWRpYUJveFswIDAgNTk1IDg0Ml0vUmVzb3VyY2VzPDwvRm9udDw8L0YxIDEgMCBSL0YyIDIgMCBSPj4+Pi9Db250ZW50cyAzIDAgUi9QYXJlbnQgNCAwIFI+PgplbmRvYmoKMSAwIG9iago8PC9UeXBlL0ZvbnQvU3VidHlwZS9UeXBlMS9CYXNlRm9udC9IZWx2ZXRpY2EtQm9sZC9FbmNvZGluZy9XaW5BbnNpRW5jb2Rpbmc+PgplbmRvYmoKMiAwIG9iago8PC9UeXBlL0ZvbnQvU3VidHlwZS9UeXBlMS9CYXNlRm9udC9IZWx2ZXRpY2EvRW5jb2RpbmcvV2luQW5zaUVuY29kaW5nPj4KZW5kb2JqCjQgMCBvYmoKPDwvVHlwZS9QYWdlcy9Db3VudCAxL0tpZHNbNSAwIFJdPj4KZW5kb2JqCjYgMCBvYmoKPDwvVHlwZS9DYXRhbG9nL1BhZ2VzIDQgMCBSPj4KZW5kb2JqCjcgMCBvYmoKPDwvUHJvZHVjZXIoaVRleHSuIDUuNS45IKkyMDAwLTIwMTUgaVRleHQgR3JvdXAgTlYgXChBR1BMLXZlcnNpb25cKSkvQ3JlYXRpb25EYXRlKEQ6MjAxNzEwMjAxNzMxMjQrMDUnMzAnKS9Nb2REYXRlKEQ6MjAxNzEwMjAxNzMxMjQrMDUnMzAnKT4+CmVuZG9iagp4cmVmCjAgOAowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDA1NzMgMDAwMDAgbiAKMDAwMDAwMDY2NiAwMDAwMCBuIAowMDAwMDAwMDE1IDAwMDAwIG4gCjAwMDAwMDA3NTQgMDAwMDAgbiAKMDAwMDAwMDQ1MiAwMDAwMCBuIAowMDAwMDAwODA1IDAwMDAwIG4gCjAwMDAwMDA4NTAgMDAwMDAgbiAKdHJhaWxlcgo8PC9TaXplIDgvUm9vdCA2IDAgUi9JbmZvIDcgMCBSL0lEIFs8NDc2NzJjZjE5ZmE0MjcwZDNhMzM3ODM2YmIyNjU0MzU+PDQ3NjcyY2YxOWZhNDI3MGQzYTMzNzgzNmJiMjY1NDM1Pl0+PgolaVRleHQtNS41LjkKc3RhcnR4cmVmCjEwMDcKJSVFT0YK",
    "rel-number": "C123441"
},




EmberJS 2 Dynamic Routing

I'm trying to setup a way to define routes, their template and model dynamically. (Ember 2.16.0)

So far I have this:

// app/router.js
Router.map(function () {

    let routes = [
        {route: "page_one", templateName: "default.hbs"},
        {route: "page_two", templateName: "default.hbs"},
        {route: "page_three", templateName: "custom.hbs"}
    ];

    routes.forEach(function (key) {
        this.route(key.route);
    }, this);
});

This works, and allows me to load pages if their template file exists.

I want to take this a step further and define the template name here, for example I want them all to use "default.hbs" as well as load the model for them dynamically.

Is this something that's possible in EmberJS? If so which documentation should I be looking at to do so.

I'm aware you can specify templates in their corresponding route file "app/routes/page_one.js" but this wouldn't be dynamic.




ember cli dont compile with daterangepicker

I install ember-cli-daterangepicker. I did error server and this had working good, but I get error now. I install anything.

I do ember server and get it

File: ember-cli-daterangepicker/components/date-range-picker.js The
Broccoli Plugin: [broccoli-persistent-filter:Babel] failed with:
Error: incorrect header check
 at Zlib._handle.onerror (zlib.js:370:17)


The broccoli plugin was instantiated at:
 at Babel.Plugin (F:\Projects\tomaq\node_modules\broccoli-plugin\index.js:7:31)
 at Babel.Filter [as constructor] (F:\Projects\tomaq\node_modules\broccoli-persistent-filter\index.js:62:10)
 at new Babel (F:\Projects\tomaq\node_modules\broccoli-babel-transpiler\index.js:35:10)
 at EmberApp._addonTree (F:\Projects\tomaq\node_modules\ember-cli\lib\broccoli\ember-app.js:913:29)
 at EmberApp._processedVendorTree (F:\Projects\tomaq\node_modules\ember-cli\lib\broccoli\ember-app.js:947:20)
 at EmberApp._processedExternalTree (F:\Projects\tomaq\node_modules\ember-cli\lib\broccoli\ember-app.js:978:21)
 at EmberApp.appAndDependencies (F:\Projects\tomaq\node_modules\ember-cli\lib\broccoli\ember-app.js:1087:30)
 at EmberApp.javascript (F:\Projects\tomaq\node_modules\ember-cli\lib\broccoli\ember-app.js:1217:34)
 at EmberApp.toArray (F:\Projects\tomaq\node_modules\ember-cli\lib\broccoli\ember-app.js:1646:10)
 at EmberApp.toTree (F:\Projects\tomaq\node_modules\ember-cli\lib\broccoli\ember-app.js:1668:30)
 at module.exports (F:\Projects\tomaq\ember-cli-build.js:43:14)
 at CoreObject.setupBroccoliBuilder (F:\Projects\tomaq\node_modules\ember-cli\lib\models\builder.js:72:19)
 at CoreObject.init (F:\Projects\tomaq\node_modules\ember-cli\lib\models\builder.js:52:10)
 at CoreObject.superWrapper [as init] (F:\Projects\tomaq\node_modules\core-object\lib\assign-properties.js:32:18)
 at CoreObject.Class (F:\Projects\tomaq\node_modules\core-object\core-object.js:32:33)
 at CoreObject.run (F:\Projects\tomaq\node_modules\ember-cli\lib\tasks\serve.js:15:19)
 at F:\Projects\tomaq\node_modules\ember-cli\lib\commands\serve.js:76:24
 at tryCatch (F:\Projects\tomaq\node_modules\rsvp\dist\rsvp.js:539:12)
 at invokeCallback (F:\Projects\tomaq\node_modules\rsvp\dist\rsvp.js:554:13)
 at publish (F:\Projects\tomaq\node_modules\rsvp\dist\rsvp.js:522:7)
 at flush (F:\Projects\tomaq\node_modules\rsvp\dist\rsvp.js:2414:5)
 at _combinedTickCallback (internal/process/next_tick.js:67:7)
 at process._tickCallback (internal/process/next_tick.js:98:9)

How fix it problem?

My package.json

{
  "name": "tomaq",
  "version": "0.0.0",
  "description": "Small description for tomaq goes here",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "repository": "",
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^2.4.1",
    "ember-cli": "2.10.0",
    "ember-cli-app-version": "^2.0.0",
    "ember-cli-babel": "^5.1.7",
    "ember-cli-daterangepicker": "0.6.0",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-g-maps": "0.5.14",
    "ember-cli-htmlbars": "^1.0.10",
    "ember-cli-htmlbars-inline-precompile": "^0.3.3",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-jshint": "^2.0.1",
    "ember-cli-lazy-load": "0.3.0",
    "ember-cli-moment-shim": "3.5.0",
    "ember-cli-pagination": "3.0.2",
    "ember-cli-qunit": "^3.0.1",
    "ember-cli-release": "^0.2.9",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^1.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "^2.10.0",
    "ember-export-application-global": "^1.0.5",
    "ember-load-initializers": "^0.5.1",
    "ember-moment": "^7.3.1",
    "ember-perfectscroll": "0.1.15",
    "ember-resolver": "^2.0.3",
    "ember-rx-shim": "0.1.4",
    "ember-scrollable": "0.4.9",
    "ember-simple-pagination": "1.0.1",
    "ember-truth-helpers": "1.3.0",
    "ember-welcome-page": "^1.0.3",
    "gulp": "^3.8.0",
    "gulp-compass": "^1.3.3",
    "gulp-concat": "^2.2.0",
    "gulp-ember-handlebars": "^0.6.0",
    "gulp-imagemin": "^3.3.0",
    "gulp-uglify": "^0.3.0",
    "gulp-watch": "^0.6.5",
    "loader.js": "^4.0.10"
  },
  "engines": {
    "node": ">= 0.12.0"
  },
  "private": true,
  "dependencies": {
    "bootstrap": "^3.3.7",
    "ember-bootstrap": "^1.0.0-beta.1",
    "ember-i18n": "^5.0.1",
    "ember-validations": "2.0.0-alpha.5",
    "gulp": "^3.9.1",
    "gulp-shell": "^0.6.3",
    "gulp-uglifycss": "^1.0.8"
  }
}




Ember App + ember simple auth + ember fastboot protected route redirects when already authenticated

I implement ember simple auth+ ember fastboot on my ember app. But when i try to refresh on protected route it redirects to my homepage. I configured SessionStore to CookieStore still same results. Is it because of my backend server?. Even i use fastboot-app-server result is still same. How can i make it work?




PDFJS - memory shoots up to 1 GB and does not decrease even after destroying the loadingTask

I am developing an ember application - pdf viewer. I use the ember addon - ember-pdf-js. Here I have created a component that uses the 'PDFJS' object to render the pdf. I load the document using 'getdocument(url)' method of PDFJS. Here while scrolling through the pdf, in the task manager I noticed that the memory shoots upto 1 GB. Even after destroying the component, the memory consumed still does not decrease quickly. Also memory does not clear up if the byte-range requests in pending are aborted while destroying the component.

I want to know if I am missing out on something to be destroyed/cleaned. Below is the willDestroyElement method called in my component while it destroys. Kindly let me know if I am missing out on something.

    willDestroyElement() {
     let self=this;
     self._super(...arguments);
     get(self,'pdfLoadingTask').destroy(); //To destroy the byte-range requests once the component is destroyed
     set(self,'pdfLoadingTask',null);
    }




jeudi 19 octobre 2017

JSON API group and subgroup EmberJS

So I want to build the following select dropdown in ember, using ember data and the API is going to be using the JSON API spec. Here is a screenshot example Select Dropdown

So would I in the services model, state the following

app/model/service.js

category: DS.belongsTo('category'),
subCategory: DS.belongsTo('sub-category')

app/model/category.js

service: DS.hasMany('service'),
subCategory: DS.belongsTo('category')

app/model/category.js

service: DS.hasMany('service'),
category: DS.belongsTo('sub-category')

I feel like I am missing something? Thoughts




Adding Style to Ember Paper Button

I'm working with Ember Paper for the first time and I'm having trouble. My trouble is that i want to add a class to the component. It won't work. I could see the class in the html tag after inspecting it through Google Chrome but adding background to it won't work.

Here is my code:

    <div class="layout-row layout-xs-column">
  <div class="layout-column flex-xs flex-gt-xs-30"></div>
  <div class="layout-column flex-xs flex-gt-xs-40">
    
      
        
           Login 
        
      
      
        
        
      
      
         Login 
      
    
  </div>
  <div class="layout-column flex-xs flex-gt-xs-30"></div>
</div>

I added .button in my app.scss stylesheet but it won't work.

How can I apply a custom style to single component?

And how can I override the $primary to be ('teal', '500')?




Mirage asking for modelid

So I am trying to setup mirage to use faker and I have done that but I am getting the following error:

assert.js:35 Mirage: The route handler for /services/1 is trying to access the :serviceId model, but that model doesn't exist. Create it using 'ember g mirage-model :service-id'.

Here is my mirage/config

export default function() {
  this.get('/services/categories');
  this.get('/services/:service_id');
}

Let me know if you need to see more data




Ember deleting a freshly created record throws error

I create a record in my controller with record = store.createRecord(variables) Then I call record.save();

Some of the attributes i.e. the id are getting set in the API(Laravel). After creation the record shows up in my template. However I cannot delete this freshly created record.

It throws the error: Uncaught EmberError {description: undefined, fileName: undefined, lineNumber: undefined, message: "Assertion Failed:idpassed tofindRecord()has to be non-empty string or number", name: "Error", …}

When I look up in Ember Inspector the id is missing and it has the dirtyAttributes Flag set to true.

I already tried a route refresh and it didnt help. Also I tried to to modify my route with reload set to true:

model: function(params) {
    return this.store.findAll('rental', params.id, { reload: true });
  },

but this also didnt help. The only thing that works is to do a manual browser refresh (F5).

Any idea how I can get the full model reloaded?




Can't sort Posts on Emberfire

I am trying to sort my posts so that the most recent appears on my blog central page. I am able to manipulate by author and title, but I am really trying to get the most recent published date to appear at the top of the page. Is there something I need to do with the sortproperties on the controller? I've tried messing with the "limitToFirst" and "limitToLast" as well. I also tried "publishedDate" instead of published, but published appears in the "Ember Inspector", so I think published is what I want. Here is my code below:

controllers/post.js 

import Ember from 'ember';

 export default Ember.Controller.extend({
 sortProperties: ['published'],
 sortAscending: false, // sorts post by timestamp
 actions: {
 publishPost: function() {
  var newPost = this.store.createRecord('post', {
    title: this.get('title'),
    post: this.get('post'),
    author: this.get('author'),
     published: new Date().getTime()
  });

  newPost.save();
   }
  }
});

models/post.js

import DS from 'ember-data';

 export default DS.Model.extend({
 title: DS.attr('string'),
 author: DS.attr('string'),
post: DS.attr('string'),
published: DS.attr('number'),
 publishedDate: Ember.computed('published', function() {
return moment(this.get('published')).format('MMMM Do, YYYY');
 })
});

route/post.js

import Ember from 'ember';

export default Ember.Route.extend({
 model: function() {
  return this.store.query('post', {
    orderBy: 'publishedDate',
    limitToFirst: 10
 });
}
});

template/blog.js

 <h2>Below are your Latest Blog Posts</h2>

 <div class="col-sm-8">
    
    <div id=blogPost>
        <div id='published'><p>Published:  </p></div>
        <div id='title'><p>Title:  </p></div>
        <div id='author'><p>Author:  </p></div>
        <div id='body'><p>Post:  </p></div>
    </div>
    
  </div>
</div>




Ember - Preload page Not triggering for slow model

I am trying to add a preloading page for my slow model page. But my router not show the template for preload.

here is my structure of route:

http://localhost:4302/cs2i/purchase/purchaseDetails

this.route('cs2i', function() {

    this.route('purchase', function() {
      this.route('purchaseDetails', function(){
        this.route('loading'); //not loading I do have template
      });
      this.route('purchaseDetails-loading'); //not loading I do have template
    });
  });

what is the issue? how can i put a preloader to my route untill my data and template are rendered?

thanks in advance.

As well I do have a action with my 'purchase' page, which is triggeres even before data load.

actions: {

        loading : function( transition, originRoute ){

            console.log("loding done");//getting before data load

        },




mercredi 18 octobre 2017

How do you access nested objects in Emberjs?

I'm trying to access a nested object from an ember model. The models look like this: Content:

export default DS.Model.extend({
  title: DS.attr('string'),
  text: DS.attr('string'),
  createdBy: DS.attr('string'),
  status: DS.attr('string'),
  contentType: DS.attr('string'),
  author: DS.belongsTo('author', { embedded: true }),
  campaign: DS.belongsTo('campaign', { embedded: true })
});

Author:

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

Campaign:

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

I'm calling a list of objects from a Rails REST API. The data looks like this:

 {
  "data": [
    {
      "id": "1",
      "type": "contents",
      "attributes": {
        "title": "The Great Escape",
        "text": "This is the way the world ends!",
        "status": "Draft",
        "content-type": "Blog Post",
        "created-by": "#\\u003cUser:0x007fe4920d8850\\u003e",
        "author": {
          "id": 3,
          "name": "Daniel Duck",
          "created_at": "2017-10-17T21:56:00.105Z",
          "updated_at": "2017-10-17T21:56:00.105Z"
        },
        "campaign": {
          "id": 3,
          "name": "Apple - Fall",
          "created_at": "2017-10-17T21:56:00.093Z",
          "updated_at": "2017-10-17T21:56:00.093Z"
        }
      }
    },
    {
      "id": "2",
      "type": "contents",
      "attributes": {
        "title": "Just a lonely Joe in search of his soul",
        "text": "One day he'll be a real boy.",
        "status": "Final",
        "content-type": "Email",
        "created-by": "#\\u003cUser:0x007fe4920d8850\\u003e",
        "author": {
          "id": 2,
          "name": "Roberta Rock",
          "created_at": "2017-10-17T21:56:00.103Z",
          "updated_at": "2017-10-17T21:56:00.103Z"
        },
        "campaign": {
          "id": 2,
          "name": "Blade Runner 2049",
          "created_at": "2017-10-17T21:56:00.091Z",
          "updated_at": "2017-10-17T21:56:00.091Z"
        }
      }
    },
    {
      "id": "3",
      "type": "contents",
      "attributes": {
        "title": "Love in the time of Silicon Valley",
        "text": "Maybe love IS all we need.",
        "status": "Waiting for Review",
        "content-type": "PR Release",
        "created-by": "#\\u003cUser:0x007fe4920d8850\\u003e",
        "author": {
          "id": 1,
          "name": "James Jackson",
          "created_at": "2017-10-17T21:56:00.101Z",
          "updated_at": "2017-10-17T21:56:00.101Z"
        },
        "campaign": {
          "id": 1,
          "name": "PRP",
          "created_at": "2017-10-17T21:56:00.089Z",
          "updated_at": "2017-10-17T21:56:00.089Z"
        }
      }
    }
  ]
}

I setup the contents route:

export default Route.extend({
    model() {
        return this.get('store').findAll('content', {include: 'author'});
    }
});

I set up the template:

<div class="jumbo">
<h1>Contents</h1>

</div>

    


I set up the listing component like this:


<article class="content">
  <h3></h3>
  <div class="detail owner">
    <span>Author:</span> 
  </div>
  <div class="detail text">
    <span>Text:</span> 
  </div>
  <div class="detail status">
    <span>Status:</span> 
  </div>
  <div class="detail content_type">
    <span>Content Type:</span> 
  </div>
</article>

When I try to list the objects:

Contents

The Great Escape

Author: <DS.PromiseObject:ember389>
Text: This is the way the world ends!
Status: Draft
Content Type: Blog Post
Just a lonely Joe in search of his soul

Author: <DS.PromiseObject:ember392>
Text: One day he'll be a real boy.
Status: Final
Content Type: Email
Love in the time of Silicon Valley

Author: <DS.PromiseObject:ember395>
Text: Maybe love IS all we need.
Status: Waiting for Review
Content Type: PR Release

How do I resolves the Promise and get the author object?




ember twitter bootstrap ember-sass ember-modal-dialog extra arrows in select tag

I have an ember project with twitter bootstrap 4. After adding ember-sass my select tags now show up like the following:

enter image description here

The arrows to the far right, are the problem.

Any insight on how to remove the arrows to the far right would be greatly appreciated.

I also added ember-modal-dialog, I do not think this caused any issue but not sure, so I will just mention it.




Override the default package.json generated by ember-cli addon

We create a lot of ember addons for internal use in our web application. To suit our needs we make minor modifications the the files generated by ember-cli when creating addons such as the package.json, ember.try, ect.

Currently I am exploring the possibility of overriding ember-cli's default blueprint for generating addons to streamline this process, but have had little luck finding any resources on this.

I was able to override the default blueprints for our routes and controllers but doing this for the addon command seems to be slightly different.

Does anyone have experience doing something slimier to this?




EmberJS Express API | Error: Assertion Failed: 'note' was saved to the server, but the response does not have an id and your record does not either

Fix one problem and get another right?
Using EmberJS, I have an API that is working fully based on the testing with Postman. I am now trying to incorporate it into an EmberJS project and am having issues with updating the database.
It seems that the EmberData is being updated, duplicated, but not updated in the database. I get this error after I call note.save();

Here is my file structure:
api
- -controllers
- - - - noteController.js
- -models
- - - - noteModel.js
- -node_modules
- -routes
- - - - noteRoute.js
- -package-lock.json
- -package.json
- -server.js
app
- - adapters
- - - - application.js
- - - - note.js
- - controllers
- - - - note
- - - - - - edit.js
- - models
- - - - note.js
- - routes
- - - - note
- - - - - - edit.js
- - - - notes.js
- - serializers
- - - - note.js
- - templates
- - - - note
- - - - - - edit.hbs
- - - - notes.hbs
config
dist
node_modules
public
server
etc...


Here are the files I believe that will be of use to solving this problem.

api>controllers>noteController.js

'use strict';

let mongoose = require('mongoose'),
    Note = mongoose.model('Notes');

exports.list_all_notes = function(req, res){
    Note.find({}, function(err, note){
        if (err)
            res.send(err);
        else
            res.json(note);
    });
};

exports.create_a_note = function(req, res){
    let new_note = new Note(req.body);
    new_note.save(function (err, note){
        if (err)
            res.send(err);
        else
            res.json(note);
    });
};

exports.update_a_note = function(req, res){
    Note.findById(req.params._id, function(err, note){
        if (err)
            res.status(500).send(err)
        else{
            note.title = req.body.title || note.title;
            note.content = req.body.content || note.content;
            note.author = req.body.author || note.author;

            //save to db
            note.save((err, note) => {
                if (err) {
                    res.status(500).send(err);
                }
                res.status(200).send(note);
            });
        }
    });
}

exports.read_a_note = function(req, res){
    Note.findById(req.params._id, (err, note) => {
        if (err) {
            res.status(500).send(err)
        }
        if (note) {
            res.status(200).send(note)
        } else {
            res.status(404).send("No note found with that ID")
        }
    }
)};

exports.delete_a_note = function(req, res){
    Note.remove({
        _id: req.params.noteId
    }, function(err, task){
        if (err)
            res.send(err);
        else
            res.json({ message: 'Note successfully deleted.' });
    });
};

api>models>noteModel.js

'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

let NoteSchema = new Schema({
    title: { 
        type: String, 
        required: true
    },
    content: { 
        type: String 
    },
    author: { 
        type: String 
    }
});

module.exports = mongoose.model('Notes', NoteSchema);

api>routes>noteRoute.js

'use strict';

let router = require('express').Router();
let note = require('../controllers/noteController');

//router.post('/:_id', note.create_a_note);
//router.post('/', note.create_a_note);
router.patch('/', note.update_a_note);
router.get('/', note.list_all_notes);

router.get('/:_id', note.read_a_note);
router.put('/:_id', note.update_a_note)
router.delete('/notes/:_id', note.list_all_notes);

module.exports = router;

api>server.js

var express = require('express'),
    app = express(),
    port = process.env.PORT || 4500,
    mongoose = require('mongoose'),
    Note = require('./models/noteModel'), //created model loading here
    bodyParser = require('body-parser');

// Allow POST, GET, PUT, DELETE, OPTIONS
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS');
    next();
});

//DB Vars
var uri = 'mongodb://localhost/AccurateEmber2';

// mongoose instance connection url connection
mongoose.Promise = global.Promise;

var options = {
    useMongoClient: true
};
mongoose.connect(uri, function (err) {
    if (err) {
        console.log('ERROR connecting to: ' + uri + '. ' + err);
    } else {
        console.log('Succeeded connected to: ' + uri);
    }
});

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


var noteR = require('./routes/noteRoute'); //importing route
app.use('/notes', noteR);
app.use('/notes/:_id', noteR);

//middleware catch
app.use(function (req, res) {
    res.status(404).send({ url: req.originalUrl + ' not found' })
});

app.listen(port);


console.log('todo list RESTful API server started on: ' + port);


app>adapters>application.js
import DS from 'ember-data';

//import JSONAPIAdapter from 'ember-data/adapters/json-api';

export default DS.RESTAdapter.extend({
    host: 'http://localhost:4500'
});

app>adapters>note.js

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({
    pathForType() {
        return 'notes';
    }
});

app>controllers>note>edit.js

import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        save: function () {
            const title = this.get('model.title');
            const content = this.get('model.content');
            const author = this.get('model.author');
            const id = this.get('model.id');

            var note = this.store.createRecord('note', {
                title: title,
                content: content,
                author: author
            });
            note.save();
            this.transitionToRoute('notes');
        },
        del: function () {
            //this.get('model').deleteRecord();
            let d = this.get('model');
            d.destroyRecord();
            d.save();
            //this.get('model').save();
            this.transitionToRoute('notes');

        }
    }
});

app>models>note.js

    import DS from 'ember-data';

    const {
        attr
    } = DS;

    export default DS.Model.extend({
        title: attr('string'),
        content: attr('string'),
        author: attr('string')
    });
app>routes>note>edit.js  
    import Ember from 'ember';

    export default Ember.Route.extend({
    });

app>routes>notes.js

import Ember from 'ember';

const {
  set,
  Route,
    inject: {
  }
} = Ember;

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

    //Overwrite
    //Allows us to use "notes" in notes.hbs rather than "model" in the  call.
    setupController(controller, model) {
        set(controller, 'notes', model);
    }
});

app>serializers>note.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    normalizeResponse(store, primaryModelClass, payload, id, requestType){      
        let isArr = Object.prototype.toString.call(payload) == '[object Array]';
        if (!isArr){
            payload = { notes: payload };
            payload.notes.id = payload.notes._id;
            delete payload.notes._id;
        }else{
        payload = {notes: payload};
            payload.notes.forEach(function(note) {
                note.id = note._id;
                delete note._id;
            }, this);
        }
        return this._super(store, primaryModelClass, payload, id, requestType);
    }  
});

app>templates>note>edit.hbs

<div class="container">
    <div class="row">
        <h2> Edit Note</h2>
        <form >
            <dl>
                <dt>
                    <p>ID:</p> 
                </dt>
                <dt>
                    <p>Title:</p> 
                </dt>
                <dt>
                    <p>Content:</p> 
                </dt>
                <dt>
                    <p>Author:</p> 
                </dt>
            </dl>
            <div class="row">
                <button type="submit" class="btn btn-primary">Done</button>
                <button type="delete" class="btn btn-primary" >Destroy</button>
            </div>
        </form>
    </div>
</div>

app>templates>notes.hbs

<div class="container">
    <div class="row">
            <h1>Notes</h1>
             
            <h3></h3>
            
            <p>
                <br>By: </p>
            
        
    </div>
</div>