vendredi 30 novembre 2018

What is the best way to test an Ember component that has an outlet?

I want to test a component that has an with a handful of subcomponents that get loaded based on the URL. Currently, I simply render each component and test them individually. What are the performance implications of running this.render(hbs...) several times? Is there a better way to do this?




setupController is not working for hasMany data

here is my code. when a user has only 1 property code is working fine but in case of multiple properties. setupController and aftercontroller is not working

 model: ->
    return @get('session.currentUser.properties')

 setupController: (controller, model)->
     controller.set('properties', model)

user model is

Userr = DS.Model.extend(
  email: DS.attr('string')
  telephone: DS.attr('string')
  properties: DS.hasMany('property', { async: true })
)

`export default User`




Getting Ember frontend and Flask backend to communicate through separate Docker containers

I have dockerized a backend webapp built with Flask. The CMD line of the Dockerfile runs python app.py which internally calls app.run(host='0.0.0.0'), so that the app is running (within the docker container) at 0.0.0.0:5000. I then run the built container with

$ docker run -p 5000:5000 -it my-image:latest

The frontend is built with ember. Within the .ember-cli file, proxy is set to http://localhost:5000. When I run $ ember serve locally, the app runs smoothly at localhost:4200, communicating with the backend running from the docker image. However, I also want to run the frontend on a docker image (based on an apache image). My Dockerfile:

FROM httpd:2.4-alpine
COPY ./dist/ /usr/local/apache2/htdocs/
COPY ./.htaccess /usr/local/apache2/htdocs/

The .htaccess file is copied directly from Ember - Deploying (as per the Servers section):

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.html [L]
</IfModule>

I then do the following:

$ ember b --prod  # build the app for production (stored in ./dist/)
$ docker build -t my-frontend:latest .
$ docker run -dit --name my-frontend -p 8080:80 my-frontend:latest

I then go to localhost:8080, and can see my app's loading wheel, which means this image is working in isolation. However, I continue to get 404 errors when it tries to access the backend.

What am I doing wrong that the containers can't communicate with each other?




Need a route called 'tests'

I have a legitimate need to generate a route called 'tests'. The problem is /tests is already being for the built in test runner. Can I reconfigure the test runner to use a different route?




Is it possible to have (an undefined number of) optional segments in the Ember router?

I would like to collect extra segments from the Ember router in an array. Here is a made-up path to illustrate what I mean:

