vendredi 30 juin 2017

HTML5 input type file Error handling

I build a module to upload files using HTML5 input type file element. I found I issue which I need to address/ resolve by showing proper error message:-

1) User selects a file to upload but before pressing uploading button user deleted the source file. now user clicks upload button. In my case nothing happens on UI.

I want to ask that by any means we can know weather file still exists before clicking upload button on input type file element of HTML5.

Pls Note: I am using ember.js




'ApplicationRouteMix' is defined but never used [Ember.js]

I am creating an authentication to login to my app, but I am with these 3 problems and I do not know how to proceed, I am new to ember, I do not know much about how to fix problems, I am learning it yet, after I followed this process my app does not appear anymore the screen went blank only, the tutorial is that of ember-simple-auth: http://ift.tt/1HLYcPX - thank you in advance:

Could not start watchman
Visit http://ift.tt/2huy34z for more info.
Livereload server on http://localhost:49153
'instrument' is imported from external module 'ember-data/-debug' but 
never used

/home/carlos/www/vendasapi-frontend/app/controllers/login.js
4:31  error  'session' is not defined  no-undef

✖ 1 problem (1 error, 0 warnings)


/home/carlos/www/vendasapi-frontend/app/routes/application.js
2:8   error  'ApplicationRouteMix' is defined but never used  no-
unused-vars
5:35  error  'ApplicationRouteMixin' is not defined           no-undef

✖ 2 problems (2 errors, 0 warnings)


Build successful (4688ms) – Serving on http://localhost:4200/



Slowest Nodes (totalTime => 5% )              | Total (avg)         
----------------------------------------------+---------------------

Babel (20)                                    | 1481ms (74 ms)      
Rollup (1)                                    | 1352ms              
EslintValidationFilter (2)                    | 703ms (351 ms)      
Concat (8)                                    | 545ms (68 ms)       

app/controllers/login.js

import Ember from 'ember';

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

  actions: {
    authenticate() {
  let { identification, password } = 
this.getProperties('identification', 'password');

   this.get('session').authenticate('authenticator:oauth2', 
identification, password).catch((reason) => {
     this.set('errorMessage', reason.error);
      });

    }

  }

});

app/controllers/application.js

import Ember from 'ember';

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

   actions: {
     logout() {
      this.get('session').invalidate();
   }
 }
});

app/routes/application.js

import Ember from 'ember';
import ApplicationRouteMix from
'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin);




What to use instead of bind-attr helper in Ember.js?

When I want to use bind-attr helper on the simple table data argument (). To change the color of that column it writes an error on console:

TypeError: Cannot read property 'getAttribute' of undefined

-Here is my index.hbs:

   <table id="t01">
          <tr>
            <th>Company Name</th>
            <th>Headquarters</th> 
            <th>revenue</th>
          </tr>
          
            <tr>
                        <td>   </td>
                        <td >           </td>
                        <td>   </td>
            </tr>
          
    </table>
    <button > Change color </button>

-And here is my index.js controller:

import Ember from 'ember';


export default Ember.Controller.extend({
  className:"red",
  actions:{
    toggleColor: function(){
      if(this.get("className") == "red"){
        this.set("className","blue");  
      }else{
        this.set("className","red");  
      }
      
    }
  }
});

-Does anyone has any idea what is wrong? It doesn't even show the values in the table that would actually show if I didn't use the bind-attr.




ember.js 2, promises or not promises?

I have this code:

let promise = child.get('authors').forEach(author => author.get('books').forEach(book => {

  let time = (Math.floor(Math.random() * 10) + 1) * 1000;

  Ember.run.later(() => {

    //Some operations and then every book in the forEach is added to my favoriteList
    favoriteList.pushObject(book);

  }, time);

}));

promise.then(() => {
  console.log('Yoo! Finally!')
})

I need that message (and other actions) to execute finally, after all forEach. But now that message is consolelogged before that forEach get finished. Why?

I know I have to use: RSVP, Promises, EmberPromiseMixin and these stuff but it's a mess!

Would you suggest the code and something beautiful site or book or something to finally learn once for all this stuff?




ember-cli on Windows, VSCode (Visual Studio Code), "EPERM: operation not permitted, mkdir" many times when I save

I'm on Windows 10 x64, VSCode (Visual Studio Code, both Stable and Insiders).

"EPERM: operation not permitted, mkdir" many times when I save. I just save again and the problem disappears. But is very annoying...

Using "handle.exe" this is my situation in my EmberApp folder:

$ handle -a tmp

Nthandle v4.1 - Handle viewer
Copyright (C) 1997-2016 Mark Russinovich
Sysinternals - www.sysinternals.com

svchost.exe        pid: 3892   type: File           520: C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Windows\Notifications\WPNPRMRY.tmp
svchost.exe        pid: 6032   type: File           2A8: C:\Users\Nickname\AppData\Local\Microsoft\Windows\Notifications\WPNPRMRY.tmp
Code.exe           pid: 6872   type: File            D4: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes
Code.exe           pid: 6872   type: File            D4: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes
Code.exe           pid: 6872   type: File           3E0: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes\authors\book
Code.exe           pid: 6872   type: File           3E0: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes\authors\book
Code.exe           pid: 6872   type: File           440: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes\authors
Code.exe           pid: 6872   type: File           440: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes\authors
Code.exe           pid: 6872   type: File           450: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp
Code.exe           pid: 6872   type: File           450: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp
Code.exe           pid: 6872   type: File           470: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes\authors\book\sum
Code.exe           pid: 6872   type: File           470: C:\projects\emberApp\tmp\funnel-output_path-2vNvynVB.tmp\routes\authors\book\sum
Code.exe           pid: 6872   type: File           478: C:\projects\emberApp\tmp\filter-tmp_dest_dir-n4SyE39H.tmp
Code.exe           pid: 6872   type: File           478: C:\projects\emberApp\tmp\filter-tmp_dest_dir-n4SyE39H.tmp
Code.exe           pid: 6872   type: File           478: C:\projects\emberApp\tmp\filter-tmp_dest_dir-n4SyE39H.tmp
Code.exe           pid: 6872   type: File           47C: C:\projects\emberApp\tmp

My VSCode settings are:

{
  "files.exclude": {
    "node_modules": true,
    "typings": true,
    "tmp": true,
    "dist": true,
    "coverage": true
  },
  "files.watcherExclude": {
    "**/tmp/**": true,
    "**/tmp": true,
    "**/node_modules/**": true
  },
  "search.exclude": {
    "tmp": true,
    "vendor": true
  }
}

I tried also everything possible: **/tmp or tmp alone. Everything and I reloaded every time VSCode. Nothing, after the first save the problem.

My jsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "experimentalDecorators": true
  },
  "exclude": ["node_modules", "bower_components", "tmp", "vendor", ".git", "dist"]
}

Also I don't have any extension in VSCode.


Output from ember version --verbose && npm --version && yarn --version:

ember-cli: 2.13.2
http_parser: 2.7.0
node: 7.10.0
v8: 5.5.372.43
uv: 1.11.0
zlib: 1.2.11
ares: 1.10.1-DEV
modules: 51
openssl: 1.0.2k
icu: 58.2
unicode: 9.0
cldr: 30.0.3
tz: 2016j
os: win32 x64
5.0.3
0.24.5

  • VSCode Version: 1.13.1
  • OS Version: Windows 10.1 x64



jeudi 29 juin 2017

Ember Mirage Model : For multiple hasMany and belongsTo

I have a page that has multiple AJAX Calls to the server. Now, I am mocking the data with Mirage for testing purpose. For that, I am using Factories.

I have factories for all the models being used during the page render. All the models have many relationships, few models have hasMany and belongsTo, the other models have hasMany alone.

I came across in the net to use aftercreate hook for these kind of associations.

My doubt is :

Model author.js in mirage has :

author: hasMany('post'),
afterCreate(a, server) {
   server.create('b', {a});
}

Similarly, Model post.js in mirage has :

author: belongsTo(),
aftercreate(b, server) {
   server.create('a', {post});
}

My doubt is, won't it be a recursive calls, after each afterCreate hook, the other model is getting instantiated, and simultaneously calls the other afterCreate and so on?

What is the best way to handle these kinds of relationship issues with mirage?

Thanks in Advance!




ckeditor field gets html codes is not changed

I am supporting an ember site that was build by someone else. The frontend is Emberjs with a Drupal 7 backend.

The site has a user profile where they can enter a bio. The initial bio entry is fine, but if the user edits the profile (changes some other field for example) but does not change the bio text, then it saves something like <p>My bio</p>as the value of the field where the html tags are saved as text.

The component.js for the form has this in it:

bodyChanged(newValue) {
  this.get('profile').set('bio', newValue);
},

Suspecting this is the culprit but not sure what to do to fix.

Thanks




Ember.js 2, Is there a better way of doing it?

I have this code:

new Ember.RSVP.Promise((resolve) => {
    let promise = myList.pushObject(book);
    resolve(promise);
}).then(() => {
    this.send('scrollToBottom', '#myList');
});

Is there a better way of doing it?




Ember not able to enable/disable by validating email

I am trying to validate an email address and accordingly enable or disable the action button. but it's not work. i am very new to emberjs any one please help me here? Here is my Tutorial

html code ( hbs ) :

<div class="jumbotron text-center">
    <h1>Coming Soon</h1>

    <br/><br/>

    <p>Don't miss our launch date, request an invitation now.</p>

    <div class="form-horizontal form-group form-group-lg row">
        <div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-1 col-md-5 col-md-offset-2">
            <input type="email" value=emailAddress class="form-control" placeholder="Please type your e-mail address." autofocus="autofocus"/>
        </div>
        <div class="col-xs-10 col-xs-offset-1 col-sm-offset-0 col-sm-4 col-md-3">
            <button class="btn btn-primary btn-lg btn-block" disabled= >Request invitation</button>
        </div>
    </div>

    <br/><br/>