this.route('group', {path: 'group/:group_id(/:segments[])*'}, function() {

Is it possible to use a request like this:

GET /group/123/some/path/segments

And have them collected in an array?

group.id = 123
segments = ['some', 'path', 'segments']

Or is there any way to define optional segments, so I can just add many and collect them manually?




mercredi 28 novembre 2018

then() returning a null value when it should be pending

Ember 2.17

I am calling an helper from my template :


  


line, as well as pricing are ember models.

The helper is as following :

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

export function pricingsFullPricing([pricing]) {
  pricing.then(
    p=>{
      debugger
    },p=>{

    }
  )
}
export default helper(pricingsFullPricing);

When I run the page, debugger is called twice (the template loop run once).

First time p is null, the second time it is a pricing.

Isn't then supposed to prevent that? Why does it behave like that?




Override application.hbs template in Emberjs

In emberjs, I am in a situation that my application already has routes template that uses the application.hbs template, but now I want to create a new route templates that doesn't use application.hbs.

Is there any easy solution for that?

I have seen many answers but that doesn't match my specification and also my version of ember is 2.11.

Thank you.




EmberJS Component - Run custom function after DOM has fully loaded

I'm struggling to fully grasp the component lifecycle. I've created a component, but I need my custom javascript function to run after the DOM is complete. I've scoured through the EmberJS Docs and Stackoverflow, but any documentation I come across doesn't work as I intended.

My Issue

I've attempted to use didInsertElement and didRender, but they still get called before my repeating elements have loaded in the DOM. How do I circumvent this to have my Javascript run after the DOM has fully rendered.

My Attempts

Below is an extremely stripped down and barebones example using an alert in place of my script. The desired outcome is to have this alert appear after the DOM is rendered, the below examples have it alert before.

import Component from '@ember/component';

export default Component.extend({

     didRender() {
        alert('didRender');
     },

     didInsertElement() {
        alert('didInsertElement');
     }
});

Thanks in advance.




mardi 27 novembre 2018

Is there any way to resolve Ember routes, controllers, components from custom directory?

Is there any way to resolve Ember routes, controllers, components etc from custom directory and fallback to default app directory when not found?




Separate Ember Addon from vendor.js file to a separate file

I'm using a "core"-addon which contains logic that is used in multiple "boilerplate" - ember applications, when I build a boilerplate-application, the addon code is added to the "vendor.js" file found in the "assets"-folder. Is there a way I can make this code build to a separate "my-addon-vendor.js" file?

My "core"-addon is linked to my "boilerplate"-project using "npm link my-core-addon".

Thanks in advance

Versions:

  • Ember Version: 3.5.0
  • Ember CLI: 3.5.0
  • Node: 8.11.3
  • npm: 5.6.0



Spring Boot + Spring Security + Ember JS

I have a Spring boot application using Spring security for authentication.

SecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .csrf().disable()
        .formLogin()
            .loginProcessingUrl("/authenticateTheUser")
            .permitAll()
        .and()
        .logout().permitAll();
}

The users are authenticated based on the values in database. I am using BCrypt password encoder for encoding passwords.

When I access the API's it is working correctly. It authorizes when a request is made.

Now I am stuck with linking my spring boot app with Ember JS. When I try to call the /authenticateTheUser method it says invalid cors request.

Can someone help me in getting it solved. Should we use any addons for authorization with Ember JS to call the default login method provided by spring security




lundi 26 novembre 2018

Emberjs dynamic inject from mixin

I have a lot of controllers using difference services,where I should extend one mixin. In mixin, based on the controller's call I should inject difference service. Is it really do ? If yes, I open to any suggestions. My controller look like this:

import FilterController from 'core/addon/filter/filter-controller';
import defaultMixin from 'default-mixin';

export default FilterController.extend(defaultMixin,{
  filter: Ember.inject.service(Pathes.inject.service.leaseFilter),
})

Mixin:

import Ember from 'ember';
import Views from '../const/views';
import ViewsService from '../static-services/views';

const {
  computed,
} = Ember;

export default Ember.Mixin.create({

##THIS VIEW SERVICE I SHOULD INJECT BASED ON CONTROLLER ##VIEW.INJECT.SERVICE.[LEASE,LEASE1,LEASE2,LEASE3]

  viewService: Ember.inject.service(Views.inject.service.Lease),

  defaultViewType: computed(
    'viewService.filteredViewsList',
    function () {
      const viewList = this.get('viewService.filteredViewsList');
      return ViewsService.getDefaultViewFromList(viewList);
    }
  ),
});




Using Etags with ember-data

I am trying to implement some client side caching via etags and last modified headers; however, ember-data doesn't seem to be using the etags for the ajax requests. I only get 200 responses and never a 304. I don't see any ETag header being sent with the request headers.

When I make the ajax request multiple times directly from the browser address bar, I'll get 304 not modified responses after the first request, so I know the server is sending things back correctly.

Is there a configuration I need to set up to make this happen?

This is a CORS request, but I think that I have and I have exposed the ETag header:

Access-Control-Expose-Headers: ETag and the Etag header is sent back with the response.




How to authenticate against Twitter with Ember Torii and Ember Simple Auth

I'm trying to authenticate against Twitter using Ember Torii and Ember Simple Auth. However, I'm not sure how to properly close the authentication popup once the user has been authenticated. My code:

//app/authenticators/torii.js
import {inject as service} from '@ember/service';
import Torii from 'ember-simple-auth/authenticators/torii';

export default Torii.extend({
  torii: service(),
  ajax: service(),

  authenticate() {
    const ajax = this.get('ajax');
    return this._super(...arguments).then((data) => {
      console.log('Authorization data:');
       console.log(data);
      if(data.provider === "twitter" && data.code) {
        return {
          accessToken: data.code,
          provider: data.provider
        };
      }
      //This is for OAuth2 providers e.g. Facebook
      return ajax.request(
        'http://localhost:8080/api/1/auth', {
        type: 'POST',
        dataType: 'json',
        crossDomain: true,
        contentType: 'application/json',
        data: {'provider': data.provider, 'authorizationCode': data.authorizationCode}
      }).then((response) => {
        return {
          accessToken: response.token,
          provider: data.provider
        };
      });
    });
  }
});


  //config/environment.js
  .......
  providers: {
    'facebook-oauth2': {
      apiKey: 'xxxxxxxxxxxxxx',
      scope: 'public_profile,email'
    },
    'twitter': {
      requestTokenUri: 'http://localhost:8080/api/1/auth/twitter/'
    },

//app/torii-providers/facebook-oauth2.js
import { computed } from '@ember/object';
import FacebookOauth2Provider from 'torii/providers/facebook-oauth2';

export default FacebookOauth2Provider.extend({
  redirectUri: computed(function() {
    return [
      window.location.protocol,
      '//',
      window.location.host,
      '/torii/redirect.html'
    ].join('');
}),

  fetch(data) {
    return data;
  }
});

From my understanding, the following happens in case of authentication using Twitter:

  1. User clicks on an UI element to initiate the authentication flow. Ember Torii creates a popup and does a GET request to requestTokenUri. The API back-end generates the oauth_token required by Twitter and redirects to Twitter login page with oauth_token as query parameter.
  2. The user logs in. Assuming a successful login, Twitter then redirects the browser popup to the configured Callback URL on the API backend along with oauth_token and oauth_verifier parameters.
  3. The back-end API's Callback URL receives these parameters and exchanges these for oauth_token and oauth_token_secret that are stored in the back-end.

My question is basically, what happens next and how to cleanly and securely close the pop-up and initialize the session:

My back-end converts the token generated in 3 above to an internal JWT token and re-directs the browser pop-upto torii/redirect.html?code=<<JWTTOKEN>>. However, when the browser pop-up closes, Torii tries to re-authenticate the given token by calling authenticate method, which is not required. I've put in a workaround as show above in app/authenticators/torii.js. Is this correct? Is there a better way?




Ember - Sort Model after findAll

I'm using Emberfire in my app, and I'm trying to findAll stats, and then sort that model by a key, like in the following example. But, when I sort this way I lose the ability to see real time updates in my template and I have to reload the page to see the new/updated data in the view.

 model() {
    return this.store
      .findAll('stats', {
        reload: true,
        backgroundReload: true
      })
      .then(stats => stats.sortBy('date'));
  }




Parameters nested in `_jsonapi` when sending from Ember

I have an Ember 3.5 application that is connected to a Rails API app which uses the jsonapi-rails gem.

I'm using the default ember store:

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

export default DS.JSONAPIAdapter.extend({
  host: 'http://localhost:3000/api/v1'
});

And I have a simple route for a user registration form:

// app/router.js
import EmberRouter from '@ember/routing/router';
import config from './config/environment';

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

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

export default Router;


But when I attempt to save a record the params are unexpectedly nested in an _jsonapi key on the Rails backend:

app/controllers/api/v1/resource_controller.rb:75:in `permitted_attributes'
app/controllers/api/v1/resource_controller.rb:63:in `create_params'
app/controllers/api/v1/resource_controller.rb:21:in `create'
Started POST "/api/v1/users" for 127.0.0.1 at 2018-11-26 19:20:37 +0100
Processing by API::V1::UsersController#create as JSON
  Parameters: {"_jsonapi"=>{"data"=>{"attributes"=>{"email"=>"test@example.com", "password"=>"[FILTERED]", "password-confirmation"=>"[FILTERED]"}, "type"=>"users"}}}
Completed 400 Bad Request in 2ms (ActiveRecord: 0.0ms)

This is really puzzling since the request payload in Chrome is:

{"data":{"attributes":{"email":"test@example.com","password":"p4ssword","password-confirmation":"p4ssword"},"type":"users"}}




Spring Boot with Spring security + Ember JS

I have an Ember application that uses API's created using Spring Boot. I have implemented spring security for authentication in spring boot. I dont know how to link Spring Boot and Ember js now. Can someone help me through it?




dimanche 25 novembre 2018

emberjs model reverse relationship unclear

I have a postal_address model that includes: street, zipcode, city, etc. I then have multiple unrelated models like Organization or User that have the postal_address as one of their attributes. The using-models simply refer to the postal_address as belongsTo, specifying the reverse is not clear to me, i.e. inside of the postal_address do I indicate anything in terms of models that refer to it?

Depending on the context, updating the address may affect the Organization, other times the User. There are many more models that could use the postal_address than the two I listed, in the event one suggests to duplicate the address-model per use-case.




samedi 24 novembre 2018

How does Ember Data deal with security of cached objects?

From what I understand, ember data is a memoization engine; invoking peekAll looks for cached data rather than making an expensive network call. But where are these data cached? If these data are loaded client-side, doesn't that mean the data is "in transit"? If I want to design a secure front end application that holds sensitive data for the least amount of time, how can I do this? Should I avoid using Ember data entirely and simply force back end calls to be made?




vendredi 23 novembre 2018

Ember build faield because of broccoliBuilderError

I'am on an ember project and I am trying to upgrade ember version from 2.8 to 3.5.0. But since I changed the version and also some several dependencies version I get this error :

enter image description here

I've tried to fix this with ember-cli-build file but the error persiste.

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) { const isPublicEnv = EmberApp.env() === 'public';

const app = new EmberApp(defaults, {

    'sassOptions': {
        includePaths: [
            'bower_components/materialize/sass',
        ],
    },
    'outputPaths': {
        app: {
            css: {
                design1: '/assets/design1.css',
                design2: '/assets/design2.css'
            },
        },
    },
    'ember-cli-babel': {
        includePolyfill: true,
    },
    'minifyJS': {
        enabled: isPublicEnv,
    },
    'minifyCSS': {
        enabled: isPublicEnv,
    },
    'fingerprint': {
        enabled: isPublicEnv,
    },
    'tests': !isPublicEnv,
    'hinting': !isPublicEnv,
    'sourcemaps': {
        enabled: !isPublicEnv,
    },
});

app.import('vendor/lib1.js');
app.import('vendor/lib2.js');

return app.toTree();

};

Any suggestion to resolve this ?




jeudi 22 novembre 2018

Even after refresh some attributes in the model are not changed

I am new to EmberJS, and facing problem with model data updation

Controller :

export default Ember.Controller.extend({
queryParams: ['jobid'],
jobid: null,
currentCount: null,

actions: {
 onOffToggle(e) {
  var isChanged = this.get('model.b.isChanged');
  this.set('model.b.enable', e.target.checked);
  this.set('model.b.isChanged', !isChanged);
  console.log(this.get('model.b.isChanged'))
},
iterationCountChange() {
  var currentCount = this.get('currentCount');
  var isCountChanged =
      (currentCount != this.get('model.b.count')) ? true : false;
  this.set('model.b.isCountChanged', isCountChanged);
}
}});

Route:

export default Ember.Route.extend({
ajax: Ember.inject.service(),

beforeModel: function (transition) {
this.jobid = transition.queryParams.jobid;
},
model(){
  return Ember.RSVP.hash({
    a:   this.store.queryRecord('a', {jobid: this.get("jobid")}),
    b: this.store.queryRecord('b', {id: this.get("jobid")})
 });
},
setupController: function(controller, model) {
  this._super(controller, model)
controller.set('currentCount', model.tunein.get('iterationCount'))
},

actions: {
 paramChange(a, b)
  Ember.$.ajax({
    url: "/rest/test",
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
       b: b,
       a: a
     })
   }).then(response => {
    this.refresh();
  })
},
error(error, transition) {
  if (error.errors[0].status == 404) {
    return this.transitionTo('not-found', { queryParams: {'previous': window.location.href}});
   }
  }
 }
});

Here in controller I am keeping track if some value have changed, and if they have changed then update the flag related to their change, these flags like isChanged and isCountChanged are the part of the model's data, after user cliks submit button , paramChange action is called and then a post call is made to update the db for respective property changes, and then this.refresh() is called to render the latest model data.

But the problem is, once isChanged and/or isCountChanged are changed from their default value, then they don't reset to the new value present in the model data, e.g. after refresh the value to both these flags should be reset to false but it comes always true, I checked the value in the setUpController hook for the values of these flags and it confirms to true.

According to me it has something to with the controller, since any value which is used in controller once is not resetting to new value coming after refresh.

Kindly help I am spent a lot of time in this and got nothing till now, do inform if any extra information is required.




In ember, how to change values of checkboxes based on another

I have four checkbox and I want to check automatically checkbox with id = 2 if checkbox with id = 4 is checked.

I did the following but did not get the output. Could someone help me with this.

{#each category in checkboxList}}
            
            
                
            

The checkboxList is

[
   {"IS_CHECKED":false,"CHECKBOX_ID":1}, 
   {"IS_CHECKED":false,"CHECKBOX_ID":2},
   {"IS_CHECKED":true,"CHECKBOX_ID":3},
   {"IS_CHECKED":false,"CHECKBOX_ID":4}
]




In ember, how to change values of checkboxes based on another

I have four checkbox and I want to check automatically checkbox with id = 2 if checkbox with id = 4 is checked.

I did the following but did not get the output. Could someone help me with this.

{#each category in checkboxList}}
            
            
                
            

The checkboxList is

[
   {"IS_CHECKED":false,"CHECKBOX_ID":1}, 
   {"IS_CHECKED":false,"CHECKBOX_ID":2},
   {"IS_CHECKED":true,"CHECKBOX_ID":3},
   {"IS_CHECKED":false,"CHECKBOX_ID":4}
]




How to handle non-model data in ember

I want to retrieve tabular data related to a model and display it in a table. I am not sure how to do that in ember. Here is what I tried :

I added a get action on my API that return a json with the data

model_path\:id\related_data

I added a custom action to the model :

allShares: modelAction('all_shares',{type: 'GET'})

ANd here is how I add it to the route's model :

allShares: invoice.then((i)=>{return i.allShares()})

Now I have a model.allShares that should contain the data. In the network inspector I can see that there has been a query to the endpoint returning the JSON data I want to display.

The following code in the view is totally blank :


              
              
            

I can now see a big object in the inspector (using debugger in model()) and I am not sure what to do of it, or even what type of object is it.

WHat can I do now to handle this data?




mercredi 21 novembre 2018

Sort Ember Object Array with Promises

I have a model model/person

{

  firstName: DS.attr( 'string'),
  lastName: DS.attr( 'string'),
  email: DS.attr( 'string' ),
}

and another model model/project

{

  name:            DS.attr( 'string' ),
  code:            DS.attr( 'string' ),
  startDate:       DS.attr( 'date' ),
  endDate:         DS.attr( 'date' ),
  users : DS.hasMany('person', {async: true}),

}

then i'm retrieving all the projects with as an array which contains ember objects. since the project -> users is async its a promise. and i want to sort that array using the first name of the person. when the data is arrived accordingly and re render the hbs that is using the list

i have a computed property called

renderProjects = computed ('model.projects.[]')
{
 // trying to sort in here but data is not avaiable so its not getting sorted
}




Ember & Cypress | Integration test failing likely due to lack of store context

I am working with Ember.js on the frontend and using Cypress.io for integration testing. I have a "Order Status" button that upon click is supposed to use data within the store to access the specific order and navigate to the Order Status page.

However within the test, upon click from the modal, the Order Status page cannot load and my test throws this error in the console, which I think likely has to do with that route's model not finding the order from within the store and loading.

In the Cypress test, I've created the necessary routes to pass in session data, but am struggling to understand if the lack of store data is throwing this error and how to fix. Important to note that this whole flow 100% works, I'm just trying to get test coverage.

I'll attach snippets from the relevant files / functions below -- please do let me know if more information is needed. I really suspect that Cypress cannot access the Ember store, but after much research and experimenting not exactly sure what the issue is. Thanks so much for your help :)

order-status.js - model function from route

async model({ order_id: orderId }) {
    let cachedOrder = this.get('store').peekRecord('order', orderId);
    return cachedOrder
      ? cachedOrder
      : await this.get('store').findRecord('order', orderId);
  },

modal.hbs - where we navigate from current page to order-status route

<fieldset>
  <span class="modal-text">See order status</span>
  <div class="inline-button-wrap">
    <button 
       
      class="close-btn button-hollow-green">
        Close
    </button>
    <button 
       
      class="order-status-btn">
       Order Status
     </button>
  </div>
</fieldset>

test.js - test that simulates clicking order status button above

it('order status btn navigates to order status page', () => {
  cy.server();
  cy.route('GET', '/api/session', sessionResponse);
  cy.route('GET', `/api/orders/*`, order);
  cy.visit('/');
  cy.get('.delivery-card .button-cta').click(); //opens modal 
  cy.get('#modal .order-status-btn').click(); //navigates to order-status
});



Ember-cli-build, exclude components ember addon

I'm using a "core" ember addon in a boilerplate, with

npm link core-addon

This addon contains generic components, helpers, routes...

Is there a way to exclude some of these components in the boilerplate's ember-cli-build file?

I already tried the following in the ember-build-cli in my boilerplate project, which is probably wrong:

const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const environment = EmberApp.env();
module.exports = function (defaults) {
    let app = new EmberApp(defaults, {
        funnel: {
                enabled:true,
                exclude:['core-addon/pods/components/pages/**/*']
            },
    });
return app.toTree();
};

Ember version: 3.5.0 Ember cli version 3.5.0 node version 8.11.3




mardi 20 novembre 2018

Why can't I iterate over a list of Firebase Img URLS, but can access each on individually?

I have an array of Firebase storage URLs that link to images like so:

[
"https://firebasestorage.googleapis.com/v0/b/xyz-app-1540127382149.appspot.com/o/images%2F-LR855-bwb_IuYAFeYlf%2Fyyz-1.jpg?alt=media&token=e39d4dd0-6821-477a-b165-4ead2eb0a8c4",
"https://firebasestorage.googleapis.com/v0/b/xyz-app-1540127382149.appspot.com/o/images%2F-LR855-bwb_IuYAFeYlf%2abc-1.jpg?
]

Paste these into a browser? Works. Get single item in array and add it to an img element src? Works.

Iterate over the array and try to add each to an img element src? Stack Error.


  <div class="carousel-item active">
    <img
      class="d-block w-100"
      src=
      alt="Post Image"
    >
   </div>
 

stack: "Error: Assertion Failed: fullName must be a proper full name

I don't get it. Why can I get a single link in the array and it will display, yet when I iterate over the list I get an error..?




How to use hotjar with ember ?

I need to use hotjar for work, but i have some difficulties to set it up. The project is an ember project, and i have found this project to integrate hotjar : https://github.com/byrnedo/ember-hotjar

In this github page, it says : "in routes and controller you will have _hj.push available", but i can't manage to make it work and i can't find any information about how to set it up.

I added this in config/environment.js :

hotjar: {
  id: my-id
},

And in a route, if i do this :

console.log(this.get('_hj'))

I get this result in the console :

ƒ () {
    (window.hj.q = window.hj.q || []).push(arguments);
  }

Meaning that hotjar is successfully installed, but when i'm trying to something like :

this.get('_hj').push('trigger', 'hello_world');

An error appears saying :

Uncaught TypeError: this.get(...).push is not a function

Does anyone know how to make it work or if i'm making something wrong ?




lundi 19 novembre 2018

EmberJS: Some errors not thrown in production

Recently I encountered a scenario where an error (Assertion Failed: calling set on destroyed object) was thrown while running my app in development mode, but the same error wasn't thrown in production.

Why is it so? Is there a justification? If I'm missing, what other differences between production and development mode should I know?




samedi 17 novembre 2018

Ember Disable button while an action is completing its process

template


<button  type="submit">Add</button>

controller

export default Controller.extend({
    actions: {
        addUser: function(){
            //some codes here
            $.ajax({
                //some codes here
            }).then(()=>{
                alert("success");
            });
        }
    }
});

When I call press the button and call the function addUser I need to disable the button until the whole function is finished execution

Please help..!




vendredi 16 novembre 2018

Ember: Send child component's action to a parent component

I am trying to call/trigger a child component's action from a parent. I've tried this a couple ways but I'm not getting anywhere. This is basically what I have so far.
I am attempting to send the action up to the parent by passing it as a parameter in the action that was passed down...
This seems a bit like a spaghetti situation but the way my project is organized, this is my result.

If anyone could, please tell me how to successfully pass an action up to the parent as a parameter. (I'm curious to know how, if possible)
If anyone also has a better suggestion on how to call a child's action, please share. Thanks in advance!

parent-component.hbs


<div onclick=></div>

parent-component.js

actionPassedFromChild: null,
....
actions: {
    parentAction(childAction){
       this.set('actionPassedFromChild', childAction);
    }
}


child-component.hbs

<div onclick=

child-component.js

....
actions: {
    anAction(){
       this.parentAction(childAction);
    }
    childAction(){
       //Some operation
    }
}

In this example, if I stop the code inside of 'anAction', I do have 'childAction'. But by the time that it gets passed into 'parentAction', it is undefined. Could anyone explain why?




Ember passing arguments to action using helper.

Let's take this case

  

In this case, value will be passed as an argument to the action "UpdateFirstName".

Now i want to pass an object "Person" also to the action. How do i do it?

I've tried

  

but no use. Can someone help?




Re render a component from another component Ember

I'm trying to re-render a specific component when another component is clicked. When the user clicks the particular button component, a variable in sessionStorage changes, which is used by another component to display data. Upon click I want that specific component to re-render itself. I have seen Ember Re-render component and Ember Rerendering component within component, but they don't seem to be working in my case. Here are my files:

templates/components/buttons/button-cancel.hbs


  
  <button class= > Accounts </button>
  



components/buttons/button-cancel.js

import Component from '@ember/component';
import MD from "../../utils/metadata";

export default Component.extend({
  init: function() {
    this._super(...arguments);
    this.metaData = MD.create().getMetaViewStuff("Leads", "record", "buttons");
    //    console.log(this.metaData);
  },
  actions: {
    changeToAccounts: function() {
      sessionStorage.setItem('module', "Accounts");
    }
  }

});

templates/components/panels/list-panel.hbs

 <!--This button is same as button-cancel-->




components/field-list-headers (the component that needs re-rendering)

import Component from '@ember/component';
import MD from "../utils/metadata"

export default Component.extend({
  init: function(){
    this._super(...arguments);
    this.metaData = MD.create().getMetaViewStuff(sessionStorage.getItem('module'), "list", "panels")
  }
});

function getMetaViewStuff

  getMetaViewStuff: function(module, submodule, item, i18n) {
    if (this.modules[module]["views"][submodule]["meta"] !== undefined && this.modules[module]["views"][submodule]["meta"][item] !== undefined) {
      let meta = this.modules[module]["views"][submodule]["meta"][item];
      return meta;
    }
    return false;
  }




jeudi 15 novembre 2018

Eslint in Visual studio code not working with .hbs files?

Ive got eslint installed in visual studio code and it works for .js files but with Ember's .hbs files no errors are shown in the code editor. I have it all enabled along with eslint packages installed. I am running Version 1.29.0.




Using React js inside an Ember project and importing a library using import from 'npm:

I've seen many other posts with a similar issue but I couldn't find any valid solution to my case.

A bit of background:

I'm working inside an Ember application, where React is being used to develop new components (we are replacing the old ember code, using React).

So far everything works fine and we are able to create and use React components inside Ember without any issues.

Problem:

One of the React component I'm writing needs to use a range date picker and I've found several utilities that do that. I've deleted all the unnecessary code from the component:

import React from 'npm:react';
import DayPickerInput from 'npm:react-day-picker/DayPickerInput';

export default class ContractDetails extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <DayPickerInput/>
      </div>
    );
  }
}

Every time I try to render it I get the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

Reading the other posts, I tried to replace:

import DayPickerInput from 'npm:react-day-picker/DayPickerInput';

With:

import {DayPickerInput} from 'npm:react-day-picker/DayPickerInput';