</div>

controller js :

import Ember from 'ember';

export default Ember.Controller.extend({

    emailAddress:'',
    isValid: Ember.computed.match('emailAddress', /^.+@.+\..+$/),
    isDisabled: Ember.computed.not('isValid'),
    actualEmailAddress: Ember.computed('emailAddress', function() {
        console.log('actualEmailAddress function is called: ', this.get('emailAddress'));
    }),
    emailAddressChanged: Ember.observer('emailAddress', function() {
        console.log('observer is called', this.get('emailAddress'));
    }),
    actions: {

        saveInvitation() {
            alert(`Saving of the following email address is in progress: ${this.get('emailAddress')}`);
            this.set('responseMessage', `Thank you! We've just saved your email address: ${this.get('emailAddress')}`);
            this.set('emailAddress', '');
        }
    }
});

when i enter the valid email, button not enables!! Thanks in advance.

UPDATE:

In browser I am getting this error :

DEPRECATION: Usage of `router` is deprecated, use `_routerMicrolib` instead.




Active links in Ember based on property

In Ember.js the link-to helper automatically sets an active css-class if the the current route matches the supplied routeName.

You could change that behaviour by applying the current-when argument, to set the active class if another route matches the supplied routeName.

But now I need to make the link active if a property is true. The only thing I could think about would be:



Obviously, this does not work, because the current-when argument does only supports strings. So how could I make this work?




Deploying client side JS applications (e.g. Ember, Vue, React) to Azure App Services - via CI

I have a general question about deploying client apps to Azure App Services. This applies to the Ember, Vue, React apps I've recently tried.

Azure allows App Services to be integrated with Github etc and enables a deployment to the App Service triggered by any push to a branch.

This is great but the general assumption by Azure is that deployment consists of syncing the /wwwroot folder with your entire repository. Aside from the additional files synced, 90% of the time the client side frameworks have their own build tooling and expect to run this and publish their contents to a dist folder or similar.

So my question is, What is the best practice to integrate such a repository with an Azure App service?

At the moment I'm looking at one of several approaches:

  1. Create a custom deployment process for Kudu which runs the same build steps as I would locally, clears the wwwroot and takes the contents of the dist folder and puts them in the wwwroot
  2. Ditch the Git integration directly and use TFS build steps to run npm build and xcopy or similar the files to their desired locations.
  3. Build and test locally and create a second git repo mapping to the dist folder and trigger builds from pushes to this :(
  4. Ditch the CI for deployment and just use the integration for testing and FTP the build results :(

None of these approaches seem great, but I'm seeing the same problems every time I try to setup CI on client side libraries and loosing a lot of time to this.

If anyone has any thoughts or better approaches I'm all ears!




mercredi 28 juin 2017

Ember Array Iteration

I'm getting my JSON in my model and rendering it fine on the template, however, I'd like to access this array (items) on my template. The goal here is to dynamically render these menu items in the nav bar.

My handlebars looks like this,


    
        
    


and returns

[object Object] [object Object] [object Object]

Any ideas?

JSON below.

{ "ID": 2, "name": "Main Menu", "slug": "main-menu", "description": "", "count": 4, "items": [ { "id": 11, "order": 1, "parent": 0, "title": "Contact", "url": "http://localhost:8888/contact/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 7, "object": "page", "object_slug": "contact", "type": "post_type", "type_label": "Page" }, { "id": 12, "order": 2, "parent": 0, "title": "About", "url": "http://localhost:8888/about/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 5, "object": "page", "object_slug": "about", "type": "post_type", "type_label": "Page", "children": [ { "id": 21, "order": 3, "parent": 12, "title": "About Us – Sub", "url": "http://localhost:8888/about/about-us-sub/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 9, "object": "page", "object_slug": "about-us-sub", "type": "post_type", "type_label": "Page" } ] }, { "id": 13, "order": 4, "parent": 0, "title": "Home", "url": "http://localhost:8888/home/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 2, "object": "page", "object_slug": "home", "type": "post_type", "type_label": "Page" } ], "meta": { "links": { "collection": "http://localhost:8888/wp-json/wp/v2/menus/", "self": "http://localhost:8888/wp-json/wp/v2/menus/2" } } }




Ember Serialize 'ID'

I'm making an API call in Ember and the API I'm hitting is returning some JSON with 'ID' capitalized, it seems Ember is looking for lowercase 'id.' Everything else should work, so how would I serialize just this one piece of JSON in this instance?

See JSON below.

{ "ID": 2, "name": "Main Menu", "slug": "main-menu", "description": "", "count": 4, "items": [ { "id": 11, "order": 1, "parent": 0, "title": "Contact", "url": "http://localhost:8888/contact/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 7, "object": "page", "object_slug": "contact", "type": "post_type", "type_label": "Page" }, { "id": 12, "order": 2, "parent": 0, "title": "About", "url": "http://localhost:8888/about/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 5, "object": "page", "object_slug": "about", "type": "post_type", "type_label": "Page", "children": [ { "id": 21, "order": 3, "parent": 12, "title": "About Us – Sub", "url": "http://localhost:8888/about/about-us-sub/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 9, "object": "page", "object_slug": "about-us-sub", "type": "post_type", "type_label": "Page" } ] }, { "id": 13, "order": 4, "parent": 0, "title": "Home", "url": "http://localhost:8888/home/", "attr": "", "target": "", "classes": "", "xfn": "", "description": "", "object_id": 2, "object": "page", "object_slug": "home", "type": "post_type", "type_label": "Page" } ], "meta": { "links": { "collection": "http://localhost:8888/wp-json/wp/v2/menus/", "self": "http://localhost:8888/wp-json/wp/v2/menus/2" } } }




VITAL NEED: EmberJS equivalent of jQuery's .ready() function that STAYS ON

Ok. So the reason why I am labeling this as a vital need is because I have written another question like this in the past, and I gave when I was asked to give a specific thing that I was trying to accomplish, and the whole thing became about that, and nothing got solved.

Now I have come to like 5 different things I wanted to accomplish that I would've been able to accomplish with jQuery and .ready() and have ALL the functionality done in a half hour. I have spent 3 days searching Google, reading the official Ember 2.13.0 docs, etc. to no avail.

This HAS to exist, because I simply refuse to believe that I can't put an event listener that will ALWAYS run on the route regardless of transitioning to child routes or clicking things or the fact that it already rendered and doesn't render twice. The only one I've been able to get to work is didRender on the component. Nothing else works.

I tried willTransition on the route. Does not work. I've tried didTransition on the route. Does not work. I've searched Google only to come up with answers on here for Ember 1x.

All I want to do is have something like this:

Ember.$('input,select,textarea').on('change',function() {
    do stuff here
}

That will:

  • Work when the route is entered
  • Still continue to function when a user clicks on sub-routes*
  • Not stop working EVER unless the user exits the actual parent route completely and goes somewhere else
  • Run all the time

What didRender on the component does is that while it's on the opening route (android/setup) .. it will actually work.. until I click a different tab that goes to a different sub route. Then it stops working and upon returning to the original sub route it starts on, it still won't work.

I don't know if it's because the component doesn't get rendered again or what but why it stops working and the event listener dies is beyond me.

If you want to know why I want to do this, I can give you 5 reasons right off the bat, so I would rather the actual EXACT PROGRAMMATIC FUNCTION I'm asking for how to do be explained instead of a single task or goal in terms of functionality because I have needed this SO MANY TIMES and have had to go around my butt to get to my elbow because I can't just .ready it and call it a day.




Is data fetched from server (via findAll/findRecord/query/queryRecord) validated via ember-validations before placing in in the store?

I know creating or updating a record triggers validating, but what about fetching a record.




Could not find module "ember-data/index"

i got an error when running a project in emberJs

Uncaught Error: Could not find module ember-data/index imported from ember-data/initializers/ember-data Uncaught Error: Could not find module ember-cli-app-version/initializer-factory imported from `hqapp/initializers/app-version

please anyone knows




` ember server` throws error, not able to run the app

I am a absolute new with emberjs. I am just following this tutorial to create my first app : http://yoember.com/ but as like tutorials instruction I am running ember server but I thrown with error like :

The Broccoli Plugin: [ConfigReplace] failed with:
Error: Build Canceled: Broccoli Builder ran into an error with Funnel plugin. �
    at new BroccoliBuildError (F:\EmberJS\libraray-app\node_modules\broccoli-builder\lib\broccoli-build-error.js:40:9)
    at F:\EmberJS\libraray-app\node_modules\broccoli-builder\lib\builder.js:168:19
    at tryCatch (F:\EmberJS\libraray-app\node_modules\rsvp\dist\rsvp.js:539:12)
    at invokeCallback (F:\EmberJS\libraray-app\node_modules\rsvp\dist\rsvp.js:554:13)
    at publish (F:\EmberJS\libraray-app\node_modules\rsvp\dist\rsvp.js:522:7)
    at publishRejection (F:\EmberJS\libraray-app\node_modules\rsvp\dist\rsvp.js:457:3)
    at flush (F:\EmberJS\libraray-app\node_modules\rsvp\dist\rsvp.js:2414:5)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

The broccoli plugin was instantiated at:
    at ConfigReplace.Plugin (F:\EmberJS\libraray-app\node_modules\broccoli-plugin\index.js:7:31)
    at new ConfigReplace (F:\EmberJS\libraray-app\node_modules\broccoli-config-replace\index.js:13:10)
    at EmberApp.index (F:\EmberJS\libraray-app\node_modules\ember-cli\lib\broccoli\ember-app.js:686:12)
    at EmberApp.toArray (F:\EmberJS\libraray-app\node_modules\ember-cli\lib\broccoli\ember-app.js:1661:12)
    at EmberApp.toTree (F:\EmberJS\libraray-app\node_modules\ember-cli\lib\broccoli\ember-app.js:1684:38)
    at module.exports (F:\EmberJS\libraray-app\ember-cli-build.js:22:14)
    at Builder.setupBroccoliBuilder (F:\EmberJS\libraray-app\node_modules\ember-cli\lib\models\builder.js:56:19)
    at new Builder (F:\EmberJS\libraray-app\node_modules\ember-cli\lib\models\builder.js:30:10)
    at ServeTask.run (F:\EmberJS\libraray-app\node_modules\ember-cli\lib\tasks\serve.js:24:55)
    at Promise.resolve.then (F:\EmberJS\libraray-app\node_modules\ember-cli\lib\models\command.js:242:46)


Livereload server on http://localhost:49153

How to fix this?




mardi 27 juin 2017

Using Material Design Lite ripple effect in Ember component

I'm trying to add a Material Design Lite button with ripple effect as a component to my Ember project, but it's not working.

I understand that MDL components need to be upgraded (especially if they're being loaded dynamically with Ember), but it looks like there's something I'm missing with the ripple effect?

Any time I click a button with the ripple effect class I get the following error:

ripple.js:73 Uncaught TypeError: Cannot read property 'style' of null
at MaterialRipple.downHandler_ (ripple.js:73)

And on mouseout I get the following error:

ripple.js:128 Uncaught TypeError: Cannot read property 'classList' of null
    at MaterialRipple.<anonymous> (ripple.js:128)

I'm using a mixin to upgrade all MDL elements, as suggested here:

// mixins/mdl-initialize.js
import Ember from 'ember';
export default Ember.Mixin.create( {
    initializeItems: function () {
        componentHandler.upgradeDom();
    }.on('didInsertElement')
});

Here's my component JS:

// components/mdl-button.js
import Ember from 'ember';
import mdlInit from '../mixins/mdl-initialize';
export default Ember.Component.extend(mdlInit, {
    tagName: 'button',
    classNames: ['mdl-button', 'mdl-js-button', 'mdl-button--raised', 'mdl-js-ripple-effect']
});

If it helps, I'm adding my MDL JS files in my ember-cli-build file in the following order:

app.import('vendor/js/mdlComponentHandler.js');
app.import('vendor/js/third_party/rAF.js');
app.import('vendor/js/ripple.js');

Any ideas on what might be happening here?

Also, I know there's already an add-on for MDL in Ember, but I'd like to do this manually, if possible.




How to update an attribute object's attribute before running acceptance test?

First, we setup a scenario like so:

setupProject(server, []);
  visit('/items');

This all works fine. The issue occurs when trying to update attributes of the current user prior to running the test.

Then update the current user with:

let user = server.create('user', 'organization', { enableManage: true });

This is intended to go to the specific user, go to an attribute object on that user called 'organization', and update an attribute of 'organization' called 'enableManage' to true.

Any help is appreciated.




Access to JSON data (Ember)

How can I access JSON data from this?

In app/component/temp.js:

import Ember from 'ember';
let formData = {
    "Name": "David",
    "Phone": "123456789"
}

export default Ember.Component.extend({
    temp: formData;    
});

I tried to write console.log(temp); to see what I get, but I don't see what I want to see. How can I get name or phone? what command should I write to see? Maybe .get?




Crawling Ember-FastBoot application

I have a Ember-FastBoot application that I'm trying to crawl using http://ift.tt/1zByED0

The FastBoot server is working well as I can use my website without javascript.

But when I crawl for example http://localhost:4200/pages/index, it uses the base index.html and not the index served by FastBoot. Like the crawler adds .html to the route which default to base index.html.

Any clues would be appreciated




What Framework/Language for Real Time Updates for Game Stats

I need some help with what framework/language I should use for my app idea that I want to create. I play Star Wars: X-Wing and I stream/record our games in OBS, here's an example:

enter image description here

The site that I use for the overlay that you can see in the image works great, but I thought this would be a fun opportunity to try and create myself, but with a few exceptions. Not all the stores I play at have internet, so I would like this to be a standalone app. My idea was to simply have a localhost website that displayed the ships stats, that I could just window capture in OBS. Then I would have a separate app that could update the stats when the ships take damage and when they blow up. This would also eliminate the cursor that pops up when I update the stats when using the original site.

That's pretty much the idea, but I really have no clue on what I should attempt to create this in. I'm familiar with several languages, i.e Java, JavaScript, jQuery, CSS, Spring, HTML, some Ember, and others. Any suggestions/ideas would be appreciated, thanks.




Generating input fields based on number of data present in database in ember js

I am developing a application for students marks entry in that I want to generate input fields for number of students present in database and save all entry at once. Is there any possible ways for going it in ember and I'm using Rails as backend.




Loading Angular2 app inside Ember JS application

I am having an Angular 2 application and there is a requirement that I have to call my Angular 2 application from the EmberJS application. The case is when EmberJS application loads and on click of a button I want to load my Angular application in the same container do some stuff and then give back the control to EmberJS. Please help me how we can do this. Using Angular 2 CLI I have created a production build of my app, but I am not aware of where to keep angular files in ember directory and how to bootstrap the angular app. Any help is appreciated.




Why Don't I have 'this' context inside of a .then() in my Ember component

I'm fairly new to Ember.

This is the code for my component:

import Ember from 'ember';

export default Ember.Component.extend({
  profiles: Ember.inject.service(),
  tagName: 'td',
  classNames: ['grey'],
  classNameBindings: ['unreadMessages'],
  unreadMessages: null,

onInit: function() {
    const id = this.get('conversation.id');
    return this.get('profiles').getMessages(id)
      .then(function(bool) {
        this.set('unreadMessage', bool);
      });
  }.on('init')
});

This throws:

TypeError: Cannot read property 'set' of undefined

So I can gather that I don't have the this context that I need to call this.set inside of the .then()

I need to assign the result of return this.get('profiles').getMessages(id) to the unreadMessages property in my component. So that I can use it for the classNameBinding.

Here is the method I'm calling from the service

  getMessages(id){
    return this.get('ajax').request('/messages?id=' + id)
    .then((obj) => {
      const unreadMessages = obj.messages.filter((e) => e.read === false);

      if (unreadMessages === []) {
         return false;
      } else {
         return true;
      }
    });
  }

I've only been able to access the boolean value that getMessages returns inside of its .then() and I am not able to call this.set() inside of the .then() I'm looking for a work around. I think I'm close and am struggling to due to my lack of experience with Ember.

getMessages makes a 'GET' request to my back end and filters through the messages to check if there are any that are unread and then returns true or false. The purpose of the classNameBinding is to notify the user of whether they have any unread messages for that thread. This is a very simple email style messaging app that I am building for practice.

Thanks!




How to pass alert trough route.js in ember

I've made a function in order to confirm a mail adress. I would like to show a toaster alert when the user confirm is mail. Howwver, i'm stuck in the route/users/confirmation.js and i dont know how to pass it trough a component from there.

import ApplicationRoute from '../../routes/application';
import Ember from 'ember';
import ENV from "../../config/environment";

export default ApplicationRoute.extend({
  beforeModel(params) {
    const confirmationToken = params.queryParams.confirmation_token;

    // Call backend with confirmation token
    Ember.$.ajax({
      url: ENV.API_HOST + '/users/confirmation?confirmation_token=' + confirmationToken,
      type: 'GET',
      headers: {
        'x-api-key': ENV.APP.api_key
      }
    this.transitionTo('app');

    return {};
  }
});

I've been thinking of passing params trough the transitionTo but it appear to be a little bit unsuited..




Ember.js 2. Lazy fetch in background after rendering the page

I have a simple page "authors" that shows a list of authors.

Each author of course has many books, but in that page (and in the API) I don't show(/include) any book data.

In the authors route I have the default model():

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

and everything is OK.

Now I need something that fetch lazy (in background) some data from others APIs (the books ones).

But I don't want this call blocking my authors page render. So, I have the default and speedy beforeModel(), model() and afterModel() without any fetch (except for authors data).

ONLY after page is rendered I need something (maybe a service?) that calls "api/books?author:1,2,3,4,5..."

In this way I already have the books in my "store" when someone click on an athor (no waiting loader in that book page).

How to do this?




Ember.js 2. Using nested templates is more RAM consuming?

I'm wondering if using nested templates it's very RAM consuming...

Something like this:

Router.map(function() {
  this.route('index', {path: '/'});
  this.route('login');
  this.route('authors', {path: 'authors'}, function() {
    this.route('author', {path: ':author_id'}, function() {
      this.route('book', {path: ':book_id'}, function() {
        this.route('cart', {path: 'cart'});
      });
    });
  });
});

is more RAM heavy than this?

Router.map(function() {
  this.route('index', {path: '/'});
  this.route('login');
  this.route('authors', {path: '/authors'});
  this.route('author', {path: '/author/:author_id'});
  this.route('book', {path: '/book/:book_id'});
  this.route('cart', {path: '/cart/:cart_id'});
});




lundi 26 juin 2017

ember server out of memory

Lastly, I use ember to develop. But I found it strange that when I installs packages like the following order: npm install and then bower install, it caused the out of memory exception; and when I exchange the order, it works well. The exception is as follows:

WARNING: Node v8.1.2 has currently not been tested against Ember CLI and may result in unexpected behaviour.

<--- Last few GCs --->

[5015:0x102805200]    74556 ms: Mark-sweep 1404.9 (1464.9) -> 1404.8 (1439.9) MB, 2781.4 / 0.0 ms  (+ 0.0 ms in 0 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 2781 ms) last resort
[5015:0x102805200]    77514 ms: Mark-sweep 1404.8 (1439.9) -> 1404.8 (1439.9) MB, 2957.7 / 0.0 ms  last resort


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x10d601fa9891 <JS Object>
    3: keysForTree [/Users/gpc/Documents/codes/gitlab/sixtant-fornt/sixtant/node_modules/.0.3.1@broccoli-kitchen-sink-helpers/index.js:36] [bytecode=0x15fbb22b08a9 offset=63](this=0x2a2411a8b051 <JS Global Object>,fullPath=0x1e708a1f0629 <String[860]: /Users/gpc/Documents/codes/gitlab/sixtant-fornt/sixtant/node_modules/.6.0.0@broccoli-babel-transpiler/node_modules/babel-core/node_modules/babel-...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]
 2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
 3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
 4: v8::internal::Factory::NewFixedArray(int, v8::internal::PretenureFlag) [/usr/local/bin/node]
 5: v8::internal::Factory::NewScopeInfo(int) [/usr/local/bin/node]
 6: v8::internal::ScopeInfo::Create(v8::internal::Isolate*, v8::internal::Zone*, v8::internal::Scope*, v8::internal::MaybeHandle<v8::internal::ScopeInfo>) [/usr/local/bin/node]
 7: v8::internal::Scope::AllocateScopeInfosRecursively(v8::internal::Isolate*, v8::internal::MaybeHandle<v8::internal::ScopeInfo>) [/usr/local/bin/node]
 8: v8::internal::DeclarationScope::AllocateVariables(v8::internal::ParseInfo*, v8::internal::AnalyzeMode) [/usr/local/bin/node]
 9: v8::internal::DeclarationScope::Analyze(v8::internal::ParseInfo*, v8::internal::AnalyzeMode) [/usr/local/bin/node]
10: v8::internal::Compiler::Analyze(v8::internal::ParseInfo*, v8::internal::ThreadedList<v8::internal::ThreadedListZoneEntry<v8::internal::FunctionLiteral*> >*) [/usr/local/bin/node]
11: v8::internal::(anonymous namespace)::GetOptimizedCode(v8::internal::Handle<v8::internal::JSFunction>, v8::internal::Compiler::ConcurrencyMode, v8::internal::BailoutId, v8::internal::JavaScriptFrame*) [/usr/local/bin/node]
12: v8::internal::Compiler::CompileOptimized(v8::internal::Handle<v8::internal::JSFunction>, v8::internal::Compiler::ConcurrencyMode) [/usr/local/bin/node]
13: v8::internal::Runtime_CompileOptimized_Concurrent(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/bin/node]
14: 0x253ed080437d
[1]    5015 abort      ember s

And the node version is v8.1.2, npm version is 5.0.3.

By the way, when the node version is v5.5.0, the exception is as follows: enter image description here

So why? Is bower and npm independent? Why the OOM happens?




emberJS opening a new webpage from different domain

All,

I am new to emberJS and I am trying to open a new page like 'www.google.com' from one of my page where I have my link specified in my HBS template like below.

Google

I tried to insert the helper inside the tag also, and wrote an action method in the controller, yet it didn't work. Not sure. Please help. Thanks.

Regards,

PK




error 'moment' is not defined no-undef in ember.js

I'm creating an application, a clock with timezone, it happens that it gives this error and I can not fix it, I'm also an initiator and I do not have much experience, the home page appears where the chosen clock is, but the page where the time zone would be It's blank, I'm waiting for help, thank you!

  • ember-cli: 2.13.1
  • node: 6.0.0
  • os: linux x64

`Could not start watchman Visit http://ift.tt/2huy34z for more info.
Livereload server on http://localhost:49153 'instrument' is imported from external module 'ember-data/-debug' but never used

app/controllers/clock.js
14:36  error  'moment' is not defined  no-undef
18:27  error  'moment' is not defined  no-undef
25:15  error  'moment' is not defined  no-undef

✖ 3 problems (3 errors, 0 warnings)


app/controllers/timezones.js
7:23  error  'moment' is not defined  no-undef
9:19  error  'moment' is not defined  no-undef
10:21  error  'moment' is not defined  no-undef

✖ 3 problems (3 errors, 0 warnings)


Build successful (4919ms) – Serving on http://localhost:4200/



Slowest Nodes (totalTime => 5% )              | Total (avg)         
----------------------------------------------+---------------------
Babel (17)                                    | 1460ms (85 ms)      
Rollup (1)                                    | 1214ms              
EslintValidationFilter (2)                    | 835ms (417 ms)      
Concat (8)                                    | 585ms (73 ms)       
TreeMerger (allTrees) (1)                     | 312ms`               

app/controllers/timezones.js

import Ember from 'ember';

export default Ember.Controller.extend({
/* create array of timezones with name & offset */
init: function() {
    var timezones = [];
    for (var i in moment.tz._zones) {
      timezones.push({
        name: moment.tz._zones[i].name,
        offset: moment.tz._zones[i].offsets[0]
      });
    }
    this.set('timezones', timezones);
    this._super();
  },
  selectedTimezone: null,
  actions: {
    /* save a timezone record to our offline datastore */
    add: function() {
      var timezone = this.store.createRecord('timezone', {
        name: this.get('selectedTimezone').name,
        offset: this.get('selectedTimezone').offset
      });
      timezone.save();
    },        
    /* delete a timezone record from our offline datastore */
    remove: function(timezone) {
      timezone.destroyRecord();
    }
  }
});

app/controllers/clock.js

import Ember from 'ember';

export default Ember.Controller.extend({
init: function() {
    // Update the time.
    this.updateTime();
},

updateTime: function() {
    var _this = this;

    // Update the time every second.
    Ember.run.later(function() {
        _this.set('localTime', moment().format('h:mm:ss a'));

        _this.get('model').forEach(function(model) {
            model.set('time',
                      moment().tz(model.get('name')).format('h:mm:ss 
a'));
        });

        _this.updateTime();
    }, 1000);
},

localTime: moment().format('h:mm:ss a')
});

app/model/timezone.js

import DS from 'ember-data';

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

app/routes/clock.js

import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
    return this.get('store').findAll('timezone');
}
});

app/routes/timezones.js

import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
    return this.get('store').findAll('timezone');
}
});

If you need any more files just talk




Ember Js, Ember-Highcharts not updating changes to chartData

I'm using Ember-CLI and ember-highcharts to plot some data. The library works fine with test data but fails when I try to pull data from an API, so I believe that there might be some kind of race-condition going on. However, I can print the series from within my component just fine, so I'm uncertain why the highcharts component isn't listening for changes to chartData and updating accordingly.

Here's my assignment statement:

this.get('chartData')[0].data.setObjects(barItems);

And my charData element:

chartData: [{
    name: 'Temperature',
    type: 'column',
    color: '#8fb1e8',
    data: []
  },
  {
    name: 'Humidity %',
    type: 'line',
    color: '#393a3d',
    data: []
  }],

The template this is all being used in:

<p id="res"></p>
<div class="graph">
  
</div>


The chart does populate with data after navigating away, and then back to the page.

Any thoughts as to how to fix this or what I might be doing wrong?




Modifying a crossdomain XML policy to accept null origin headers

I am currently dealing with an error that reads

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

The request is working fine on my server, but breaks on my client. I recently found this file, public/crossdomain.xml

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://ift.tt/1d1B8yI">
<cross-domain-policy>
  <!-- Read this: http://ift.tt/18sUytt -->

  <!-- Most restrictive policy: -->
  <!-- <site-control permitted-cross-domain-policies="none"/> -->

  <!-- Least restrictive policy: -->

  <site-control permitted-cross-domain-policies="all"/>
  <allow-access-from domain="*" to-ports="*" secure="false"/>
  <allow-http-request-headers-from domain="*" headers="*" secure="false"/>

</cross-domain-policy>

While this looks like the fix I have been seeking, I am still being thrown the same error. There are no issues like this server side, and my client now largely matches the configuration of my server. Why would this policy fail to resolve the error? Do I need to configure this policy further to accept the required headers?




How can I get Ember Route variables in Handlebars

I've noticed something interesting today.

If I create a variable in my Controller

export default Ember.Controller.extend({
   controllerFoo: "Cut"
});

And I create a similar variable in my Route

export default Ember.Controller.extend({
    routeFoo: "Copy"
});

that when I print it in the .hbs:

controllerFoo:
<hr>
routeFoo: 

only the controllerFoo will display. I previously though Route and Controller variables could be used interchangeably. If I wanted to use a route variable, how could I do that? Or maybe is it bad practice?




EmberJS - How not to conflict with actions and events in components

I think there is a an issue between template actions and events in components.

As far as I understand all action clicks will be first executed and bubbled. Finally events in components will be also executed. There are like two parallel stacks executed one after the other.

If you have something like this in the template of a component:

Hello <button onclick=>Click me</button>

and this in the corresponding javascript file:

click: function() {
   alert('second message');
}

You are not sure that the second message will be displayed. If event.stopPropagation() is called in the stack of action (not necessary inside the action 'clickMe'), the second message won't be shown.

Here is a twiddle: http://ift.tt/2tcQdgw

Is there a solution to bypass this problem?




Not able to import mapbox-gl npm package and cordova-plugin-mapbox

How to import mapbox-gl npm package in cordova application?

const mapboxgl1 = require('mapbox-gl/dist/mapbox-gl.js');

mapboxgl1.accessToken = 'pk.eyJ1IjoibGF2by1jYWN0aW1lZGlhIiwiYSI6ImNqNGU3bjhsZzBrbHoycW1rZWxod290ZHYifQ.xof4oeDjbexECuTyqdkewQ';
  const map = new mapboxgl1.Map({
  container: 'map-test',
  style: 'mapbox://styles/mapbox/streets-v10'
});

This is giving an error as -

Uncaught Error: Could not find module mapbox-gl/dist/mapbox-gl.js imported from (require)




Communication between components in Ember

I have a template with two components, a file upload component, and a progress bar to show the upload progress.




And am using ember-uploader. I'm trying to set the progress of the progress bar like so:

uploader.on('progress', e => {
    // send progress to other component
});

I've read that you should use actions to communicate between components, but I only have access to that progress value within the filesDidChange function in the upload component, so I don't think I can send it in an action. What is the best way to send this progress value into the progress bar component?




Ember cli pagination not changing the display content

I am using ember cli pagination for local store in my ember app. i have successfully created pagination area with proper page number but the display content is not changing with the page number. here is my code---

in my hbs--



 






in controllers--->

queryParams: ["page", "perPage"],
page: 1,
perPage: 3,
pagedContent: pagedArray('content', {
page: Ember.computed.alias("parent.page"),
perPage: Ember.computed.alias("parent.perPage"),
}),
totalPages: Ember.computed.oneWay("pagedContent.totalPages"),

how to change the display data with the page number?




Adding locale in url without changing link-to helpers

Is there any way to avoid changing all link-to helpers, all transitionTo and transitionToRoute methods when wrapping all routes in parent lang route.

@route 'lang', path: ':lang', ->
  @route 'index', path: '/'
  @route 'my-route'
  @route 'my-route-1'

  @route 'my-route-3', path: '/', ->
    @route 'my-subroute'
    @route 'my-subroute-1'




Append query parameters after queryParam update in Ember.js

I defined the queryParams in the controller and I need to add additional query parameters which is not used inside the controller and can be anything. It's an analytics thing. Ember deletes that additional parameter after it updates the URL.

Example:

In the Controller:

queryParams: ['fin', 'ftw'],
fin: null,
ftw: null,

url:

localhost:3000?fin=111&ftw=121&anatylicsvalue=1

when I change the value of fin or ftw, anatylicsvalue is removed. I need the app to retain that bit of string.

What is the best way of doing this?




What is the correct way to inject Emberdata in an Ember integration test

I have a component that expects a model property that is an ember data object (originally created from the route model)

I've tried this in the integration test but the store is undefined

test('it renders', function (assert) {
  this.inject.service('store')

  let model = this.get('store').createRecord('post');

  this.set('model', model);

  this.render(hbs``);

  assert.equal(this.$().text().trim(), 'Post your thoughts');

  // Template block usage:
  this.render(hbs`
    
      template block text
    
  `);

  // assert.equal(this.$().text().trim(), 'template block text');
});




dimanche 25 juin 2017

Service not injected into component's integration test

I have a service Foo (e.g. app/services/foo.js):

import Ember from 'ember';

const FooService = Ember.Service.extend({
  myMethod() { ... }
});

export default FooService;

which I initialize in app's initializers (e.g. app/initializers/foo.js), such as:

const initialize = function initialize(app) {
  app.inject('component', 'foo', 'service:foo');
}

const FooInitializer = {
  name: 'foo',
  initialize: initialize
}

export {initialize}
export default FooInitializer;

And then I have a component (e.g. app/components/my-component.js), in which I use this service (I do not inject it manually here because it's already injected into every component in initializers):

import Ember from 'ember'

const MyComponent = Ember.Component.extend({

  actions:
    doSomething() { this.get('foo').myMethod(); }

});

export default MyComponent;

I created integration test for this component:

import { test, moduleForComponent } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import sinon from 'sinon';

const fooStub = Ember.Service.extend({
  myMethod() {
    return true;
  }
});

moduleForComponent('my-component', 'Integration | Component | my-component', {
  integration: true,

  beforeEach() {
    this.register('service:foo', fooStub);
    // Calling inject puts the service instance in the context of the test,
    // making it accessible as "foo" within each test
    this.inject.service('foo', { as: 'foo' });
  }
});

test('it does something', function (assert) {
  this.render(hbs``);
  const spy = sinon.spy(this.get('foo'), 'myMethod');

  const $someElement = this.$().find('.some-element-within-my-component');
  // This element triggers `doSomething` action inside the component
  $someElement.click();

  assert.ok(spy.calledOnce, "myMethod was called within foo service");
});

When running this test, it throws an error:

TypeError: Cannot read property 'myMethod' of undefined

which means the service is not being injected, even thought I injected it in the test manually as a stub.

I read a couple of discussions, but none was really helpful until I bumped into this one which hinted me that Ember might not inject services into tests if they are initialized using initializers and not injected manually into the component that is being tested.

So I tried to inject the service manually into the component and the test worked. This is, however, only partial solution since it completely destroys the purpose of initializers if I have to inject services into my components (and there's a lot of them) manually just to make the tests work.

Have any of you experienced this and if so, is there something I'm doing wrong or is there a workaround to make this work without manually injecting my services into every component that I have? Maybe this will end up filing a bug in Ember, but I first wanted to try stackoverflow to see if there's another solution.




HTML code is a not in a correct format in emebr js

Im try to code this html code for the ember js format, but i cant do it, how can i fix it?

<h5>Thursday. May. 05. 2017</h5>
<div class="progress-bar position" data-percent="48" data-duration="1000" data-color="#6a6f77,#5fb756"><script>$(".progress-bar").loading()</script></div>




Making a cross-domain request in ember.js using an adapter

I am trying to access a third party API via the OAUTH protocol in an application using Ember on my front end and rails on my back end. As it stands, I am able to begin the request phase on my server, but my client is unable to redirect to the authorization page, sending an error reading:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

The problem here is that the Origin of the request being returned from coinbase is null, so my client rejects it. I need to find some way to bypass this or handle this error. It is worth noting that I am doing my testing on chrome, with my client and server at two different localhost ports. I also have cors configured on my back end and the request is firing with no issue. How can I go about resolving this error in ember?




Where do I apply an 'Access-Control-Allow-Origin' header in a rails application

I am trying to link to a third party authentication page via omniauth in a rails app using ember.js as a client. I am able to redirect my server to the proper url, but I cannot send my client there (causing my server to hang indefinitely in the request phase). My problem is that I need to set the Access-Control-Allow-Origin header somewhere in my application, but I am not sure where. I currently have this (non-working) setup in my application_controller.rb:

class ApplicationController < ActionController::API
  # Force to wants JSON for API
  before_action :api_request_settings, :cors_preflight_check

  after_action :cors_set_access_control_headers

  def cors_preflight_check
    p 'hits cors preflight check'
    if request.method == :options
      headers['Access-Control-Allow-Origin'] = '*'
      headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
      headers['Access-Control-Allow-Headers'] = '*'
      headers['Access-Control-Request-Method'] = '*'
      headers['Access-Control-Max-Age'] = '1728000'
      render :text => '', :content_type => 'text/plain'
    end
  end

  def api_request_settings
    p request.headers
    request.format = :json
  end

  def cors_set_access_control_headers
    p 'hits cors acces set control headers'
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Max-Age'] = "1728000"
  end

What am I doing wrong and where should I put these headers to send my client to the landing page?




Ember.js 2. Nested routes but non-nested templates

First of all, thank you all for your efforts in this forum.

I have this situation:

  • mysite.com/authors (list of authors)
  • mysite.com/author/1 (author 1)
  • mysite.com/book/1 (book 1 of author 1)
  • mysite.com/cart/1 (cart page of book 1 of author 1)

I need an url like this:

http://ift.tt/2u3sLzf

but I don't want nested template (every page is different and I don't want same info in many page).

Is there a way to have that URL?




Could not find module `ember-qunit` after adding cropper js

Hi I am trying to run tests in my Ember application.

It works fine until I add cropperjs to my ember-cli-build.js file. Once i add this line

app.import('bower_components/cropperjs/dist/cropper.js');

It gives Could not find module ember-qunit .

Link to cropper js

cropperjs link




samedi 24 juin 2017

Redirecting an Ember application to an omniauth authorize URL

I need to send the user of my application to the coinbase authorization page. My application uses an Ember.js front end and is connected to a Ruby on Rails back end. I have been able to execute this functionality using rails views before, but I am having trouble doing so using an external client. Client side, I have constructed an adapter which runs the requisite server side functions to generate an authorize. When I click the button which fires this adapter and I am returned a correct redirect url, but my app throws a 404. I am fairly certain I need to use the method window.location.replace(redirect_url) to launch this redirect, but I cannot seem to figure out the syntax for properly returning the value and plugging it into this call.

the method called in the route:

donate (params) {
      return this.get('store').findAll('account', {reload:true})
        .then((accounts) => {
          return accounts.findBy('editable', true);
        })
        .then((account) => {
          params.patronId = account.id;
          const adapter = this.store.adapterFor('account');
          // adapter.donate(params);
          return adapter.recieve_donation(params);
        })
        // .then(() => this.transitionTo('accounts.search-accounts'))
        .then(() => {
          this.get('flashMessages')
          .success('We have successfully sent your donation');
        });
    },

the adapter method:

recieve_donation(params){
    console.log(params);
    const api = this.get('host');
    const url = `${api}/auth/coinbase`;
    // , {data: params}
    return this.ajax(url, 'GET');
  },

I also am not sure if the problem is on my server side; my intuition says the fact that I am successfully returning a url leads me to believe it is not, but I can't be sure.

How can I redirect my ember app to the returned redirect URL?




how can I load my urls and page without the whole browser loading in laravel

pls im looking for a new way to load my urls and pages in laravel, i want the url to change and the webpage to change but i do not want the whole browser to load, some examples are like soundcloud.com, wakanow.com, http://ift.tt/2bk8aBx, even linkedin has the same feature, where the pages load like desktop apps and they have nice preolading animations that works with the page, i believe this will be helpful to other people too :)




vendredi 23 juin 2017

Ember multiple polymorphic association same model

I have the following model in rails. what will be it's equivalent in Ember?

User.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Group.rb
  has_many :posted_posts, class_name: 'Post', as: :posted
  has_many :received_posts, class_name: 'Post', as: :received

Post.rb
  belongs_to :posted, polymorphic: true
  belongs_to :received, polymorphic: true




Ember.js Tutorial - Services & Utility Functions

I'm reading through the Ember Tutorial and am questioning the following:

  • The authors say that the advantage of using a service and utility function separately is that a service is a singleton so it can hold state, and in essence, doesn't need to reload maps because it will store them.
  • Why do they emphasize the fact that a service being a singleton is so great, when the utility function is in essence a singleton too.
  • The singleton is being called as an object that's being instantiated so it will hold state.

My question is, why don't we just put that utility function code inside the google maps service that we're creating in the tutorial? Is separating the ember implementation code from the google maps javascript API code that much of an advantage?




Ember.Object that does not implement Ember.Copyable

I have an acutal quite simple situation:
A route to add a new item. In the corresponding controller I pre define a mockup model of my new item:

item: Ember.Object.create({
                date: moment(),
                amountTotal: '',
                netto: '',
                //...more properties
}),

This needs to be an Ember-Object, not a plain js-Object, because otherwise other things would break.

When I try to safe that newly created item:

actions: {

    addItem: function() {
        let expense = this.store.createRecord('expense', this.get('item'));
    },
    //....
}

I get the error

Assertion Failed: Cannot clone an Ember.Object that does not implement Ember.Copyable

So my Question is:
How can I create an Object that implements Ember.Copyable?
Or is there any way around this?

Yes, I've read the two other questions about that. The first gives a soulution where I would initially create a record in the store. This has the usual downsides to it (already populating in lists, ..).

I've also tried all ways I could think of to get around that like

item: Ember.Copyable.create({...})
// or 
let newItem = Ember.copy(this.get('item'));
let expense = this.store.createRecord('expense', newItem);
// and many more




why is ds.store.query returning everything

In Ember.js,

I am trying to perform a query of all posts with a matching key. Btw, this is in Firebase. My data looks something like this:

post example

I'm trying to query specific posts based off the key property (multiple posts may have the same key property value).

So here is my model(params) in my route

route/stuff.js

export default Ember.Route.extend({
    model(params) {
        console.log(params.site_id);
        return this.store.query('post', { "key": params.site_id} );
    }
})

And here is me trying to display my posts in my template:

template/stuff.hbs


<div class="panel panel-default">
    <div class="panel-heading">
        Post Title: 
    </div>
    <div class="panel-body">
        <div class="col-lg-6 col-md-6 col-sm-6 margin-top-1em">
            <ul class="li-type-none">
                <li>Post Author: </li>
            </ul>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-6">
            <ul class="nav nav-pills margin-top-small">
                Edit
                <button class="btn btn-danger btn-s" >Remove Post</button>
            </ul>
        </div>
    </div>
</div>





And, the good news is that my posts will display. The bad news is that ALL posts display. Even ones that don't have the right key. Why is my query returning all the posts instead of only the ones that have the right key attribute?

Here is some extra information that maybe helpful:

model/post.js

import DS from 'ember-data';

export default DS.Model.extend({
  author: DS.attr('string'),
  title: DS.attr('string'),
  content: DS.attr('string'),
  key: DS.attr('string'),
  date: DS.attr('date', { defaultValue() { return new Date(); }}),
  site: DS.belongsTo('site'),
  isLocked: DS.attr('boolean'),
  lockedContent: DS.attr('string'),
  metaData: DS.attr('string')
});

Also, here is how it looks in the URL (note that the key attribute is passed into the url)

http://localhost:4200/posts/-D2312jsj23u1828u42/stuff

Thank you!




switching between the page in not working in pagination

I have used ember-cli-pagination for adding pagination in my ember app. Pagination is added to the ui but in number it is changing the page number but in ui it is not displayed.

in my controllers i have added:

 queryParams: ["page", "perPage"],
  page: 1,
  perPage: 3,
  pagedContent: pagedArray('content', {
    page: Ember.computed.alias("parent.page"),
    perPage: Ember.computed.alias("parent.perPage"),
  }),
  totalPages: Ember.computed.oneWay("pagedContent.totalPages"),

in router i have added>>

model:function(){
    return this.store.findAll('rule');   
  },

how to switch between the pages>>>




How do I properly display properties of deeply nested relationships in templates when using Ember Data and JSON API's include feature?

I've been attempting to take advantage of the { include: 'level1,level1.level2,level1.level2.level3' } option with Ember Data's find and query methods to load data in my route's model hooks. but as I understand it the route only pauses on the first level of data's Promise and all hasMany and belongsTo relationships have a chance to reach template code unfulfilled, and the template won't update once properties of those relationships do fulfilled.

I have a router like:

Router.map(function() {
  this.route('users', { path: '/' }, function() {
    this.route('user', { path: '/:user_id' });
  });
});

a User route:

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('user', params.user_id, { include: 'gifts,gifts.given_by,gifts.occasion.arranged_by' });
  }
});

a User model:

export default DS.Model.extend({
  name: DS.attr('string'),
  gifts: DS.hasMany('gift', { inverse: 'givenTo' })
});

a Gift model:

export default DS.Model.extend({
  name: DS.attr('string'),
  givenBy: DS.belongsTo('user'),
  givenTo: DS.belongsTo('user'),
  occasion: DS.belongsTo('occasion')
});

an Occasion model:

export default DS.Model.extend({
  name: DS.attr('string'),
  location: DS.belongsTo('location'),
  giftsGiven: DS.hasMany('gift')
});

a Location model:

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

So for example, I have many levels of relationships I'm loading and wanting to use in my User template as part of the User's profile. In my User template I want to list in a table the Gifts the user has been given and related information like.

<h1>'s Gifts
<thead>
  <tr>
    <th>Gift Name</th>
    <th>Given By</th>
    <th>Occasion</th>
    <th>Where</th>
  </tr>
</thead>
<tbody>
  
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  
</tbody>

Let's say 10 gifts were returned from the database so the table is 10 rows long. What I'd expect to see is a fully populated table, what I see instead, consistent between page refreshes is the following:

╔═══════════╦══════════╦══════════╦══════════╗
║ Gift Name ║ Given By ║ Occasion ║  Where   ║
╠═══════════╬══════════╬══════════╬══════════╣
║ Present 1 ║ Friend 1 ║ Birthday ║ The Park ║
║ Present 1 ║ Friend 1 ║ Birthday ║ The Park ║
║ Present 1 ║ Friend 1 ║ Birthday ║ The Park ║
║ Present 1 ║ Friend 1 ║ Birthday ║ The Park ║
║           ║ Friend 1 ║          ║ The Park ║
║           ║ Friend 1 ║ Birthday ║          ║
║           ║ Friend 1 ║ Birthday ║          ║
║           ║ Friend 1 ║ Birthday ║ The Park ║
║ Present 1 ║ Friend 1 ║          ║ The Park ║
║ Present 1 ║ Friend 1 ║ Birthday ║ The Park ║
╚═══════════╩══════════╩══════════╩══════════╝

I use the same data repeatedly on purpose to illustrate what I'm seeing. Even if a model's property renders correctly in some table cells, it won't in others, and seems to randomly but 100% consistently between page refreshes populate and not populate the same table cells. Which cells are populated and not are also different between User models in this example.

Hopefully this example makes sense, I know I could flatten data but in my actual app I can't and being able to include deeply nested relationships like this and have them show in templates correctly would be great.

It seems to mostly work, but fail for some reason that I imagine have to do with Promises. If I look in Ember inspector, all of the data is there, as evident by showing in most of the cells anyway.

What am I doing wrong and what can I do better if I want to take advantage of the { include: '' } feature of Ember Data's JSON API adapter?




How to display collapse when checkbox clicked in Ember bootstrap?

I'm fairly new to Ember and I'm trying to implement a Collapse method when I have clicked on a checkbox as a part of my form. This checkbox is inside a collapsed section part of a button group I have in my form.

Template.hbs

      
        
          
        
        <div>
          
            
            
          
        </div>
      

Component.js

collapsed: true,
actions: {
toggle() {
  let toggleValue = !get(this, 'collapsed');
  set(this, 'collapsed', toggleValue);
  }
}

When running ember serve and I go to my form if I click on the checkbox an error pops up in Ember Inspector:

Assertion Failed: You cannot use the form element's default onChange action for form elements if not using a model or setting the value directly on a form element. You must add your own onChange action to the form element in this case! Error

If I change onClick to onChange then fields aren't displayed when I click the checkbox, but I still get the error. What would be the best way to go about trying to fix this problem?




Validate optional email with ember-cp-validations

I would like users to optionally insert an email using ember-cp-validations:

const Validations = buildValidations({
  managerEmail: {
    validators: [
      validator('presence', null), // means it can be optional
      validator('format', { type: 'email' })
    ]
  }
});

But it still requires an email and won't accept an empty field. How can I make it optional?




Calling a function on a component from the controller

I like your opinion on this pattern. I wanted to be able to call focus function on a component from my controller, the way I implemented it was a reference to of itself by an action defined on the controller then call the method on it. It works fine just wondering if some sort anti-pattern I should stay away from?



<button </button>

 // x-input.js
import Ember from 'ember';

export default Ember.Component.extend({

  init() {
    this._super();
    if (!Ember.isNone(this.get('bindingAction')) {
     this.get('bindingAction')(this)
    }   
  }

  focus() {
    // focus on component.
  }

});


// controller.js
import Ember from 'ember';

export default Ember.Controller.extend({

actions: {

    bindInput(input) {
       this.set('input', input);    
    }

    focusOnInput() {
       this.get('input').focus();       
    }

}
});




In Ember, AJAX callback should it be wrapped in Ember run loop?

The below statement is from ember guides,

The most common case for using the run loop is integrating with a non-Ember API that includes some sort of asynchronous callback. For example:

DOM update and event callbacks
setTimeout and setInterval callbacks
postMessage and messageChannel event handlers
AJAX callbacks
Websocket callbacks

I usually will do for AJAX request,

Ember.$.ajax(
{
 type: "POST",
 url:"someurl",
 contentType: "application/json",
 success: function(data) {
 //Should I wrap this success callback code in Run loop. or is it safe to leave
 //Here I will set properties to display, I might call sendAction/send to communicate with parent.
 }
})

I haven't faced any problem with that but sometime rendering is taking too much time after I change data in callback ?. does any one face that issue ?

Should I use ember-ajax addon to wrap success callback in Ember run loop?.

PS: Below is from ember guides, you should wrap any non-Ember async callbacks in Ember.run. If you don't, Ember will try to approximate a beginning and end for you. Relying on autoruns is not a rigorous or efficient way to use the run loop.




Could not find module `ember-resolver` imported from `AppName/resolver Ember tests

I am trying to run Ember tests and it gives this error saying Could not find module ember-resolver imported from `AppName/resolver.

I am not sure what is causing it. I am using Ember-cli-2.12.1. Any help would be appreciated. Thanks




jeudi 22 juin 2017

Ember.JS jquery circular progrees bar not display

Im add My Ember Application for j query circular progress bar, Its not a correctly display , image 01 Im use this example example

Look image 01, display like this, normal html , its is working fine, )

This is my Coding part application.hbs


  <div class="navbar-header">
    
    <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span>
  </div>
  
    
      Home
      Manage rooms
      Channel manger
      Cash reports
      Add expenses
      Settings
      Helps
    
  


    <div class="progress-bar position" data-percent="60" data-duration="1000" data-color="#ccc,yellow"></div>


app.css

.progress-bar {
  position: relative;
  height: 200px;
  width: 200px;
}

.progress-bar div {
  position: absolute;
  height: 200px;
  width: 200px;
  border-radius: 50%;
}

.progress-bar div span {
  position: absolute;
  font-family: Arial;
  font-size: 25px;
  line-height: 175px;
  height: 175px;
  width: 175px;
  left: 12.5px;
  top: 12.5px;
  text-align: center;
  border-radius: 50%;
  background-color: white;
}

.progress-bar .background { background-color: #b3cef6; }

.progress-bar .rotate {
  clip: rect(0 100px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 100px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 100px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}
 @keyframes
toggle {  0% {
 opacity: 0;
}
 100% {
 opacity: 1;
}
}

and im added vendor folder to following files-

jQuery-plugin-progressbar.js
jquery-2.1.4.min.js

after add ember-cli-build.js to

app.import('vendor/jQuery-plugin-progressbar.js')

app.import('vendor/Progress.js')

, please help me to fix it,




Action Cables, nested JSON attributes and JSONAPI

I have a fairly specific problem that I was hoping one of you really intelligent folk might know a solution for (or even a workaround at this stage)

Specifically, I'm dealing with action cables, nested JSON, and the JSONAPI.

I have an asset model, which has some attributes like name, desc etc. but it also has an attribute called state which is a complex nested JSON object.

// app/models/asset.js
export default DS.Model.extend({
    // Attributes
    name: DS.attr('string'),
    desc: DS.attr('string'),
    state: DS.attr(),
    lastSeen: DS.attr('date'),
});

When anything on the asset changes in the backend, it is pushed down the cable to Ember, where it does a pushPayload(data), the payload looks like this;

{
    "data": {
        "id": "5",
        "type": "assets",
        "attributes": {
            "asset_id": "962ABC",
            "name": "962 ABC",
            "desc": "Test Vehicle",
            "activation_status": "active",
            "state": {
                "avl": {
                    "longitude": 152.9475426,
                    "reported_at": "2017-06-22T21:59:52Z"
                },
                "dfm": {
                    "in_alarm": false,
                    "reported_at": "2017-06-21T05:46:57Z",
                    "sensitivity": "normal",
                    "voice_prompt": false,
                    "driver_detected": true,
                },
                "tpms": {
                    "system_desc": "Doran 360MTR",
                    "system_type": "doran360mtr"
                }
            },
            "last_seen": "2017-06-22T21:59:54.000Z"
        },
        "relationships": {
            "company": {
                "data": {
                    "id": "1",
                    "type": "companies"
                }
            },
            "events": {
                "links": {
                    "related": "/events/?asset_id=5"
                }
            },
            "messages": {
                "links": {
                    "related": "/messages/?asset_id=5"
                }
            }
        }
    }
}

This all works fine and dandy, updates to the asset & state are displayed as they happen thanks to the cable, and state is read only so I don't have to worry about saving anything. HOWEVER, I have noticed that when any single attribute on state changes in the backend, the entire asset is pushed down from the backend (this should be fine), and then this fires the observer for state and also all observers for state descendants - whereas I need it to only fire the observer for the state attribute that changed.

I have tried a number of things and each seemed to either not work at all, or still continue to update state in a way that fired off all state observers.

What I have tried;

  1. ember-model-data-fragments (while it should work, I think the way that the action cable pushes the data must subvert this?)
  2. embedded records (requires an ID for state, not currently compatible with JSONAPI)
  3. raw json transform (making the json into ember objects, didn't seem to help)

Can anyone suggest a strategy or solution for me to try? I've spent nearly 2 days on this problem.. I would even settle for just splitting it up between avl/tpms/dfm, as long as when an attribute in one of those sections is changed, it doesn't notify properties from the other 2 sections.

Thanks




ember.js: Acceptance testing with an ajax request

I'm writing an acceptance test where a user fills in a form and an ajax request is made to a third party resource. I'm mocking the request with Ember CLI Mirage.

I'm writing a basic working example that I'll refactor after my tests pass. I know I need to abstract out my request into a service or utility but I don't like refactoring my code without a working test around it.

My code seems to work however, when I return a result that changes some content in the template, I can't get the test to pass.

It might be important to note: The third party API I am mocking out is not restful.

Here's the mirage config:

export default function() {
  this.post('/LogonAction', () => {
    return {foo: 'bar'};
  });
}

I haven't set the canonical URL of the web service yet. It should be an external service.

And my component:

import Ember from 'ember';

export default Ember.Component.extend({
  result: null,
  errors: null,
  usernameTextChanged: function() { this.reset(); }.observes('username'),
  passwordTextChanged: function() { this.reset(); }.observes('password'),
  reset() {
    this.set('errors', null);
    this.set('result', null);
  },
  actions: {
    sync() {
      this.reset();

      // TODO abstract out validation and add more use cases
      if(this.get('username') === undefined || this.get('password') === undefined) {
        this.set('errors', 'Please fill out the form');
      }
      else {
        // TODO abstract out into a utility and move config values into config
        let params = { userId: this.get('username'), passwd: this.get('password') }

        this.set('test', 'foos'); //just checking...

        Ember.$.post('/LogonAction', params).then((r) => {
          // This renders to console.
          console.log('promise happened 1', r, this.get('result')); 
          // Fails here. I don't know why.
          this.set('result', true);
          // This does not execute
          console.log('promise happened 2', this.get('result'));
        });
      }
    }
  }
});

You'll see that I output to console twice so I can debug it. I am not sure this is the right way to debug while I am writing tests.

This is my template:

<form id="logon" >
  
  
  <button>Click me</button>

  [[]] <!-- this is just debugging -->

  
    <div id="result">Sync complete</div>
  
  
    <div id="result"></div>
  
</form>

And finally, my test:

test('logging in', assert => {
  server.createList('LogonAction', 0);
  visit('/');

  console.log(0);

  fillIn('input.username', 'foo');
  fillIn('input.password', 'bar');
  click('button');

  console.log(1);

  andThen(() => {
    console.log(find('#logon').html());
    assert.equal(find('#result').text(), 'Sync complete')
  });
});

The console logging (I think) tells me that the promise is resolved before I assert that the page shows the result to the user. But I can't get this to pass! As soon as I set the value of result, it fails silently.

Any help, much appreciated.




Simple Ember.js Test Methods

I'm reading through this section of the guide. I'm testing the complex component in the tutorial.

What I'm not understanding is why these two lines exist together, I believe only the first one should.

fillIn('.list-filter input', 'Seattle');

keyEvent('.list-filter input', 'keyup', 69);


In the first line, we fill in the input field which should automatically trigger a filtering of the results. Why are we adding an extra e to the field (keycode 69)? It's like we're going to search Seattlee (note the two e's at the end). Is the keyEvent method necessary to activate the triggering of the refresh but it actually doesn't print to the input field?




Updating the Ember view after changing the Ember model

enter image description here

I have 4 posts. Each one has a title and an Author. Right now, it is sorted by Author. I would like to click a button (such as Sort By Title) and have the information be sorted by title instead of by author.

So far, I know that I am sorting the authors and titles and the model is being updated. The problem is displaying the updated information in the view. For some reason, I assumed that if I just did this.set('model', newModel) that the new information would display automatically. This is not so.

Here is my code.

practice.hbs




<button >Sort by Title</button>
<button >Sort by Author</button>

    <h2>Title: </h2>
    <h3>Author: </h3>


routes/practice.js

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        var myArray = [{
            title: "Learning EmberJS",
            author: "Erik Hatchett"
        },{
            title: "Controllers are Dead",
            author: "Frank Treacy"
        },{
            title: "Diddly Doo",
            author: "No I'm Adrian"
        },{
            title: "Yisss",
            author: "Dank Sir"
        }];

        myArray.sort(function(a,b) {
            if (a.author > b.author) {
                console.log(a + " is greater than " + b);
                return 1;
            }
            else {
                console.log(b + " is greater than " + a);
                return -1;
            }
        });

        if ("dat" < "cat") {
            console.log("ayy");
        }

        console.log(myArray[2]);
        return myArray;
    }
});

controllers/practice.js

import Ember from 'ember';

var sortByAuthor = function(a,b) {
            if (a.author > b.author) {
                console.log(a + " is greater than " + b);
                return 1;
            }
            else {
                console.log(b + " is greater than " + a);
                return -1;
            }
        };

var sortByTitle = function(a,b) {
            if (a.title > b.title) {
                console.log(a + " is greater than " + b);
                return 1;
            }
            else {
                console.log(b + " is greater than " + a);
                return -1;
            }
        };



export default Ember.Controller.extend({

    actions: {
        sortAuthors() {
            var myModel = this.get('model');
            console.log(myModel[0].author);
            myModel.sort(sortByAuthor);
            console.log(myModel[0].author);
            this.set('model', myModel);
        },
        sortTitles() {
            var myModel = this.get('model');
            myModel.sort(sortByTitle);
            console.log(myModel[0].title);
            this.set('model', myModel);
        }
    }
});

The information is definitely being sorted and the model is definitely being updated. It just doesn't appear to display the sorted information.




Mirage serializer drop Ids when include and embed some model

I have a problem with mirage.

I am defining a serializer extending ActiveModelSerializer with serializeIds: 'always', in this case the model is serialized with the relations models ids.

But when i want include some model in the serialized content i use include: ['someModel'], in that case the someModel is included succesfully, but the ids of the rest of relationships are ignored.

How can i include the ids too?




Not working Jquery circuler Proces bar in Ember.js

I'm beginner for the Ember.js , I'm try to make some application using ember, I need to add some JQuery Circular Process Bar, But its not display how can I add this,??

I'm used this Process Bar, Process Bar




mercredi 21 juin 2017

Simple Ember.js Input Syntax

I'm seeing conflicting within the ember guides on how to go about actions syntax on an helper. I'm referring to the key-press and key-up parameters.

This section shows it without parenthesis as such:

Yet here (with the code snippet titled "app/templates/components/list-filter.hbs"), it does use parenthesis as such:


I'm not sure why the API docs leave out the parenthesis but the example puts them in. Any insight appreciated




Google Maps Autocomplete InvalidValueError: not an instance of HTMLInputElement

I've read through a few different S.O. questions on this one and haven't been able to find anything indicating what I might be missing here. I'm very new to Ember, so it's possible that I've got this code in the wrong place. Regardless, here's what I've got:

../components/auto-complete.js

import Ember from 'ember';

export default Ember.Component.extend({
  didRender: function(){
    var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-90, -180),
      new google.maps.LatLng(90, 180)
    );
    var options = {
      bounds: defaultBounds
    }
    var i = Ember.$('input');
    var autocomplete = new google.maps.places.Autocomplete(i, options);
  }
});

../components/auto-complete.hbs

<input id="input-user" class="controls" type="text" placeholder="Location"
          onfocus="autocomplete">

My console output

I've looked at the tutorial, docs, etc. and there doesn't seem to be that much room for error here. I've also tried without the onfocus="autocomplete" Any and all advice would be appreciated.




Rails + Ember: Nested models incorrect format

I have a Rails API and I am trying to pull in records in Ember and while its working, my nested model is not. I have an Employee that belongs_to a Location and have created a serializer like so:

class API::EmployeeSerializer < ActiveModel::Serializer
  attributes :id, :name, :phone, :email, :manager, :terminated, :location
  belongs_to :location
end

which outputs:

{"employee":
    {"id":19,"name":"John Abreu","phone":"","email":"","manager":false,"terminated":false,"location":
        {"name":"Peabody","id":2}
    }
}

and my ember app pulls this in through:

import Ember from 'ember';

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

but I hit my error when I encounter the location portion of the hash. I get the following:

> Assertion Failed: Ember Data expected the data for the location
> relationship on a <employee:19> to be in a JSON API format and include
> an `id` and `type` property but it found {name: Peabody, id: 2}.
> Please check your serializer and make sure it is serializing the
> relationship payload into a JSON API format.

How can I correct this? I already have a LocationSerializer that has:

class LocationSerializer < ActiveModel::Serializer
  attributes :id, :phone, :address, :name
end




Multiple javascript components inside Ember.js

I am building a prototype SPA application using Ember.js and to quickly get things up and working I have (3) three separate javascript components, i.e. A calendar/todo list, A javascript clock, and another jquery type plugin. I want all of these to be in sync together.

In other words, when someone enters a todo or calendar entry, it will color the analog clockface in with the time, and then update the other plugin with details.

Right now of course, all of these components are NOT written to talk to one another. They are just independent plugins written by different open source developers.

I have two questions concerning how to go about this.

1.) It's ridiculous going about it this way, and it would be much better to just take each of the components apart, see how they work and then code them from the bottom up to work together in a uniform way.

COMMENT: The above is good, but HUGELY time consuming, and defeats the purpose to get something working quickly for proof of concept. I just basically am going to write a Rails backend with postgres and populate all the controls with data and update as you play with it.

2.) if you can use the components as they are.... is it advisable or doable to black box or wrap each of these as an Ember component, i.e. turn them each into components and then get Ember to pass data back and forth.

Of course the goal here is to get something working and UNDERSTAND how it is put together and then from this knowledge, rewrite the whole thing in from ground up in Ember/ES6, or some other framework.

Thanks guys!




How do I integrate client side and server side javascript?

I'm currently trying to learn how to create a website using a full javascript stack after previously using PHP/MySQL tech stacks. I'm familiar with javascript but I've only ever used it client side before.

To give some context, I'm looking to create a simple website that consumes the Riot Games API and basically displays the data and does various calculations with it. Nothing groundbreaking, it's mainly a project to teach myself how.

I decided to use Ember.js because I've dabbled with it before, but quickly learnt that you can't use the API with client side javascript. So, I've now got Node.js with express.js running and I've got it all set up and working in the backend, I've set up some routes to query the API and get responses.

I want to now integrate this with an Ember.js frontend, but I'm unsure what the best way to do this is. I've read this guide but it specifically states to (from my understanding) use Ember.js for your router and forward all requests through express.js to it:

// app/routes.js

 module.exports = function(app) {
        app.get('*', function(req, res) {
            res.sendfile('./public/index.html'); // load our public/index.html file
        });
};

Currently my router looks a bit like this:

// app/routes.js
var routes = require('./routes/routes');
app.use('/api', routes);

// app/routes/routes.js
var router = require('express').Router();
var lol = require('lol-js');
var riot = lol.client({
    apiKey: 'APIKEY',
    cache: null
});

// Example route
router.route('/summoner/:region/:summoner_name').get(function(req,res) {
    var summonerName = [req.params.summoner_name];
    var summoner = riot.getSummonersByName(req.params.region, summonerName, function(err, data) {
        res.json(data);
      }
    });
});

module.exports = router;

I require a couple Node.js modules in my router, but if I forward all responses to the Ember.js router like the guide I linked suggests, how would I be able to access and use Node.js modules, like lol-js (a library for using Riot Games API) from it? I'm also a bit unclear whether I should use ember-cli to create a new Ember project in the root folder or the public folder.

I have been out of the web development loop for about a year at this point, so all suggestions are welcome, including if this is a bad design or even if my chosen tech stack is old or there are better alternatives. I say this because I did also find this pre-built MEEN tech stack but didn't use it because it has been deprecated in favour of something else.




Ember: catch not working with ember-data findRecord error

I can't figure out why I can't catch this error:

Assertion Failed: You made a 'findRecord' request for a 'cart' with id '3ea1901a-56a9-11e7-a8f4-60e147bfe84c', but the adapter's response did not have any data

This is happening when trying to add an item to my cart service, but there's a problem with the API. Specifically, I am testing a security scenario where there's a token mismatch with the API. The API will send back an empty response, which it is doing, but I want ember to catch that error and trigger a addItemToNewCart function.

This is the 'add' method:

// cart methods
add(item) {

    let self = this;

    // get cart from API first.  if this fails (in catch clause) a new one should be created
    return this.get('store').findRecord('cart', get(this, 'cartObj.id')).then(response => {

        console.log("RESPONSE", response.get('cartitems'));
        // check if cart already has lineitem
        let existingLineItem = response.get('cartitems').findBy('skuid', item.skuid);
        if (existingLineItem) { // if item is already in cart, just add more
            console.log("line item in response, adding quantity");
            set(existingLineItem, 'quantity', parseInt(existingLineItem.quantity)+parseInt(item.quantity))
        } else {
            console.log("line item not in response, adding new");
            response.get('cartitems').addObject(item);
        }
        // saving persists the cart back to API
        response.save().then(newCart => {
            set(this, 'cartObj', newCart);
        });
    }).catch(e => {
        // this is not firing even though there is an error
        console.log("problem with findRecord - create a new cart and add item to it", e.message);
        self._addItemToNewCart(item);
    });

},

It appears that somehow the ember-data promise is successfully resolving, because the console.log messages I have within the then block are being printed:

enter image description here

I am guessing findRecord is looking locally first, finding the cart, executing the then block and an async findRecord is coming in later with an error from the API (too late for the catch block), maybe?

If that's the case, how do I say, "wait for a response from the API before doing anything and if the response is empty, call _addItemToNewCart" ?




Ember addon custom build

I have build an ember addon that we use to put common components we use on all ember applications and I would like to know if there is a way control what components get added the ember application build like for example if I have 5 components define in the addon but application only used 3 of them and is there a way exclude the other 2 from the build.




Component runtime compile

I am appending the below script to the body on runtime. The script is appended when i navigate to a new route default.

<script type="text/x-handlebars" data-template-name="default">
        <div class="row">
          
        </div>
</script>

I can find the script tag appended to the body. but the component is not created inside the application outlet. I tried the events like willTransition, didtransition, activate, all are called only after the navigation so it is not creating the component.

I want to render a component inside the application when navigated to a link whose template script(route.hbs) is appended to body on runtime