But I get a similar result (note the error now says it's getting an undefined rather than an object):

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `ContractDetails`.

The only thing that prevent the error to appear is to use:

<DayPickerInput.default/>

Which, however, causes issue with the library css.

I've tried to replace this library with many others but I always get the same error, so I'm excluding an error within the library itself.

Do you have any clues why I'm getting this error?

I'm using the latest react version (16.6.3)




Ember data model explicit inverse relationships

I’m struggling with explicit inverse relationships: https://guides.emberjs.com/release/models/relationships/#toc_explicit-inverses.

If 4 instances of the blog-post model can be associated with a comment (onePost, twoPost, redPost, bluePost), how come the inverse is set on the class definition of the blog-post and not at an instance level?

Surely all instances that are created from that model definition now will now be inverse to redPost? How do I create, say, a blog-post that I would like to be associated with the comment's bluePost attribute?

The closest answers I've found are Ember - Understanding Inverse Relationships and Setting the inverse option dynamically/conditionally in ember-data? but the first one oversimplifies the problem as to not be a relevant answer and the second one went unanswered.

Thanks in advance.




mercredi 14 novembre 2018

Cann't start ember server

I tried to run npm install for an old ember project and it stops with the error npm ERR! 404 Not Found: @myFile/zf-ember-notification@1.0.1 I am just starting with ember, can someone explain how can I open and edit old ember projects.




Iterating through key-values in ember.js handlebars template

I have a javascript object

this.attributes = {
            key: value,
            // etc..
        }

I would like to iterate through it and output key:value

Here is my solution:

import Ember from 'ember';

export default Ember.Component.extend({
init() {
    this._super(...arguments);
    this.attributes = {
        'SKU': '123',
        'UPC': 'ABC',
        'Title': 'Hour Glass'
       }

},

ProductAttributes: Ember.computed('attributes', function() {

    var attribs = this.get('attributes');
    var kvp = Object.keys(attribs).map(key => {
        return {
            'attribute_name': key,
            'attribute_value': attribs[key]
        };
    });
    return kvp;
})});

The template I came up with:


     : 


I am not happy with this solution since it looks cumbersome: first I convert object into an array of auxiliary objects with non-dynamic keys attribute_name and attribute_value, and then I references non-dynamic names directly within my template.

It works fine but is there a better way of doing this?




How can I see what request is done by Ember FastBoot?

I've installed ember-cli-fastboot and a certain path throws an Error: The adapter operation was aborted server-side (i.e. in the terminal).

Can I output all requests fastboot does, so I can see what the last one was before the rendering of the page was aborted due to this error message?




Why can't I set persistence even though login functions work with Firebase?

I have a component with a form that holds the email and password. Imports at the top:

import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import * as firebase from 'firebase';

Next, I inject the service for the firebaseApp and session (session just has some attrs that I set to tell the app we're authenticated -- these will be refactored later):

session: service(),
firebaseApp: service(),

If I pass these values into the signInWithEmailAndPassword() function from fbApp.auth(), the account is validated and logged in. Works as expected:

login() {
  const session = this.get('session');
  const fbApp = this.get('firebaseApp');
  const e = this.get('form.email');
  const p = this.get('form.password');

  fbApp.auth().signInWithEmailAndPassword(e, p).then(u => {
    session.set('user.email', u.email);
    session.set('user.signedIn', true);
    this.get('goHome')(); // route transition to home
  }).catch(e => {
    this.set('error', 'Something went wrong. Try again?');
  });
}

Next, I wanted to persist the session so that the user is not logged out on refresh, only if the tab is closed. So I modified the code and wrapped the signInWithEmailAndPassword in with setPersistence as follows:

login() {
  const session = this.get('session');
  const fbApp = this.get('firebaseApp');
  const e = this.get('form.email');
  const p = this.get('form.password');

  fbApp.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
              .then(()=> {

    fbApp.auth().signInWithEmailAndPassword(e, p).then(u => {
      session.set('user.email', u.email);
      session.set('user.signedIn', true);
      this.get('goHome')(); // route transition to home
    }).catch(e => {
      this.set('error', 'Something went wrong. Try again?');
    });

  }).catch(e => {
    this.set('error', 'Something went wrong. Try again?');
  });
}

This doesn't work. I get a Cannot read property 'SESSION' of undefined error in the console. I'm sure it has to do with how firebase is imported but I'm having trouble with it.




Ember js Disconnect Outlet doesnt clear cached template data

i have a modal where i open and via a outlet so opened it using following code

this.render( controller, {
  into: 'application',
  outlet: 'modal'
} );

then in the modal view i have a computed property

  peopleArray: computed ('someDataFromaMixin' , function (){
    debugger;
    return this.get( 'someDataFromaMixin' )
  }),

then i close the modal using below code

removeOutlet: function( ) {

    return this.disconnectOutlet( {

      outlet: 'modal',
      parentView: 'application'
    } );
  },

issue is the computed property compute if i go there with a page refresh

if i close the modal and re-open again the computedProperty will not trigger ( even if i modified the computed property data )

im clueless what cause this issue




mardi 13 novembre 2018

Rendering a component programmatically (not via template)

I'm working on an Ember app that's integrated with a separate SDK that has its own custom UI components. For example,

<integration-name-customer-view customer-name="Bob">

These components have render lifecycle hooks, like onRender, onCreate, etc.

I would like to hook into the onRender callback and insert an Ember component I have created (a tooltip with some special functionality).

Here's what I've attempted:

Integration-Customer-Name Definition

import MyTooltip from 'ember-app/components/my-tooltip';    

...

onRender() {
    let parent = this;

    MyTooltip
        .extend({
            layout: myTemplate,
            didRender: () {
                parent.appendChild(this.element);
            }
        })
        .create({ position: 'above' })
        .appendTo(document.body);
}

Now, this actually works, but I have two questions:

  1. Is this the right thing to do? Is there a simpler way/is this going to crash and burn?
  2. My template has a block in it. Is there a way to programmatically determine what is going to be rendered into that block?



how to include images to ember cli

i am doing a project using ember js as frontend.need help adding image.

for eg: in the template I want to add an image like

<img src="/location/image.png"/>

Where should I store the image? Is there any standard practices that follow in ember to store images and fonts?




Ember: Why does computed not fire when the observer does?

I'm having difficulty wrapping my head around this - I'm working with inherited legacy code, and while this seems like it should be very simple, it's anything but.

In this app/pods/application/route.js, there's a "welcome pack" object that's grabbed by the server, as part of that, there's a setWp() method called on the welcome-pack service, which sets the 'wp' value on that same service. (Yes, I know you can probably set the value on the service directly, with "this.wp.set('wp', welcomePack)" but as I said: inherited legacy code.) Point is, that should trigger the change in the value. My observer for wp.wp is firing, but NOT my computeds based on wp.wp. Any clues?

// app/pods/application/route.js
wp: inject('welcome-pack'),
model(){
  return this.store.findAll('welcome-pack').then((welcomePack) => {
  this.wp.setWp(welcomePack);
})
}



// app/pods/welcome-pack/service.js
import Service from '@ember/service';
export default Service.extend({
  wp: null,
  setWp(wp){ // <-- called when the model loads from the ajax request
    this.set('wp', wp)
  }
})

// app/pods/application/controller.js
import Controller from "@ember/controller";
import { inject } from "@ember/service";
import { computed, observer } from "@ember/object";

export default Controller.extend({
  wp: inject("welcome-pack"),
  init(){
    console.log('this.wp', this.wp) // <- logs service as class
    console.log('this.wp.wp', this.wp.wp) // <-logs null
    setTimeout(() => {
      // set for after the ajax call has been made and setWp() has been called. 
      console.log('this.wp', this.wp) //<- logs service as class
      console.log('this.wp.wp', this.wp.wp) //<- logs object as class
    }, 2000)
  },
  obsWPChanges: observer('wp', function(){
    console.log('wp changed'); // <-- never executes (don't expect it to)
  }),
  obsWPWPChanges: observer('wp.wp', function(){
    console.log('wp.wp changed') //<-- executes (as expected) when setWP() is called
  }),
  primaryColor: computed("wp.wp", function() {
    console.log("this.wp.primaryColor", this.wp.primaryColor) // <-- does not execute
    return this.wp.wp.primaryColor || "#37b3c0";
  }),
  secondaryColor: computed("wp.wp", function() {
    return this.wp.wp.secondaryColor || "#38a0d0"; // <-- does not execute
  })
});




lundi 12 novembre 2018

Ember addPackageToProject or addBowerPackageToProject

In an Ember app, I wanted to understand how addPackageToProject or addBowerPackageToProject exactly works ?

e.g. this.addPackageToProject('moment')

I understand this would update the package.json or bower.json of the host/parent app by adding 'moment' as a dependency. But does it also run npm install or bower install commands after that ?




How can I set ember-simple-google-maps env variables?

Trying to configure settings for ember-simple-google-maps.

let ENV = {
  modulePrefix: 'app-name',
  environment,
  rootURL: '/',
  locationType: 'auto',
  EmberENV: {
    FEATURES: {},
    EXTEND_PROTOTYPES: {
      Date: false
    }
  },

  APP: {},

  firebase: {
    apiKey: "xxxxxx"
  },

  GOOGLE_MAPS_VERSION: '3.34',
  GOOGLE_MAPS_API_KEY: 'xxxxxxxxxx'
};

According to the documentation I should be able to set these variable but it doesn't work. Version isn't set to the latest and the API is not found. Any thoughts? I'm sure I'm missing something super obvious...

Aspects of the Google Maps Installation can be customized, by supplying environment variables to the server process.




Ember rendering multiple models

I want to render multiple models into the same route. The data is coming from a DRF backend in JSON format The routed data should be accessible in the template separately




Live actions in Ember

How can we implement live actions in ember without reload or pressing an action button?

for example, if I'm filling a form to change the password, In the confirm password input, I need to check the matching of these two passwords lively(without pressing any button) This is just a case? how can I implement this?




Create a fully dynamic table in EmberJS

I have defined a model in EmberJS with the following attributes:

import DS from 'ember-data';

export default DS.Model.extend({
    "name": DS.attr('string'),
    "status": DS.attr('string'),
    "email1": DS.attr('string'),
    "account_name": DS.attr('string'),
    "phone_work": DS.attr('string'),
    "date_entered": DS.attr('string'),
    "date_modified": DS.attr('string')
});

I am creating a component called fields-list that would render these attributes into a table (headers, body; just like a typical table to list some fields). However, instead of making the table bound to this model only, I want to make the component fully dynamic, so that other models with different field names could also reuse this component to generate their tables as well.

This way, whenever the component is used, it detects the model and populates the headers of the table as well as the body according to the fields in that model.

How do I achieve this? If there is anything that's not clear in the query please do let me know, I've tried my best to explain the issue properly as much as I can. Thanks in advance!




dimanche 11 novembre 2018

Rails ActionController::ParameterMissing error when creating new record in Ember

Rails 5.2 with fast_jsonapi 1.5, Ember 3.4

I create a new Tag record like this in Ember:

let newTag = this.get('store').createRecord('tag', {
  name: this.get('name')
});
newTag.save();

This sends the following json (as seen in the Network tab of Chrome as the Request Payload):

{"data":{"attributes":{"name":"photos","created_at":null,"updated_at":null},"type":"tags"}}

But Rails only gets (as verified by printing out the params in the create method of the TagsController):

{"controller"=>"tags", "action"=>"create"}

And it throws the following error:

ActionController::ParameterMissing (param is missing or the value is empty: tag)

And here is my controller code:

# app/controllers/tags_controller.rb
class TagsController < ApplicationController
  def create
    tag = Tag.create!(tag_params)
    render json: {status: "success"}
  end

  private

  def tag_params
    puts params
    params.require(:tag).permit(:name)
  end
end

What's the trick to get ember and rails to understand each other? Since ember is sending the "type" in the payload, can I get Rails to understand that this is model and thus fulfill the requirement I've set that "tag" be present in the params?




Replace Ember.ArrayController.create() will not resolve belongTo relationships | ember upgrade 3.x

Im in the process of upgrade and im facing issues on ArrayController is being depreciated

in my old Ember 1.13 route im using

model/announcement.js

export default DS.Model.extend( {


  id:DS.attr('string'),
  title: DS.attr( 'string' ),
  description: DS.attr( 'string' ),
  published: DS.attr( 'boolean' ),
  publishedAt: DS.attr( 'date' ),

  course: DS.belongsTo( 'course' ),
  author: DS.belongsTo( 'profile', { async: true } ),

  viewed: false,
  isNew: true,

}

serializer/announcement.js

import DS from 'ember-data';
import ApplicationSerializer from 'mim/serializers/application';

export default ApplicationSerializer.extend( DS.EmbeddedRecordsMixin, {

  keyForRelationship: function( key ) {

    return key !== 'author' ? key : 'id';
  }
} );

routes/announcement.js

 setupController: function( controller, model ) {

    this._super( ...arguments );

     var announcements = Ember.ArrayController.create( {

          model: model,
          sortProperties: [ 'publishedAt' ],
          sortAscending: false
        } );

        controller.set( 'model', announcements );
  },

in controller of route announcement as follow

controller/announcement.js

publishedAnnouncements: Ember.computed( 'model.[]', 'model.@each.published', 'model.@each.viewed', function() {

    var published = this.get( 'model' ).filterBy( 'published', true ),
        announcements = Ember.A();

    announcements.pushObjects( published.filterBy( 'viewed', false ) );
    announcements.pushObjects( published.filterBy( 'viewed' ) );

    return announcements;
  } ),

so in the template im running a for each loop to render all announcements like

templates/announcements.hbs

  
        
       

In ember upgrade 3.5 i have changed these to following

model/announcement.js

export default DS.Model.extend( {

  id:DS.attr('string'),
  title: DS.attr( 'string' ),
  description: DS.attr( 'string' ),
  published: DS.attr( 'boolean' ),
  publishedAt: DS.attr( 'date' ),

  course: DS.belongsTo( 'course' ),

// remove async true from profile

  author: DS.belongsTo( 'profile'),

  viewed: false,
  isNew: true,

}

serializer/announcement.js

import DS from 'ember-data';
import ApplicationSerializer from 'mim/serializers/application';

export default ApplicationSerializer.extend( DS.EmbeddedRecordsMixin, {

  keyForRelationship: function( key ) {

    return key !== 'author' ? key : 'id';
  }
} );

routes/announcement.js

setupController: function( controller, model ) {

    this._super( ...arguments );

     //removed arrayController from here and assigned model

        controller.set( 'model', model );
  },

controller/announcement.js

sortProperties: ['publishedAt:desc'], sortedModel: computed.sort('model', 'sortProperties'),

publishedAnnouncements: Ember.computed( 'model.[]', 'model.@each.published', 'model.@each.viewed', function() {

   //getting model by local computed property defined above.arrayController sort is doing with above method by sortPropteries 
   var published =this.get('sortedModel').filterBy( 'published', true);
        announcements = Ember.A();

    announcements.pushObjects( published.filterBy( 'viewed', false ) );
    announcements.pushObjects( published.filterBy( 'viewed' ) );

    return announcements;
  } ),

templates/announcements.hbs

  
        
       

then the announcement.author.firstname is undefined in ember 3.5 but when if it is not a belongsTo relationship it will be there (example announcement.publishedAt)

i have no clue what i missed or what i did wrong here.

im here attaching screenshot of a console log which i did in controller published variable.

ember 1.13

enter image description here

ember 3.5 enter image description here




vendredi 9 novembre 2018

How do I minify CSS classnames with Ember CLI?

I looked through the docs on how to do this but nothing turned up.

There's this:

The compiled css-files are minified by broccoli-clean-css or broccoli-csso, if it is installed locally

So I'm guessing it uses broccoli-clean-css by default which uses clean-css. I looked at both clean-css and csso and neither seem to have an option for mangling/minifying class names.

So I looked at how the React / Webpack folks are doing it. They seem to use css-loader which relies on post-css.

As far as I can tell, Ember doesn't use PostCSS out of the box?

Question: how can I get Ember CLI to mangle class names and remove useless classes/IDs like .ember-view and #ember123?

My motivation for this is I want to cache SSR content in Redis but my Redis instance is filling up so I need smaller payloads.




Chrome responds with "Error 403 (from disk cache)" on Get Request

Ever since Chromium 70, some users of our webapplications have been getting an occasional error "403 (from disk cache)" only in Chrome.

It isn't a regular 403 error returned by the back-end, because if I test the request, by using Postman to GET with the same endpoint, headers, query-params etc... I just get a regular response.

If we use the application in Firefox we have not problem either.

403-from-disk-cache

Probably unrelated, but our Back-end is built with Drupal8/Symfony3 on PHP7.2 and front-end EmberJS 3.4 LTS.




jeudi 8 novembre 2018

How to build a meta-driven application in emberJS

Note: The English used in this article (along with the terms) may be a bit "out of order" since my native language is not English. Rest assured I have tried my best to make it as readable as possible, and if I have missed anything please do comment before downvoting so I may update the question accordingly (I'm still new to this)

So I've searched most of the internet for a solution to this, to find a tutorial that would guide me on the metadata driven approach for building an application on EmberJS. The documentation on Ember doesn't explain anything about the approach, just a function definition of extractMeta here, and a basic overview of how to handle metadata here.

What I want to achieve is to build a portal, with Sugar as the back-end for the application. The application will use REST API for making calls to extract the data as well as the metadata of the application. We want to make the application generic, so that no matter what module is called, the metadata is extracted to determine the fields required in the model, a filtered portion of the data needed from the call is populated into the model accordingly and the is displayed in a generic template, that will be global and used throughout the application.

The metadata includes various items such as buttons, panels, attributes(each with multiple layers of data within) etc, each may be used once or multiple times within the call or not at all. For example, for displaying the application would require the attributes for display within the table, as well as buttons for adding, deleting updating etc. Upon click the panel may be required for say, adding a particular record, which itself may contain various fields.

list As an example, is the default Sugar instance that shows the leads in the data, notice how it contains various components.

add data Here, another example, of the panel that appears when I click the create button in the leads list, notice the fields that appear within the panel

Please Note that I do understand how to make the REST API calls for the data as well as the metadata. But how to turn that into a generic application is what I am struggling with. Thanks in advance!




Ember : Could not find module `@ember-intl/intl-relativeformat` imported from `ember-intl/services/intl`

I added the module ember-intl in my app since the ember-i18n is deprecated. so yarn works well, updates package.json and yarn.lock (i got rid of the package.lock), but i get this error on the browser's console after a successful ember build:

Error: Could not find module @ember-intl/intl-relativeformat imported from ember-intl/services/intl

But in my node_modules the folders @ember-intl/intl-relativeformat and ember-intl both exist. in the yarn.lock i have this line: "@ember-intl/intl-relativeformat@^2.1.0":

more info:

Ember : 3.5.1
Ember Data : 3.5.0
jQuery : 3.3.1 Ember Remodal : 2.18.0




Configuring ember-cli 3.5's content security policy, CSP

I have this error in my ember-cli build app: Content Security Policy: Les paramètres de la page ont empêché le chargement d’une ressource à eval (« script-src »).

The error is in vendor.js, referring to lines made with webpack and broccoli. I cannot understand why the built js would take files from /tmp/, so I am guessing that the app is trying to get files from my hard drive in /tmp/, which is madness for a website.

I did configure the content security policy with these options:

//in the file config/environment.js
/* eslint-env node */
'use strict';

module.exports = function(environment) {
  let ENV = {
// ...

    contentSecurityPolicy: {
      'script-src': ["self", 'unsafe-eval','unsafe-inline'],
      'img-src': "'self'",
    },
// ...

But it doesn't change the CSP in my build. It breaks the JS and my app cannot load fully. What did I miss?




Is it possible to use Torii with FastBoot in Ember?

I'm using Torii 0.10.1 with Ember 3.5 in order to use facebook-connect by injecting the torii service into the controller.

This works fine, but as soon as I enable FastBoot, I'm getting the following error:

There was an error running your app in fastboot. More info about the error: 
 ReferenceError: document is not defined
    at loadScript (/tmp/broccoli_merge_trees-output_path-foo.tmp/assets/addon-tree-output/torii/providers/-private/utils.js:24:1)
    at Ember.RSVP.Promise.then.window.fbAsyncInit (/tmp/broccoli_merge_trees-output_path-foo.tmp/assets/addon-tree-output/torii/providers/facebook-connect.js:34:1)
    at initializePromise (/tmp/broccoli_merge_trees-output_path-foo.tmp/assets/rsvp.js:397:1)
    at new Promise (/tmp/broccoli_merge_trees-output_path-foo.tmp/assets/rsvp.js:877:1)
    at fbLoad (/tmp/broccoli_merge_trees-output_path-foo.tmp/assets/addon-tree-output/torii/providers/facebook-connect.js:26:1)
    at Class.init (/tmp/broccoli_merge_trees-output_path-foo.tmp/assets/addon-tree-output/torii/providers/facebook-connect.j




How do I hide Bootstrap tab content?

In my Ember application I have a Bootstrap nav with nav-pills, which each show different content in a tab-content. None are active until clicked. What I want is to make the currently active tab (and pill) deactivate if clicked again, hiding all content.

<div class="col-sm-9 nav-pills">
  <ul class="nav nav-pills">
    <li><a class="tab-toggle" data-toggle="pill" href="#special-instructions">Special Instructions</a></li>
    <li><a class="tab-toggle" data-toggle="pill" href="#job-details">Job Details</a></li>
    <li><a class="tab-toggle" data-toggle="pill" href="#alerts">Alerts</a></li>
    <li><a class="tab-toggle" data-toggle="pill" href="#toolbox">Toolbox Talk</a></li>
    <li><a class="tab-toggle" data-toggle="pill" href="#load-cell">Load Cell</a></li>
  </ul>
</div>

<div class="tab-content job-info">
<div id="special-instructions" class="tab-pane fade in">
  <div class="row spacer-mb-1"></div>
  Special Instructions
</div>
<div id="job-details" class="tab-pane fade in">
  <div class="row spacer-mb-1"></div>
  Job Details
</div>
<div id="alerts" class="tab-pane fade in">
  <div class="row spacer-mb-1"></div>
  Alerts
</div>
<div id="toolbox" class="tab-pane fade in">
  <div class="row spacer-mb-1"></div>
  Toolbox Talk
</div>
<div id="load-cell" class="tab-pane fade in">
  <div class="row spacer-mb-1"></div>
  Load Cell
</div>
</div>

I'm new to Ember and not sure how to include jQuery in it. I have only a template and a route.




mercredi 7 novembre 2018

Ember 3.5 BelongsTo Relationships not Resolving

i used to have emberjs 1.13 which i upgraded to 3.5 i got an issue with belongsTo relationships where i cannot access those data in it. my code as below

model

export default DS.Model.extend( {

  peoplesoftId: DS.attr( 'string' ),
  title: DS.attr( 'string' ),
  description: DS.attr( 'string' ),
  published: DS.attr( 'boolean' ),
  publishedAt: DS.attr( 'date' ),

  course: DS.belongsTo( 'course' ),
  author: DS.belongsTo( 'profile', { async: true } ),

  viewed: false,
  isNew: true,

}

in controller

this.get('model.published') working 
this.get('model.author.name') not working 

but the same code was working on 1.13 of emberjs




Ember JS 3.5 Why are the ids not loaded with the hasMany relationship?

I am trying to do a search using the ids from a has many relationship. There is a Promise, but I can't figure out where to wait for it.

Ember 3.5

const user = this.get('user');
return user.get('accounts').then((accounts) => {
    console.log(accounts); // <-- This is a Promise Array with length at least 1.
    const ids = accounts.mapBy('id');
    console.log(ids); // <-- Why is this empty?
    return this.store.query('order', { filter: { accounts: ids } });
}




mardi 6 novembre 2018

emberjs loading spinner with findRecord

EmberJS 3.4

I'm loading a Project entity from a backend which takes a couple of seconds. Now I would like to show a spinner during loading.

as described I created a project-loading.hbs. https://guides.emberjs.com/release/routing/loading-and-error-substates/

project model class:

export default AuthenticatedRoute.extend({
  model(params) {
    return this.store.findRecord("project", params.projectname);
  },

  actions: {
    refresh: function() {
      this.refresh();
    }
  }
});

though it takes time to load the entity, the loading template seems not to be rendered/shown. Am I doing something wrong ?




Ember cli mirage: using fixtures in acceptance test

I am trying to use fixtures with my acceptance tests however its causing tests to fail due to duplicate data since fixtures are re-inserted in the mirage DB every test. Is there a way to get around this or remove the fixtures every test

setupApplicationTest(hooks);
setupMirage(hooks);

hooks.beforeEach(function() {
    this.server.loadFixtures();
});




Ember : if a value is set in controller , perform an Ajax command(written in template),

I have given a rough code to understand what I need to perform,

/app/route1/controller.js

export default Controller.extend({
    test: function(id) {
        $.ajax({
            .....
            .....
            .....
        }).then(() => {
           set('message','successfully added');
        });
    }
});

/app/route1/template.hbs

<div class="ui container">
  <div class="ui segment"
    <button class="ui button" >Submit</button>
  </div>
</div>
<div class="ui container">
  <div class="ui modal">
    <div class="header"
      Message
    </div>
    <div class="content"
      
    </div>
    <div class="actions">
      <div class="ui ok button">OK</button>
    </div>
  </div>
</div>
<script type="text/javascript">
  $.ajax({
    if(message) {
      $('.ui.modal').modal('show');   
    }
  })
</script>

If I set a message in controller then, I have to show this message in the MODAL. The Ajax command that I've written is not correct., Please help to solve this issue. Thanks in advance




lundi 5 novembre 2018

When I try to run $ npm install to install all modules on project, or when trying to install ember v 2.18 with $ npm install ember@2.18 it gives me the error:

npm http GET https://www.npmjs.com/ember
npm http 200 https://www.npmjs.com/ember
npm ERR! registry error parsing json
npm ERR! SyntaxError: Unexpected token <
npm ERR!
npm ERR! <!doctype html>
npm ERR! <html>
. . .
. . .
npm ERR! </html>
npm ERR! 
npm ERR!     at Object.parse (native)
npm ERR!     at RegClient.<anonymous> (/home/felipe/.nvm/v0.8.16/lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:226:23)
npm ERR!     at Request.init.self.callback (/home/felipe/.nvm/v0.8.16/lib/node_modules/npm/node_modules/request/main.js:120:22)
npm ERR!     at Request.EventEmitter.emit (events.js:99:17)
npm ERR!     at Request.<anonymous> (/home/felipe/.nvm/v0.8.16/lib/node_modules/npm/node_modules/request/main.js:648:16)
npm ERR!     at Request.EventEmitter.emit (events.js:126:20)
npm ERR!     at IncomingMessage.Request.start.self.req.self.httpModule.request.buffer (/home/felipe/.nvm/v0.8.16/lib/node_modules/npm/node_modules/request/main.js:610:14)
npm ERR!     at IncomingMessage.EventEmitter.emit (events.js:126:20)
npm ERR!     at IncomingMessage._emitEnd (http.js:366:10)
npm ERR!     at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 4.9.0-8-amd64
npm ERR! command "/home/felipe/.nvm/v0.8.16/bin/node" "/home/felipe/.nvm/v0.8.16/bin/npm" "install" "ember@2.18"
npm ERR! cwd /workspace/acras/projects/api_dashboard
npm ERR! node -v v0.8.16
npm ERR! npm -v 1.1.69
npm ERR! type unexpected_token
npm ERR! Error: EACCES, open 'npm-debug.log'
npm ERR!  { [Error: EACCES, open 'npm-debug.log'] errno: 3, code: 'EACCES', path: 'npm-debug.log' }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 4.9.0-8-amd64
npm ERR! command "/home/felipe/.nvm/v0.8.16/bin/node" "/home/felipe/.nvm/v0.8.16/bin/npm" "install" "ember@2.18"
npm ERR! cwd /workspace/acras/projects/api_dashboard
npm ERR! node -v v0.8.16
npm ERR! npm -v 1.1.69
npm ERR! path npm-debug.log
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, open 'npm-debug.log'
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /workspace/acras/projects/api_dashboard/npm-debug.log
npm ERR! not ok code 0

I tried with sudo, no luck.
I also tried to uninstall NPM and NodeJS, but no luck also.

How do I fix that? Is this a problem with my NPM or NodeJS installation?

Thanks!




How to detect a period of inactivity in EmberJS?

I am trying to detect a period of user inactivity in my EmberJS application so that, after a certain duration I can call a session.inValidate method and revoke their authentication.

The only resource I have been able to find is an article here which I was advised in an original question is out of date and doesn't use current Ember concepts.

The out-of-date article suggested adding a property to the App object and updating the property on certain events like mousemove but I was unable to find a location to set this property correctly in either app.js or the config environment.

ember-concurrency was recommended but after looking at some of the documentation I still don't understand where such code fits in an EmberJS application structure.

Unfortunately I'm stuck at a point before I can give a code sample. Any advice is appreciated.




edit array in ember.js inside javascript file

I have declared an array in ember as shown below.

checkboxList:[{VALUE: "Content", CHECKBOX_ID: 1},{VALUE: "Size", CHECKBOX_ID: 2}],

I want to change the value in the first object from 'Content' to 'Contents' in another part of the program.

I tried to do the following :

this.set('checkboxList.[0].VALUE', "Cont");

But it did not work. Could anyone help me out with this ?

Thanks in advance :)




How to add a property to the App object in an EmberJS application

I am trying to add some timeout functionality to my application and using an old article for reference (available here).

I'm falling at the first hurdle in that I don't understand how to add a lastActiveTime property to my App object. The ember documentation states

An instance of Application is the starting point for every Ember application. It helps to instantiate, initialize and coordinate the many objects that make up your app.

Each Ember app has one and only one Application object. In fact, the very first thing you should do in your application is create the instance...

This is obviously being handled in my working application and I can view the App object but I can't see where to add properties to it. I tire dot add it in app.js:

import Application from '@ember/application';
import Resolver from './resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';

const App = Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  lastActiveTime: null,
  ready: function () {
    App.lastActiveTime = new Date();
  },
  Resolver,

});

loadInitializers(App, config.modulePrefix);

export default App;

or in the environment config:

module.exports = function (environment) {
  let ENV = {
    modulePrefix: 'insight',
    environment,
    rootURL: '/',
    locationType: 'hash',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      }
    },

    //turn on/off config
    export_data: false,

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
      lastActiveTime: null,
       ready: function () {
         App.lastActiveTime = new Date();
       },


    }
  };

and neither produce an App.lastActiveTime property. I'm actually unable to import App in the environment config so that can't be correct.

I don't know if I'm failing in Ember or failing some basic aspect of Object handling. Any advice is appreciated




How to get the id of the checkbox in ember.js

I am new to ember.js and I need to get the id of the checked checkbox in ember.

I have used javascript but in ember it's different.




If I select the second checkbox I need only the id which is 2. Can anyone help me out in this ? Thanks in advance :)




dimanche 4 novembre 2018

Ember handlebars How can I make an Ajax or jquery call for an handlebar file?

<div class="ui form segment">
    <div class="field">
      <div class="ui selection dropdown" tabindex="0">
        <div class="default text">
          Select
        </div>
        <i class="dropdown icon"></i><input name="hidden-field" type="hidden">
        <div class="menu" tabindex="-1">
          <div class="item" data-value="1">
            Choice 1
          </div>
          <div class="item" data-value="2">
            Choice 2
          </div>
        </div>
      </div>
    </div>
  </div>

this code is written inside a template.hbs(handlebar) file. I want to initialise the drop down with the following command

$('.ui.dropdown')
  .dropdown();

where could I write the second code? if it was an html/php file I could write inside the template




How to retrieve data from database and display it in a select box using ember

Im new to ember. For example, I have store 5 countries in database, which is [US, CH, CA, JP, KR]

How do I retrieve them and display those countries in a drop-down-list using ember?

*I've seen tutorials that put arrays of countries in the controller, but now I wanted to get it from the database.




Testing a Select Element with ember-cli-page-object

Not certain if I'm missing something, this seems like it should be built in. I'm using a native select dropdown on a site and am having issues figuring out how to implement it into my integration tests.

This is part of the page object I'm testing against.

  apiSelect: {
    scope: 'section.api-selector block-select',
    select: clickable('.select-dropdown'),
    options: collection('option', {
      label: text(),
      select: clickable()
    }),
    value: value('select'),
    isDisabled: is(':disabled', 'select')
  }

await component.content.customAnswers.apiSelect.select();
    assert.deepEqual(
      api.customAnswers.selectedAnswers,
      [ 'my-api-answer' ],
      'see api answer is set'
    );

I know the above doesn't work (nor should it), but I'd expect at the least for the dropdown to actually receive a click action and be displayed as opened during my test.

Essentially, I need to find a way to open this drop down and have it select an option.

I looked through everything on http://ember-cli-page-object.js.org/docs/v1.14.x/ and wasn't able to find anything outlining how to do this. It seems like it should be super simple, but maybe not? I see a lot of addons for select, but would rather not add another package unless I have to.




vendredi 2 novembre 2018

Is it posible to create a pwa with screen overlay acces for android?

Hey there! My Name is Silvan and i'm currently working on a new chat webapp for android using emberjs, cordova and firebase.

Yhe only problem i encounter is that i can't find anything about the screen overlay acces for android.

so does anyone know if this is possible in some kind of way for a PWA?

regards.




ubuntu 18.04- ember: command not found

I know this has been addressed before, but I've tried the advice on No command 'ember' found and it hasn't worked for me.

I'm trying to install EmberJs for a techtest and I keep getting 'Command 'ember' not found'. I'm on Ubuntu 18.04, and have checked all my paths as follows.

When I run npm install -g ember-cli it installs and shows:

npm WARN deprecated exists-sync@0.0.4: Please replace with usage of 
fs.existsSync
/home/[user]/.npm-global/bin/ember -> 
/home/[user]/.npm-global/lib/node_modules/ember-cli/bin/ember
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 
(node_modules/ember-cli/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for 
fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: 
{"os":"linux","arch":"x64"})
+ ember-cli@3.5.0
updated 1 package in 14.662s

So I've definitely got it installed. When I run which npm/ which node I get the following respectively:

/usr/bin/npm
/usr/bin/node

When I run echo $PATH I get:

/home/[user]/npm_global/bin:/usr/local/share/npm/bin:
/usr/local/bin:/usr/local/sbin:~/bin:/usr/share/rvm/gems/ruby-2.3.7/
bin:/usr/share/rvm/gems/ruby-2.3.7@global/bin:/usr/share/rvm/rubies/
ruby-2.3.7/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/
sbin:/bin:/usr/games:/usr/local/games:/usr/bin:/snap/bin:/usr/
share/rvm/bin

Andddd I have these paths in my bashrc:

export PATH="/usr/local/share/npm/bin:/usr/local/bin:/usr/local/sbin:~/bin:$PATH"

and

export PATH="/home/[user]/npm_global/bin:$PATH"

I realise this is a lot of info, I'm new to this so wanted to give as much as I could. Any suggestions very much appreciated, thank you!




How do I reference a function in the vendor folder in a component?

I'm currently receiving an ES Lint error in the following JS file for a component:

import Component from '@ember/component';

export default Component.extend({


  didInsertElement() {
    this.$(document).ready(function () {
      App.init();
    });

  },

  actions: {

    toggleDropdownCurrentUser() {
      this.toggleProperty('userDropDownOpen');
    },

    toggleNav() {
      this.toggleProperty('navDropDownOpen');
    }

  }

});

The function App is reporting as not defined. This function is in the vendorjs files that is compiled on build and definitely works.

I tried to import App from ../../../vendor/apps but I can't seem to get the folder structure correct and end up with an error suggesting I can't go back to the root of the project.

Is there some methodology I am missing?




jeudi 1 novembre 2018

Fetching dynamic Id part from URL in Ember JS

I have a route pointing to URL "http.appname.com/employee/:empid/addproject".

Now how can I get the dynamic part :empid in the controller?




how to achieve this.resource() with new this.route() in ember for highly nested routes ?

im in the process of upgrading ember1.x to 3.x and i have an issue with router where it was used this.resource for nested routes and now it is depreciated and changed to this.route

but when it comes to nested route its not working anymore if i futher explain, let say

this.resource( 'parent1', { path: '/' }, function() {

    this.route( 'someroute1', { path: '/' } );
    this.route( 'someroute2', { path: '/someroute2' } );


    this.resource( 'parent11', { path: '/app' }, function() {

      this.route( 'someroute11', { path: '/' } );
      this.route( 'someroute12', { path: '/someroute12' } );

      this.resource( 'parent111', { path: '/:paramid' }, function() {
      this.route( 'index', { path: '/' } );
      this.route( 'someroutewanttogo', { path: '/pathrouteiwanttogo' } 
  );
});

This was before and i was routing to the last route as

this.transitionTo('parent111', id)

this worked perfectly.

then i changed resource to route as below

this.route( 'parent1', { path: '/' }, function() {

    this.route( 'someroute1', { path: '/' } );
    this.route( 'someroute2', { path: '/someroute2' } );


    this.route( 'parent11', { path: '/app' }, function() {

      this.route( 'someroute11', { path: '/' } );
      this.route( 'someroute12', { path: '/someroute12' } );

      this.route( 'parent111', { path: '/:paramid' }, function() {
      this.route( 'index', { path: '/' } );
      this.route( 'someroutewanttogo', { path: '/pathrouteiwanttogo' } 
  );
});

then the route was not found in the route transitionTo() so then i tried to call

this.transitionTo('parent1.parent11.parent111', id );

but this is lost is nowhere as its not triggering controller of parent111 or either children.

what i did wrong in here?




How to disable ember-fastboot after site already loaded locally?

This is related to a post I recently made regarding ember-fastboot and saving a webpage for offline viewing.

I am making a separate post because I believe this is more an ember-fastboot question and isn't specific to the website I am trying to save for offline viewing.

Basically, I am trying to find out how, on the local end, to completely override ember. That is, since I already have open in my browser the rendered page, what does one need to do in order to save the page such that when opened later locally as offline page, the page appears the same way it did when rendered in the first place?

It seems like I am in a paradox. I have a rendered page, with content such as a javascript media player. I save rendered page. I then open the locally saved, rendered page but then the ember javascript kicks in and alters the page, such that the javascript media player no longer loads, due to ember altering a div's class name to specify that the player is not booted! The thing is, once rendered, I don't need ember doing anything, as I am just interested in viewing a frozen copy of the rendered page with no interest in subsequent connections to the rendering server.

Anyway, hope someone can shed some light on this.

Thanks!




How to save a webpage offline that is rendered with ember-cli-fastboot?

I am trying to save a webpage for offline viewing but not exactly having luck.

The page is fairly intricate, as it involves javascript audio and video players, HTML embedded media.

On top of that, when I view the source I noticed ember-cli-fastboot comments and did some reading about it here: https://github.com/ember-fastboot/ember-cli-fastboot. So this ember-cli-fastboot seems to be all about server side rendering which for me I guess defeats the purpose of saving a website offline.

I have tried various Chrome extensions such as Save Page WE, WebScraper. They get me fairly close, with text, images, and the basic structure of the page looking fine, but the flash and JS-based players are not loading.

I also tried downloading the page in Chrome Developer Tools using Save All Resources extension, but that seems to produce similar result to what I get with Save Page WE, namely all text and images are loaded but audio and video players don't load.

Here is an example snippet of code for one of the players:

<div id="area49254180_6" class="component interaction_component float-none clear-none hideSlideshowControls interaction_booted"><div role="status" class="int-prep hidden"><i aria-hidden="true" class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i><br> Loading interaction...</div><div>
<div class="data-field interaction-type">Slideshow</div>
<div class="data-field interaction-init">
<span class="field">jplayer_swf_path</span><span class="value"><a target="_blank" href="https://dvgddacn5gars.cloudfront.net/691v.swf?response-content-disposition=inline%3Bfilename%3D%22Jplayer.swf%22&amp;Expires=2147483647&amp;Signature=BUOmjigHUL9go1MM~SvrLXLDR8gJZzCVKEUrXoUw~49Qn4g54HUK3nQpFpLUD8IXZiuv3ygkyqcxNMdhZg1V2g4DnvIql-tnGGZ2E1Kdyz3c6SIfbNx-LZasBf5M9jvoXFYGqEtugXZV0etgoGrL9CRV0Xnwn~Ee09DCrzdRPLQ_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ">https://dvgddacn5gars.cloudfront.net/691v.swf?response-content-disposition=inline%3Bfilename%3D%22Jplayer.swf%22&amp;Expires=2147483647&amp;Signature=BUOmjigHUL9go1MM~SvrLXLDR8gJZzCVKEUrXoUw~49Qn4g54HUK3nQpFpLUD8IXZiuv3ygkyqcxNMdhZg1V2g4DnvIql-tnGGZ2E1Kdyz3c6SIfbNx-LZasBf5M9jvoXFYGqEtugXZV0etgoGrL9CRV0Xnwn~Ee09DCrzdRPLQ_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ</a></span>
</div>
<div class="data-field interaction-asset">
<span class="field">audio_track</span><span class="value"><a target="_blank" href="https://dvgddacn5gars.cloudfront.net/5fkk.mp3?response-content-disposition=inline%3Bfilename%3D%22L01_Diatonic-Chords-1.mp3%22&amp;Expires=2147483647&amp;Signature=SGmoFTa4sBtiuDqCS0v9A5Qv6y7Q-3PftkRN6Eu3DbxhTqMLbmEhwA4~oXuaRw0BprkB8MbockpY3AhQwEUxWxVOrQE1WO9Wb-riZxHtygYphEpYcbn9eZ4Bp02u-4nM820PsOxqvWJ~-9Fovk7IFu1LAmZ-aG9vWptqPo5Ke-8_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ">https://dvgddacn5gars.cloudfront.net/5fkk.mp3?response-content-disposition=inline%3Bfilename%3D%22L01_Diatonic-Chords-1.mp3%22&amp;Expires=2147483647&amp;Signature=SGmoFTa4sBtiuDqCS0v9A5Qv6y7Q-3PftkRN6Eu3DbxhTqMLbmEhwA4~oXuaRw0BprkB8MbockpY3AhQwEUxWxVOrQE1WO9Wb-riZxHtygYphEpYcbn9eZ4Bp02u-4nM820PsOxqvWJ~-9Fovk7IFu1LAmZ-aG9vWptqPo5Ke-8_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ</a></span>
</div>
<div class="data-field interaction-asset">
<span class="field">images</span><span class="value"><a target="_blank" href="https://dvgddacn5gars.cloudfront.net/5fkj.xxx?response-content-disposition=inline%3Bfilename%3D%22L01_Diatonic-Chords-1.xxx%22&amp;Expires=2147483647&amp;Signature=inxGPaQkl-beyoR2OG8bOSLXCekpyWf4G6XmHq3KCgEV8qWDLJM5-ThWnI9hI~-nh8TtyrqsC8ZNYN3iWh~0U5zrzNfgw~8F96hhNmJuvsRyFWb33~yXyQVjSlBmKbrHd-qxa~tSm00W-ViBnNIMuQw1AVIy8uiZSSWwAiPnCTU_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ">https://dvgddacn5gars.cloudfront.net/5fkj.xxx?response-content-disposition=inline%3Bfilename%3D%22L01_Diatonic-Chords-1.xxx%22&amp;Expires=2147483647&amp;Signature=inxGPaQkl-beyoR2OG8bOSLXCekpyWf4G6XmHq3KCgEV8qWDLJM5-ThWnI9hI~-nh8TtyrqsC8ZNYN3iWh~0U5zrzNfgw~8F96hhNmJuvsRyFWb33~yXyQVjSlBmKbrHd-qxa~tSm00W-ViBnNIMuQw1AVIy8uiZSSWwAiPnCTU_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ</a></span>
</div>
<div class="data-field interaction-init">
<span class="field">initial_json</span><span class="value">[{"imageIndex":0,"time":0,"rect":null}]</span>
</div>
<div class="interaction_title"></div>
<div class="interaction_content Slideshow" style="min-height: 50px; width: 400px;"><div id="ember7214" class="ember-view"><div class="slideshow-jplayer" id="slideshow_player_49254180_6"></div>
<div class="slideshow-player">
  <audio class="player" src="https://dvgddacn5gars.cloudfront.net/5fkk.mp3?response-content-disposition=inline%3Bfilename%3D%22L01_Diatonic-Chords-1.mp3%22&amp;Expires=2147483647&amp;Signature=SGmoFTa4sBtiuDqCS0v9A5Qv6y7Q-3PftkRN6Eu3DbxhTqMLbmEhwA4~oXuaRw0BprkB8MbockpY3AhQwEUxWxVOrQE1WO9Wb-riZxHtygYphEpYcbn9eZ4Bp02u-4nM820PsOxqvWJ~-9Fovk7IFu1LAmZ-aG9vWptqPo5Ke-8_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ"></audio>
  <div class="audio-controls">
    <i class="fa fa-play playpause"></i>
    <i class="fa fa-pause playpause inactive"></i>
    <input id="player-seek" type="range" min="0" max="100" value="0" onchange="">
    <i class="fa fa-retweet loop"></i>
  </div>
</div>
<div class="controls fr hidden">
  <i class="fa fa-arrow-circle-left back"></i>
  <span class="pages">1 of 1</span>
  <i class="fa fa-arrow-circle-right forward"></i>
</div>

<div class="page_container">
  <div class="highlight hidden"></div>
  <div class="image-area"><immg src="https://dvgddacn5gars.cloudfront.net/5fkj.png?response-content-disposition=inline%3Bfilename%3D%22L01_Diatonic-Chords-1.xxx%22&amp;Expires=2147483647&amp;Signature=inxGPaQkl-beyoR2OG8bOSLXCekpyWf4G6XmHq3KCgEV8qWDLJM5-ThWnI9hI~-nh8TtyrqsC8ZNYN3iWh~0U5zrzNfgw~8F96hhNmJuvsRyFWb33~yXyQVjSlBmKbrHd-qxa~tSm00W-ViBnNIMuQw1AVIy8uiZSSWwAiPnCTU_&amp;Key-Pair-Id=APKAIVZN4AJ762UIENTQ"></div>
</div>
</div></div>
<div class="interaction_data" style="display: none;"></div>
</div></div>

Notice in the first div element above, this text: "interaction_booted" in the class name.

This seems to be the key to what is happening. When I save the page and then load it, using one of the methods I mentioned above, I see this in that first div element (corresponding to what I pasted above):

<div id="area49254180_6" class="component interaction_component float-none clear-none hideSlideshowControls"><div role="status" class="int-prep"><i aria-hidden="true" class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i><br> Loading interaction...</div>

So we no longer see "interaction booted" in the class name. So anytime I open saved versions of this page, the javascript seems to be making some sort of check and is then not loading the content, and instead replaces the element along the lines of what you see in the above code snippet.

Now, I am not a developer. I have done some PHP coding and am fairly technical at this stuff for a non dev, but hey I am a guitarist first and foremost and I am definitely out of my technical league trying to figure this out...

Really curious how you experts would go about saving this sort of content for offline viewing, such that all resources are saved offline, with no need for server side rendering. If it requires some custom scripting, I could probably handle it, just need to understand the general idea.

Thanks!




In Ember can you overwrite component functions using the component helper?

Still pretty new to Ember. I am trying to use the component Ember helper to overwrite a function on the component.

My component looks like:

Ember.Component.extend({
  ...
  getValue() {...}
  ...
});

I have another component with a template that looks like:

<div>
  
</div>

I would imagine that this would overwrite the getValue function from the original component, but it does not. Is this possible using this helper to do this? Or am I going about this the wrong way?




emberjs: how to force download video from url

i need to to force download video from video url how it be done

<a href="" download> download </a>

it download all the files but incase of video it start to play in the browser.

Thanks in advance.




Ember not showing foreign key field data

I have four models

//models/exam.js

name: attr('string'),
owner: belongsTo('user'),


//models/question.js

content: attr('string'),
exam: belongsTo('exam')


//models/answer.js

owner: belongsTo('user'),
question: belongsTo('question'),
answer: attr('string'),
remarks: attr('string'),
exam: belongsTo('exam')


//models/user.js

owner: belongsTo('user'),
question: belongsTo('question'),
answer: attr('string'),
remarks: attr('string'),
exam: belongsTo('exam')

I load the models into a route. Then, when I run the following template code,


<p></p>


it shows the output as follows

<frontend@model:question::ember276:5>
<frontend@model:question::ember281:6>
<frontend@model:question::ember286:4>

why is it showing such an code, why not showning the original content?




Deploying Ember JS application in EC2

I would like to deploy ember app in an EC2 ubuntu instance.

  • I have installed tomcat in EC2 ubuntu instance.
  • I have run ember build and generated dist files

I dont know how to make the tomcat run the dist files that is generated during the build. Can someone explain it in a step by step so that I can understand clearly?