mercredi 31 août 2016

Resolving multiple promises at once that have dependencies on each other

I am using ember-async button which will show a spinner until the actions promise resolves.



In my case I can't start the child promises until the parent promise has resolved.

This does not work, the spinner will stop as soon as the parent promise resolves.

actions: {
  save(model) {
    cont promise = model.save();

    promise.then(() => {
      const promises = [];
      model.get('subModels').forEach((subModel) => {
        promises.pushObject(subModel.save());
      });

      return Ember.RSVP.all(promises);
    });

    return promise;
  }
}

How do I keep a long running promise running until all dependent promises have finished, taking into account that some of the promises are dependent on others completing?




Stop pushPayload from triggering automatic fetches

I'm currently manually pushing some data upon initialization of my Ember app using pushPayload. I'm using JSONAPI as the adapter.

When I push it the data (which loads correctly) it contains relationship references to other records that are not yet loaded (or may never load depending on how the user interacts with the page).

If Ember sees something like

{ 
   id: 1,
   type: 'project',
   relationships: 
     jobs: {
       data: [
         { id: [some_id_not_yet_loaded], type: 'job' }, 
         { id: [another_id_not_yet_loaded], type: 'job' }, 
       ]
     },
}

It then is automatically querying /jobs/filter[id]=1,2,..x. It's both unnecessary/not performant to issue this request. I realize this is part of the Ember Data default behavior but I'd like to be able to override it such that the Ember store will still maintain the references to both jobs but only hydrate them when the corresponding project is loaded (or not).




Ember manual url change does not load page

I have an EmberJS application using Coffeescript and Ember 2.7.1.

I redirect the / to /student.

When I open my application, let's say on http://ift.tt/2bDsywu (yes, I need the ~somebody/dist part), it goes to http://ift.tt/2bI1RDT as expected.

I also have other pages, for example /settings. When I manually change the url from http://ift.tt/2bI1RDT to http://ift.tt/2bDsnRE, it doesn't load the page.

I get a Failed to load resource: the server responded with a status of 404 (Not Found) error.

The Settings router is "empty" (I didn't touch it) and the Student router returns now a hard coded json-like data as model. Both of them will fetch data from a server via Ember Data.

Any idea how to fix this?

My router.coffee file:

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

Router = Ember.Router.extend
    location: config.locationType,
    rootURL: config.rootURL

Router.map ->
    @route 'student'
    @route 'settings'
    @route 'statistics'
    @route 'directory'

`export default Router`

My routes/index.coffee file:

`import Ember from 'ember'`

IndexRoute = Ember.Route.extend
  beforeModel: ->
      @transitionTo('student')

 `export default IndexRoute`

My environment.js file:

    /* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'something-frontend',
    environment: environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
      ENV.location = 'hash';
      ENV.rootURL = '/~somebody/dist'
  }

  return ENV;
};




Aurelia version upgrade policy

One thing I'd like to know about Aurelia is if it follows a compatibility-oriented update model similar to the Ember's one; I'm citing from a recent interesting article about Ember:

All the changes made in the 1.x releases are supposed to be backwards compatible, so in theory, you can upgrade from 1.3 all the way up to 1.11 with relatively few issues.

The way they do this is to incrementally deprecate things in the framework that they plan to remove, but they will keep the features (and tests) around for the entire 1.x series or otherwise shim them with compatibility layers. So while you are encouraged to resolve these deprecations as soon as possible, you are given a very long timeframe to do so.

I didn't found anything on the subject, but I discovered that Rob Eisenberg favours Ember above React or Angular, because it shares some of his design principles.

Does anybody knows anything about this?




ember js get multiple checkbox value

My templates:

<form name="spam_list" >
    
    <tr>
        <td></td>
    </tr>
                           
<button >Check All</button>
</form>

My routes:

model(){
        // return 10 spams
    },

My controller:

actions:{
        spamDecide: function(model){
             var isCheck = model.getEach('isCheck');
             console.log(isCheck);
        },

        checkAll: function(model){
            var model = this.get('model');
            model.setEach('isCheck',true);
        },
    }

Currently action checkAll is work fine, set all checkbox into checked. My question is how can I know which checkbox is checked when I manually check them.
For example I set checkbox 1 5 7 is checked, then get the equivalent spam.id with each check?




store.query response expected to be an array but it was a single record

I am making an API call to get the conference rooms that match the profided filters. The response is returning an array, however Ember is giving me the error:

Error while processing route: rooms Assertion Failed: The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use store.queryRecord to query for a single record.

I am using RESTAdapter.

What am I doing wrong?

route:

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.store.query('room', { filter: { option1: 'x', option2: 'y' } }).then(function(rooms) {
        return rooms;
    });
  }
});

Returned by server:

{"rooms":[
    {"id":"1","size":"600","title":"Centennial Room","description":""},
    {"id":"3","size":"1500","title":"Grand Auditorium","description":""}
]
}

Thank you.




Setting up admin views in Ember.js

I'm new to Ember.js and I'm using Ember Simple Auth and I'm having a hard time trying to figure out how to get the current user that is logged in and then checking if the user is an admin so I can display admin only thinks in templates. Currently I am using jwt authentication using Ember Simple Auth Token and a Ruby on Rails backend. Any help in pointing me in the right direction would be great.




Ember template not rendering

I have my rails api to serve the list of tasks as json to the url

http://ift.tt/2bVDTaC

I had defined the routes in ember as

router.js
this.route('tasks',function() {
    this.route('index', {path: ''});
}

I have a template for "http://ift.tt/2bVDTaC"

When i hit the route, its not rendering the template, instead the server response JSON is loaded

Is there any restriction like , the server and ember routes must be different ? If not, how to overcome this ?




Ember vs Angular

What is difference with respect to working/features between Angular & Ember framework on high level?
I have found some similarity as below:

  • MVC Framework
  • Two way data binding
  • Reusable new web component
  • Great support



using sass in ember.js addon

I am developing an addon in ember.js for my new ember app.

I am trying to figure out how to use sass as styles with my addon and make it independent from my app.

Saying that addon uses sass but the app using it dones't necessary has to have ember-cli-sass in its packages.json.

I've tried almost every solution that there is to be found on google, co I come here for the help :)

Lets say my addon name is awesome-tables, so if I put a css file in awesome-tables/addon/styles/addon.css the styles are concatenated into vendor.css as expected, but it doesn't work for sass / scss




mardi 30 août 2016

Stop ember from concatenating model name to adapter's namespace

I have an API that expects a GET request at this URI:

/rooms/500

which will return all of the conference rooms that hold 500 people. The number could differ as it is entered by the user.

I am using Ember.js and my adapter looks like this, hardcoded for testing:

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
   namespace: 'rooms/500',
});

But the model name (rooms) always gets concatenated to the request, making it /rooms/500/rooms, for which there is no endpoint. How can I get Ember to stop changing the namespace?

Thank you.




Ember.js - filtering queries isn't working

I'm building an Ember app and I'm trying to query some data from my database with a filter on it:

this.store.query('game', {filter: {season: season}}).then(function(games) { 
  controller.set('gameList', games); 
}); 

However, this is returning every single game object in the database instead of correctly filtering by season. I think I followed the documentation correctly... are there any obvious mistakes I could have made?

Here's the file: admin.js




How to add integration tests for components defined in an ember-addon

Here is the structure of my ember-addon.

addon/
.. components/
.... my-component/
...... component.js
...... style.less
...... template.hbs   
.. engine.js
.. routes.js
app/  
.. components/
.... my-component/
...... component.js
.. etc ..
tests/  
.. dummy/
.... app/
...... components/
...... controllers/
...... etc ....
.. integration/  
.... components/  
...... my-component-test.js  
.. index.html
.. test-helper.js

The test file tests/integration/components/my-component-test.js:

//tests/integration/component/my-component-test.js
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('my-component', 'my component module description', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs``);

  console.log('This rendered', this.$()[0]);
  assert.ok(false);
});

I link to my addon from app/ as well:

//app/components/my-component/component.js
import MyComponent from 'my-project/components/my-component/component';
export default MyComponent;

Let's say that my component template looks something like this:

<!-- addon/components/my-component/template.hbs -->
<div class="foo"></div>

And let's say that my component's js file looks something like this:

//addon/components/my-component/component.js
import Ember from 'ember'
export default Ember.Component.extend({
    someProperty: 'someValue'
});


I would assume that the output of the console log would be:

<div id="ember234" class="ember-view>
    <div class="foo"></div>
</div>

But unfortunately the console in Qunit comes up with:

<div id="ember234" class="ember-view">
    <!---->
</div>

Is Ember just struggling to find my .hbs template? Other projects seem to do all their component tests with the standard grouping (ie having named component js files and template files rather than component.js and template.js).

http://ift.tt/2cq36gO

This relates to another question I asked, but I thought it more appropriate to continue probing this testing issue here in a separate question.

How does ember-qunit render components in integration testing?




Implement jwplayer on Emberjs

I want to implement jwplayer on an emberjs app, i use bower to install jwplayer and i include it on ember cli build.

app.import('bower_components/jwplayer/jwplayer.js');

The problem is when im trying on the application route to setup the jwplayer:

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

jwplayer.key='t7jmHu1/RAgJaW/NYESUcyMbUjuFcEeBqDTr/Q==';

jwplayer("video").setup({
    file: "http://ift.tt/2bUfbYw"
});

}

Anyone knows how to fix this?




How do you properly configure Spring Security's OAuth2 system to work with EmberJS

I'm creating an EmberJS app wrapped with Cordova alongside a Rest API provided by Spring Boot. Here is my Spring Code:

@SpringBootApplication
@RestController
public class Application extends SpringBootServletInitializer {

...

@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
         // any calls made to the API must be authenticated
         http.antMatcher("/api/**")
            .authorizeRequests()
            .anyRequest().fullyAuthenticated();

         http
            .cors().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("b-api");
    }
}

@Configuration
@EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        // we're hosting a static landing page with Spring so we're removing any security requirements for them
            .antMatchers("/resources/**")
            .antMatchers("/img/**")
            .antMatchers("/*")
            // this is to allow preflight to work but it doesn't seem to be doing the trick...
            .antMatchers(HttpMethod.OPTIONS, "/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest()
            .hasRole("USER");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
        // enable in memory based authentication with a user named "user" and "admin"
            .inMemoryAuthentication()
                .withUser("user")
                    .password("password")
                    .roles("USER")
            .and()
                .withUser("admin")
                .password("password")
                .roles("USER", "ADMIN");
    }
}

@Configuration
@EnableAuthorizationServer
@CrossOrigin(origins = "http://localhost:4200", methods = {RequestMethod.GET, RequestMethod.PUT, RequestMethod.OPTIONS, RequestMethod.HEAD}, allowedHeaders = "**")
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("my-trusted-client")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "ROLE_USER")
                .scopes("read", "write", "trust")
                .resourceIds("b-api")
                .accessTokenValiditySeconds(600);
    }
}

}

The frontend code is using EmberJS with ember-simple-auth's oauth2 authenticator.

Currently when I try and authenticate through the frontend Chrome's devtools throw this error:

XMLHttpRequest cannot load http://localhost:8080/oauth/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

Any ideas regarding what I'm missing would be appreciated. Thanks :)




How does ember-qunit render components in integration testing?

Here is a basic component / integration test for ember-qunit.

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

moduleForComponent('my-component', 'TODO: put something here', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs``);

  console.log('This is the rendered element', this.$()[0]);
  assert.ok(false);
});

I have an ember-addon with a directory structure like this:

addon/   
app/  
tests/  
.. integration/  
.... components/  
...... my-component-test.js

How does ember determine where is?

This is kind of in the same vein as this:
How does Ember-CLI precompile templates?




How to load a component template in component integration tests - EmberJS

Here is a verbatim copy of an EmberCLI generated component test after this command:
ember generate component-test my-component

my-component-test

//tests/integration/components/my-component-test.js
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

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

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs``);

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

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

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

my-component has a template looking something like this:

<div class="foo">
    
       <span>item.name</span>
    
</div>

However, if I change the my-component-test to search for elements inside of the compiled component, I have no luck finding them.

this.set('myArr', [{name: 'John'}]);
this.render(hbs``);
this.$('.foo').length; // zero

Are templates not automatically looked-up and included? If so, how can I include my template without re-writing the whole thing?

Similar:
Integration test for component containing a component

Guide: http://ift.tt/2bOXnfb




Ember run later in coffeescript not working correctly

I am pretty new to Ember so I am totally stumped by this. The run later appears to work however it seems to ignore the fact that it is supposed to only run once every 5 seconds to update the status. Also because of this code the page never actually gets rendered. I must be doing something wrong in this code:

App.ServersController = Ember.ArrayController.extend(

    startWatchingStatus: () ->
        controller = @
        controller.getServers()
        Ember.run.later(controller, () ->
        controller.startWatchingStatus()
        , 5000)




ember cli and autodesk forge

I am creating a Autodesk viewer using the Autodesk forge API and Emberjs Framework. I have the viewer working but I want to add extensions to edit the model and provide more graphic information. Using ember cli how would you load the extension code? I currently have the code placed in the vendor folder and have it mapped in the ember-build file. I than load the viewer and extensions in the controller using the following code:

var config3d = {extensions: ['ExtensionName']}; viewerApp.registerViewer(viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D, config3d);

Do I not have the file in the right folder or am I not calling the extension properly at the registerViewer function?




How to render conditional actions in EmberJs?

How can I render actions based on a condition?

<a href="#" ></a>




EmberJS 2.7 How to restructure/reformat/customize data returned from the store

I have what I think is a very simple issue, but I just don't get how to do this data manipulation. This sadly didn't help, even though it's the same pain I am feeling with Ember.

Here is a route:

route/dashboard.js:

import Ember from 'ember';

export default Ember.Route.extend({
    // this is for testing, normally we get the data from the store
    model: function() {
        return this.get('modelTestData');
    },

    modelTestData: [{
        name: 'gear',
        colorByPoint: true,
        data: [
            {y: 10, name: 'Test1'},
            {y: 12, name: 'Test2'},
            {y: 40, name: 'Test3'}
            ]
    }],

});

The structure of the 'modelTestData' object has to be exactly like that as it is passed into a child component that needs it structured that way.

I can easily get my data from the API and put it into the model:

model: function() {
    return this.store.get('category');
},

But then I need to restructure it...but how?

I have to somehow iterate over the categories collection and extract parts of data from each record to replace the 'data' part of the modelTestData object.

So I have 3 issues I am completely stumped on:

  1. How to 'get at' the attributes I need from the model?
  2. How to structure them as an array of objects with 'y' and 'name'?
  3. How to assign that structure to 'data' instead of it being hardcoded?

Categories is a JSONAPI object like this:

{
   "data":[
      {
         "id":"1",
         "type":"categories",
         "attributes":{
            "name":"Carrying system",
            "total-weight":{
               "grams":"100.0",
               "ounces":"0.0"
            }
         }
      },
      {
         "id":"2",
         "type":"categories",
         "attributes":{
            "name":"Shelter system",
            "total-weight":{
               "grams":"10.0",
               "ounces":"0.0"
            }
         }
      }
   ]
}

I need to iterate this structure and grab the category.attribute.name and the attribute.total-weight.grams [ignore ounces, it's not used].

I need to map the grams value to 'y' and the name to 'name' in modelTestData.

Note that the category data is used in other routes for other purposes exactly as returned by the API. So I don't want to change the model structure itself, or what the API returns...that will break other parts of the app that do use 'category' in its original structure.

This is a specific use case that this route needs to massage the data to pass to the child component as per the structure of modelTestData.

I also wonder whether this data manipulation task belongs in a route?

Should I somehow do this in the serliazer adapter, creating a new structure as say 'categoryWeights' so I can then do:

model: function() {
    return this.store.get('categoryWeights');
},




lundi 29 août 2016

EmberJS 2.7 passing data down into a component is failing

I have read many questions on this problem, but none of them seem to have the issue I have here.

I am using a third-party component (ember-highcharts) which works great except for this snag.

I have a route called dashboard. For now this route is just using dummydata, it is not using the store. This servers to illustrate the problem.

templates/dashboard.hbs

<div>
 <-- NOTE this logs the object to the console as expected
 <-- my component, see below
</div>

routes/dashboard.js

import Ember from 'ember';

export default Ember.Route.extend({
    // this is for testing, normally we get the data from the store
    model: function() {
        return this.get('modelTestData');
    },

    setupController: function(controller, models) {
        this._super(controller, models);
        controller.set('model', models);
    },

    modelTestData: [{
        name: 'gear',
        colorByPoint: true,
        data: [
            {y: 10, name: 'Test1'},
            {y: 12, name: 'Test2'},
            {y: 40, name: 'Test3'}
            ]
    }],

});

templates/components/summary-chart.hbs

  <-- NOTE this logs '**undefined**' to the console as expected


components/summary-chart.js

import Ember from 'ember';

export default Ember.Component.extend({

  summaryOptions: {
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: 'Total weight of gear in each category'
    },
    tooltip: {
        pointFormat: '<b>{point.percentage:.1f}%</b> of {series.name}'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: false
            },
            showInLegend: true
        }
    }
  }

});

Why is the model undefined and not being passed into summary-chart component? The chart renders (you can see the title) but of course without the data being plotted, because the model is undefined.

If I change the component to this, so the data is 'local' to the component, then the chart is rendered with the data points:

templates/components/summary-chart.hbs



components/summary-chart.js

import Ember from 'ember';

export default Ember.Component.extend({

  summaryOptions: {
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: 'Total weight of gear in each category'
    },
    tooltip: {
        pointFormat: '<b>{point.percentage:.1f}%</b> of {series.name}'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: false
            },
            showInLegend: true
        }
    }
  },

  summaryData: [{
    name: 'gear',
    colorByPoint: true,
    data: [
        {y: 10, name: 'Test1'},
        {y: 12, name: 'Test2'},
        {y: 40, name: 'Test3'}
        ]
  }]

});

Note that 'summaryData' is an identical data structure to 'modelTestData', so the chart understands how to plot it.

What I do not understand is why the route/controller combination is NOT passing the model down to the child component.




Access to Ember component data from within component template

I'm trying to figure out Ember.js so that I'm not manually manipulating the DOM, and using handlebars instead.

I'm trying to get access to the component's data within the component's template so that I can iterate over the data and build a table. If this isn' the Ember way, please let me know. I don't have the data set in a model, store, or in the route. Everything is done in the component "issue-data".

Here is the component and its template:

import Ember from 'ember';

export
default Ember.Component.extend({
  runAll: null,
  csvData: null,
  initTable: function() {
    function buildTable() {
      var csvFile;
      Ember.$.ajax({
        url: 'open_issues_data/open_issues_data.csv',
        dataType: 'text',
        async: false,
        success: function(response) {
          csvFile = response;
        },
        error: function(err) {
          console.log(err);
        }
      });

      Papa.parse(csvFile, {
        complete: function(results) {
          csvFile = results.data;
          this.csvData = csvFile;
        }
      });

      /* Uncomment when ready to implement filter
        options = {
          valueNames: ["issue_number", "customer_id", "date_reported", "location"]
        };

        var myList = new List("table-div", options);
      */
    }
    buildTable();
  }.on('didInsertElement'),

  didInsertElement() {
    this.runAll = Ember.run.later(this, function() {
      this.initTable();
      this.runAll = Ember.run.later(this, this.runAll, 60000);
    }, 60000);
  },

  didDestroyElement() {
    Ember.run.cancel(this.runAll);
  }
});
<div id="table-div">
  <input class="search" placeholder="Filter by your input">
  <button class="sort" data-sort="issue_number">Sort by Issue #</button>
  <table id='data-table' class='table table-striped table-bordered'>
    <tbody id='table-body' class="list">
      
      <tr>
        
        <td></td>
        
      </tr>
      
    </tbody>
  </table>
</div>


Here is the template for the route:

<h2>Open Issues Data</h2>






Ember model/route/template setup

This would be easy to do with regular JS/AJAX, but I am trying to learn and do this the Ember way (v2.6):

I have a URL /dates and on this page there are two calendars. On page load, a request is made to the server to get which date to pre-select in calendar 1. The response looks good, but the date is not appearing in the template.

/templates/dates.hbs:

Preselect: []  //this is outputting:  Preselect: []

/routes/dates.js:

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.get('store').findAll('my-date').get('firstObject');
  }
});

/models/my-date.js:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({
    preselect: attr() 
});

Server response:

{"myDates":{"id":1,"preselect":"2016-10-02"}}

There will be more requests for calendar 2 later, but I'm stuck on calendar 1.

Why is the model data not appearing on the page? There are no errors in ember inspector. The model does appear in ember inspector with the proper data.

Thank you.




Communicate between php session to ember-application

I build a website based on cms(wordpress) and on his website it has some sort of form, when you successfully fill out the inquiry it will going to redirect to subdomain which is the ember app

my question is how can i exactly communicate the php session to ember-app? if your going to ask me why i build a seperate app for that is because there's a lot of functionality i want to add eg(sms verification,dashboard and so on) which is not possible to wordpress




passing json data to a ember router

I am trying to pass data to the route through an json file.

app/templates/dashbord.js



app/routes/dashboard.js

import Ember from 'ember';

export default Ember.Route.extend({

  model() {
    return $.getJSON( "app1.json");
 },
});

public/app1.json

[
  ['Task', 'Hours per Day'],
  ['Work', 11],
  ['Eat', 2],
  ['Commute', 2],
  ['Watch TV', 2],
  ['Sleep', 7],
];

when i am trying to do like this no output is displaying on browser why? thanks in advance.




dimanche 28 août 2016

Ember: Build Error Unexpected token

I am following tutorial try codes below

controller index.js

import Ember from 'ember';

export default Ember.Controller.extend({
    emailAddress: '',

    isValid: Ember.computed.match('emailAddress', /^.+@.+\..+$/),
    isDisabled: Ember.computed.not('isValid')

    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', '');
        }
    }
});

index.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">
            
        </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>
    
    <div class="alert alert-success"></div>
    

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

What I expected is If I click on the button, the saveInvitation action is called and shows an alert box, sets up a responseMessage property, and finally deletes the content of emailAddress.

However, I got an error like this

Build error

library-app/controllers/index.js (in /Users/Cy/Desktop/ember/library-app/tmp/babel-input_base_path-oMvwkQCG.tmp/0)

The Broccoli Plugin: [Babel] failed with:
SyntaxError: library-app/controllers/index.js: Unexpected token (9:1)
    isDisabled: Ember.computed.not('isValid')

    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')}`);

Anybody could let me know what causes the error and how to fix it? Thanks




ember - How to create a user for those who use facebook login

I'm still quite new to ember and I've created a custom user signup/login system with Firebase as the backend and the torii add-on for user authentication. I've also looked around and there's plenty of tutorials/info on how to incorporate facebook login, which I have done, however that's all it does for me right now... Log you in and give you a session, but doesn't create a user in the users database that I've set up.

Whereas if you use the custom login, it creates a user model and saves it in the users database that you can retrieve. As of right now if you try to retrieve users from the database who are logged in through facebook, it gives an error since they are not in the database, even though they have a uid assigned by firebase.

So basically right now there seem to be two different kinds of users in my app, the ones who use the custom sign up and are in the users table/database, and users who sign in using facebook, but can't really do anything but log in. How do I create a user when someone signs into my app for the first time using facebook so that they have the same capabilities as someone who uses the custom sign up?

So far I have the facebook SDK loaded in an initializer and I have a button that triggers the sign in action in a controller that passes in "facebook" as the provider.

import Ember from 'ember';

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

    actions: {
      signIn: function(provider) {
        const email = this.get('email');
        const password = this.get('password');
      this.get('session')
      .open('firebase', { provider: provider, email: email, password: password})
      .then(function(data) {
      });
    },

      signOut: function() {
        this.get('session').close();
      }

});




Ember.js - localhost:4200 looks for index.html

I just created a new ember app and I'm having trouble getting started. I created a new route: index, and for a while, localhost:4200 was correctly loading index.hbs in my app/templates folder. For some reason, now when I load localhost:4200, it's looking for an index.html file. Here's the error:

Error: ENOENT: no such file or directory, stat '/home/tom/http://ift.tt/2brQu8u

I'm not really sure what's causing this. I haven't made any chances to my router. Does anybody know why it's looking for this file instead of just loading the index route?

Thanks.




Ember: how to make one item binding instead of valueBinding="this" in list

This code for all items works well:

 
                <li>
                    <p>
                        <span class="index">. </span>
                        <span></span>
                    </p>
                    <div class="chart">
                        
                          
                        
                        
                          <div class="no-results">No data.</div>
                        
                    </div>
                </li>


But I want to do the same for one item in content.Questions. E.g.:

 <li>
                        <p>
                            <span class="index">.</span>
                            <span></span>
                        </p>
                        <div class="chart">
                            
                              
                            
                              <div class="no-results">No data.</div>
                            
                        </div>
</li>

This doesn't work. What should I write instead?




Attempted to handle event `pushedData` on

I have a basic crud app for blog posts.This error throws up in the console.When I delete a post.But the post gets deleted from the database and from the ember data.I searched for similar questions and none of the answers solved the issue.I use JSONAPIAdapter for the crud actions.

deletePost:function(id){
  var self = this;
  this.get('store').find('post', id)
    .then(post => post.destroyRecord())
      .then(() => self.transitionToRoute('posts'));
}

I use nodejs as backend and mysql as db.After deleting the record I send a response like this res.status(204).end();




nested rails api with ember js (beginner)

First time poster and extremely new to ember js,rails and would describe myself as a beginner programmer.

I am currently using a nested rails api(and for the moment it cant be changed).It follows a pattern of:

   - apiHost/businesses returns all businesses
   - apiHost/businesses/business_id returns the business with that id **
   - apiHost/businesses/business_id/prices returns the prices in the business
   - apiHost/businesses/business_id/prices/prices_id returns the price with the id **

The ** shows the link which a PUT request can be sent to.

I am really struggling of finding a way to accesses the nested elements and from research ember js isn't a fan of nested resources.

I have come across a some websites which look promising but I just cannot seem to get it to work:http://ift.tt/1mRTsCM (maybe my implementation is incorrect or code when doing return....) or I'm not sure of how to implement it Ember JS: Nested api routes

I have added my business model and the price model below.

export default DS.Model.extend({
  address: DS.attr('string'),
  description: DS.attr('string'),
  price: DS.hasMany('price')
 });

export default DS.Model.extend({
  cost: DS.attr('string'),
  description: DS.attr('string'),
  business:DS.belongsTo('business')
});

Any help would be greatly appreciated, the first link looks to be promising and perhaps the simplest solution for me.

I am currently using ember cli 2.7

Thank you.




samedi 27 août 2016

Ember Lighting Deploy Strategy - S3 NoSuchBucket error

Im deploying to S3 using ember-cli-deploy-lightning-pack. Ive followed various posts and screencasts setting this up.

on S3 i have a new bucket called emberdevlocal with nothing in it.

this is the snippet i have in my deploy.js file

  if (deployTarget === 'dev') {
ENV.build.environment = 'development';
ENV.redis.url = process.env.REDIS_URL || 'redis://0.0.0.0:6379/';
ENV.s3.bucket = 'emberdevlocal.s3.amazonaws.com';

}

I have my region set to

ENV.s3.region = 'us-west-2';

I have currently set the bucket permissions to wide open to make sure there is nothing going on there.

When i run the deploy it fails about half way through.

it sets the domain correctly

      Endpoint {
    protocol: 'https:',
    host: 's3-us-west-2.amazonaws.com',
    port: 443,
    hostname: 's3-us-west-2.amazonaws.com',
    pathname: '/',
    path: '/',
    href: 'http://ift.tt/1omcMWy',
    constructor: [Object] },
 region: 'us-west-2',
..........etc

its doing a PUT to

_header: 'PUT /emberdevlocal.s3.amazonaws.com/...........

I have the correct Keys being passed.

I just cant figure out why its timing out when trying to connect to the bucket.




vendredi 26 août 2016

Array values are not getting reflected while rebinding in EmberJS

I have an array (['Name1','Name2','Name3']) which I am populating at page Load. Now at button click, I want to assign some other values to that array and populate the same like

App.myArray = ['Name4','Name5','Name6'] 

But it is not reflected.

Complete code

<!DOCTYPE html>
<html>
   <head>      
      <script src="http://ift.tt/1H1Z8nj"></script>
      <script src="http://ift.tt/13wBVXk"></script>
      <script src="http://ift.tt/1H1Z8Uo"></script>
      <script src="http://ift.tt/1LNmMn9"></script>
      <script src="http://ift.tt/1H1Z8nl"></script>
      <script src="http://ift.tt/1e1uqGJ"></script>
   </head>
   <body>

      <script type="text/x-handlebars">
         
      </script>


      <script type="text/x-handlebars" data-template-name="index">
      <button >Click Here</button>
         <ul>

                           
               <li></li>
            
         </ul>
      </script>

      <script type="text/javascript">
         var App = Ember.Application.create()

         App.myArray = ['Name1','Name2','Name3']         

         App.IndexRoute = Ember.Route.extend({

            actions: {

               ClickFn: function() {

                  App.myArray = ['Name4','Name5','Name6'] 
                  console.log(App.myArray) ;               
               }
             }
         });

      </script>
   </body>
</html>

The current situation is

enter image description here

I am looking for the output should be when button click

enter image description here




Loading Promise in Handlebars templates based on volatile computed property

I'm building an asynchronous component for a sidebar that lists people you may know, a result set from an API.

The code below works to add these items to the page as they become available to the store. When the user logs out, I call unloadAll(), however, my recommendations computed property is volatile() so it's not cached and will populate with new entries for the next user (or the same) that logs into the application instance.

// app/services/invite.js

recommendations: Ember.computed(function() {
  return this.get('store').findAll('recommendation');
}).volatile(),

// app/templates/components/people-you-may-know.hbs


  


// app/components/people-you-may-know.js

export default Ember.Component.extend({
  invite: Ember.inject.service()
})

I think I need a new computed property like below, but this is where I'm struggling with blank pages and infinite loops.

reducedRecommendations: Ember.computed('recommendations', function()
  return this.get("recommendations").slice(0, 10);
}),


  





ember application.hbs page not render other page

Ember CLI version 2.7.0

In templates folder I created two files, application.hbs and post.hbs
application.hbs

<h2 id="title">balabala</h2>


post.hbs

<h3>I am from post.hbs</h3>

I expect "balabala I am from post.hbs" shows in browser, however I can only see "balabala".
Anybody could help? Thanks.




How emberjs function is invoked?

I want to understand how the function in plugin is invoked.

Here's the code snippet from discourse-adplugin

export default Ember.Component.extend({
  ...
  _initGoogleDFP: function() {
    var self = this;
    loadGoogle(this.siteSettings).then(function() {
      ...
    });
  }.on('didInsertElement'),
  ...
});

There's no mention that the _initGoogleDFP function is evidently invoking by somebody but it's somehow invokes from guts of emberjs.

What is the principles of initialising emberjs components? How _initGoogleDFP is invoking by emberjs?




How to give a route a model that contains both sides of hasMany and belongsTo relationship?

I have successfully managed to get this rather ember-unfriendly API result into a parent/child pair of models called 'connector' and 'pin', where the connector is the parent and an array of pins is the children. I have a hasMany('pin') on the connector model and belongsTo('connector') on the pins.

{
    "Connector" : {
        "ConnectorID" : "2015-11-30T16:34:34.217",
        "ConnectorName" : "D38999/20WA98SN"
    },
    "Pins" : [{
            "ConnectorID" : "2015-11-30T16:34:34.217",
            "PinName" : "A"
        }, {
            "ConnectorID" : "2015-11-30T16:34:34.217",
            "PinName" : "B"
        }, {
            "ConnectorID" : "2015-11-30T16:34:34.217",
            "PinName" : "C"
        }
    ]
}

So far, all is well, I think. I am now faced with getting all of the data from both to appear on a route called 'connector'. I can't quite wrap my mind around how to chain the promises so that I can get both

this.get('store').findRecord('connector', params.connector_id);
and 
this.get('store').findRecord('connector', params.connector_id).findAll(???);

It seems like I am fighting an up-hill battle on this relationship. I wish I could just get Ember to treat the array of pins as it would any other singular data type and get/save the data with the record. Am I think of this correctly?




Ajax - "Access-Control-Allow-Origin" error in ember.js

I would like to know your opinion on the issue in this simple code in ajax, which has the problem Access-Control-Allow-Origin, already tried several ways defenir the ember "Access-Control-Allow-Origin": "* "but without success, so I wonder if someone with the same problem found a solution.

I use the url address 'localhost: 4200' and already tried with a subdomain of 'firebase' in both cases the error was always the same.

The ajax request:

import Ember from 'ember';
import { isAjaxError, isNotFoundError, isForbiddenError } from 'ember-ajax/errors';

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

 code() {

        var cliente = '***';
        var redirectUri = 'http://localhost:4200/teste';
        var client_secret = '***';
        var code = '***';
        var grant_type = 'authorization_code';
        var data =
            "client_id=" + cliente +
            "&redirect_uri=" + encodeURIComponent(redirectUri) +
            "&client_secret=" + client_secret +
            "&code=" + code +
            "&grant_type=" + grant_type;

        this.send('post', data)

    },

    post(data) {

        this.get('ajax').post("http://ift.tt/1cWYSBC", {
            method: 'POST',
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Content-Type": "application/x-www-form-urlencoded",
            },
            data: data,
            dataType: 'JSON',

        });
      }, 
   }});`

My content Security Policy:

contentSecurityPolicy: {
        'connect-src': "'self' http://localhost:4200 http://ift.tt/1ymbsZQ http://ift.tt/1cWYSBC",
        'child-src': "'self' http://localhost:4200",
        'script-src': "'self' 'unsafe-eval' https://login.live.com",
        'img-src': "'self' http://ift.tt/2bqnwQj http://ift.tt/2bn4gGK http://ift.tt/1ASonEP http://ift.tt/11DnTic https://www.gstatic.com",
        'style-src': "'self' 'unsafe-inline' ",
    },

The error is:

XMLHttpRequest cannot load http://ift.tt/1cWYSBC. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.




Queueing save requests

For example, a user keeps hitting a key when inside a textbox, and a save request is sent to the server to save the value.

Postponing consequent events by debouncing doesn't work because each keyUp is run in a new Run loop, unlike holding the key down a long time and entering characters that way.

So the question is: what's the most Ember Way approach to A) wait for a request to complete before sending a new one, to ensure an older value doesn't overwrite a newer value, and B) ensure that at least the very last request is sent, saving the most current user-entered value.

UPDATE:

After poking around for a bit, seems like a simple debounce is the only way I can accomplish what I wanted to:

  keyUp: function(e) {
    Ember.run.debounce(this, this.saveFieldValue, 2000);
  },
    
  saveFieldValue: function() {
    const field = this.get('field');
    field.save();
  },

One important thing that I missed initially, which caused my saves to run each time a key was pressed, as opposed to once per debounce period, was that the function passed into the debounce method has to be named. Factoring out the save code and passing the reference to the function did the trick of saving a maximum of one times in a 2 second interval.

If you have a better "auto-save" approach, please post your answer here.




How to display comma seperated list into table in EmberJS?

Ok, I have Array [ "1,john", "2,jane", "3,zack" ]

At present it is displayed as enter image description here

I want to display as

enter image description here

How to to this

My code

<!DOCTYPE html>
<html>
   <head> 
      <script src="http://ift.tt/1H1Z8nj"></script>
      <script src="http://ift.tt/13wBVXk"></script>
      <script src="http://ift.tt/1H1Z8Uo"></script>
      <script src="http://ift.tt/1LNmMn9"></script>
      <script src="http://ift.tt/1H1Z8nl"></script>
      <script src="http://ift.tt/1e1uqGJ"></script>
   </head>
   <body>

      <script type="text/x-handlebars">
         
      </script>


      <script type="text/x-handlebars" data-template-name="index">

      <table>       
            <tr>
                <th>Id</th>
                <th>Name</th>
            </tr>
            <tr>
                
                <td></td>
            
            </tr>
      </table>  

      </script>

      <script type="text/javascript">
         var App = Ember.Application.create()         
        var someArray = [ {
                        'id':1,
                        'name':'john'
                    },{
                        'id':2,
                        'name':'jane'
                    },{
                        'id':3,
                        'name':'zack'
                    }];

        App.testData = someArray.map( function( el )
                    { 
                       return el.id + ',' + el.name; 
                    }); 
      </script>
   </body>
</html>




Ember can't use data from store

Hey so im having a problem using ember-data and can't seem to find the solution anywhere. Essentially the problem is that I am passing an object that contains 3 objects which each contain on array of objects (which are a a different model). I know that the backend is passing the data correctly because I can see it in the network tab of the console:

network tab

Here is what 'app/routes/dashboard.js' looks like:

    import Ember from 'ember';

    export default Ember.Route.extend({
        model: function() {
            var tmp = this.store.findQuery('series', {view: 'dashboard'});
            console.log(tmp);
            return tmp;
        },

        setupController: function(controller, models) {
            controller.set('model', models);
        }
    });

Heres what my 'app/serializers/application.js' looks like:

      import DS from 'ember-data';

      export default DS.JSONSerializer.extend({
         primaryKey: '_id'
      });

And this is what the series model looks like:

    import DS from 'ember-data';

    export default DS.Model.extend({
        awesome: DS.hasMany('video'),
        boring: DS.hasMany('video'),
        funstomp: DS.hasMany('video')
    });

And in the video model I added: 'series: DS.belongsTo('series')'. But when I try to print out the model in the dashboard controller (ie. console.log(this.get('model'));) all I get is this:

log

As you can see I can't seem to find the awesome/boring/funstomp objects anywhere. And the content is just an empty array, so not sure where anything is. Any help is greatly appreciated, thanks.




Not able to bind the array to table in EmberJS

I am new to EmberJS. I am trying to populate the record from here

The typical JSON looks as under

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]

My code is as under

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs displaying list of items</title>
      <!-- CDN's-->
      <script src="http://ift.tt/1H1Z8nj"></script>
      <script src="http://ift.tt/13wBVXk"></script>
      <script src="http://ift.tt/1H1Z8Uo"></script>
      <script src="http://ift.tt/1LNmMn9"></script>
      <script src="http://ift.tt/1H1Z8nl"></script>
      <script src="http://ift.tt/1e1uqGJ"></script>
   </head>
   <body>

      <script type="text/x-handlebars">
         
      </script>


      <script type="text/x-handlebars" data-template-name="index">
      <button >GetData</button> 
          <table>         
            <tr>
              
                <td></td><td></td>
              
            </tr>         
        </table>

      </script>

      <script type="text/javascript">
         var App = Ember.Application.create()  


         App.IndexRoute = Ember.Route.extend({
         //defining the action for the button click event
            actions: {

               GetUserRecords: function() {

                  App.userData = [];

                  $.ajax({
                            type: "get",
                            url: "http://ift.tt/1n31l1Y",
                            cache: false,
                            data: {},
                            async:   false,
                            success: function (data) {                                        

                                App.userData = data;
                                console.log(App.userData);  
                            },
                            error: function (err) {               
                                alert(err);
                            }
                        });                   
               }
             }
         });

      </script>
   </body>
</html>

In the console.log(App.userData) i am able to find the arrays

enter image description here

But not able to bind it to the table.

Please help.

Many thanks in advance.




Why is __ember_meta__ getting added to my vanilla javascript ember-data property?

I have a model that has an attribute I define as follows:

aux: Ember.DS.attr()

So there's no transformation going on. And when I first load the model, when I do a model.get('aux'), the result is a vanilla javascript object.

But somewhere along the line my application is doing something that adds a bunch of extra properties to the object like __ember_meta__. This is interfering with my attempt to recursively clone the object, because it enters an infinite loop.

I'm not too concerned about my infinite loop problem, but rather I'd like to understand under the hood what I'm doing that's causing Ember to transform my vanilla javascript object.

It's not an Ember.Object instance, at least according to Ember.Object.detectInstance(aux).




call controller from model ember js

I am new to ember and How can I call controller from model.

structure

ember
-source
--controllers
---controller1(method1)
--models
---model1 --(Call controller1.method1)
--routes
--views
--router.js
--appname-app.js

I tried these ways

var subs= AppName.controller1.method1();



var cd = Soni.controller1.create(); 
var subs = cd.method1();



var controller = $(this).get('controllers.controller1');
var subs = controller.method1();

Error: ember.min.js:205 Uncaught TypeError: AppName.controller1.method1() is not a function

Where exactly am I doing wrong?




What is the difference between returning a Mirage.Response object vs returning a raw JSON object through Mirage?

I am trying to build an EmberJS test server in the browser. I have an API call to "myApiMethod", from which I am trying to GET a JSON object. While trying to test the response from a specific method I found out that that I can either return a raw json object, or wrap it in a Mirage.Response object. Since I wanted the mock server's response to be reflective of the real world, I wasn't sure which of the two was a better idea.

What I wanted to know was the functional differences between the following two chunks of code that I have in my Mirage's config.js:

Version 1:

    this.get('/myApiMethod', function(param1, param2){
        var jsonObject = myFunctionThatReturnsJson(param1, param2);
        return jsonObject;
    });

vs.

Version 2:

    this.get('/myApiMethod',function(param1, param2){
        var jsonObject = myFunctionThatReturnsJson(param1, param2);
        return Mirage.Response(200, {}, jsonObject); 
    });




Qunit _initProperties is not a function

I've run into some strange behavior here and wanted to see if anybody knew why it occurs. I've written a simple Ember QUnit test and want to share some data between each test, just to reduce clutter.

Test

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

let shared = {}
shared.stardardData1 = { id: 1 }
shared.stardardData2 = { id: 2 }

moduleFor('controller:foo', 'description', {
    beforeEach() { ... }
    afterEach() { ... }
}

test('should do things', function () {
    let myGroup = [shared.standardData1, shared.standardData2];
}

A couple things here:

  • I'm getting an error _initProperties is not a function
    • The error goes away when I remove the shared stuff
    • The error persists if I add the shared stuff between the moduleFor and the test
  • I want to be able to share variables defined in either the beforeEach or globally
  • I've tried doing something like let a = 1 in the beforeEach, but can't seem to reference them in the test itself

I noticed that the QUnit docs say that they've eliminated globals. Could that be playing a role in this? http://ift.tt/2bm1W2D

PS: It would be nice to have something that set up the module just once instead of every time




Controller fails to be called

I have recently started learning ember.js and for some reason i cant get my controller to be called

App = Ember.Application.create();

App.Router.map(function() {
  this.route('about');
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return ['red', 'yellow', 'blue', 'pie','koala'];
  }
});

App.IndexController = Ember.Controller.extend({
    sortedModel : function(){
        alert("this works");
    }
});

app.js

<script type="text/x-handlebars" id="index">
    <ul>
    
      <li></li>
    
    </ul>
  </script>

its probably something really stupid but for the life of me i cant seem to see it, i followed the tutorial to the letter and cant continue without it




what is 'this' really represent in emberJS framework?

I'm really new in emberJS,I see many 'this.' in the official Guides . In ember Object model I know 'this.' represent the object itself,such as follow:

var obj = Ember.Object.extend({ baz: {foo: 'BLAMMO', bar: 'BLAZORZ'},

something: Ember.computed('baz.{foo,bar}', function() { return this.get('baz.foo') + ' ' + this.get('baz.bar'); }) });

this means obj itself,but in other case,such as models like follow:

app/routes/application.js export default Ember.Route.extend({
model() { this.store.push({ data: [{ id: 1, type: 'album', attributes: { title: 'Fewer Moving Parts', artist: 'David Bazan', songCount: 10 }, relationships: {} }, { id: 2, type: 'album', attributes: { title: 'Calgary b/w I Can\'t Make You Love Me/Nick Of Time', artist: 'Bon Iver', songCount: 2 }, relationships: {} }] }); } });

what is 'this' really represent?




Ember - abort the route and reload the route with same model

In my ember app, when the user clicks the Back button of browser,I need to stop the transition (whereever it might take me as per Ember history) and reload the same url with same model. Have tried the below code, but doesnt seem to work:

search-route.js

var route = Ember.route.extend({
   actions:{
      willTransition: function(transition){
         if(this.controller.get('order') === 1){
             transition.abort();
             this.transitionTo('search',model)
         }
      }
    }
})

This doesnt seem to work and gives error about query params. So, i looked for what is there in transition object. Saw that as soon as I enter this code, the object transition contains prop queryParams but with the old values, not the current URL one. But there is another prop - transition.intent.preTransitionState.fullQueryParams which contains the current URL query params. Would that be used here somehow.

I looked for solutions and someone also suggested to put in this.refresh(), but also didn't work.




jeudi 25 août 2016

ember.js and firebase - unable to sign up user

I'm trying to get a user sign up working on my ember app using firebase as the backend. I'm using the torii add-on for user authentication and am just trying to test it out. However when I try to sign up a user I get the following error: Uncaught TypeError: n.default is not a constructor

This is how my route looks at routes/index.js:

import Ember from 'ember';
import Firebase from 'firebase';

export default Ember.Route.extend({
  actions: {
    signUp: function(){
      var controller = this.get('controller');
      var firstName = controller.get('firstName');
      var lastName = controller.get('lastName');
      var email = controller.get('email');
      var password = controller.get('password');
      var ref = new Firebase("http://ift.tt/29z2EHE");
      var _this = this;

    ref.createUser({
      email    : email,
      password : password
      }, 
      function(error, userData){
        if (error) {
          alert(error);
        } else {
          _this.get('session').open('firebase', {
            provider: 'password',
            'email': email,
            'password': password
          }).then(function(){
            var user = _this.store.createRecord('user', {
              id: userData.uid,
              firstName: firstName,
              lastName: lastName
            });

            user.save().then(function(){
              _this.transitionTo('protected');
            });
          });
        }
      });
    }
  }
});

My template at templates/index.hbs:

Signup here: <br>

<br>
<br>
<br>
<br>
<button > Sign Up </button>

and my user model:

import DS from 'ember-data';

export default DS.Model.extend({
  firstName: DS.attr(),
  lastName: DS.attr()
});

I'm really not sure where I'm going wrong. I've pretty much followed this guide: http://ift.tt/2bl6PsX, except I'm just focusing on the sign up and putting it all in the index for simplicity.




Ember ember-simple-auth override routeIfAlreadyAuthenticated in application route

How do you override the routeIfAlreadyAuthenticated?

And once that happens, how can it transition to a route with a dynamic segment?

I realize I can override sessionAuthenticated; and in that ways override the functionality of routeAfterAuthentication. However, routeIfAlreadyAuthenticated is a computed property that is executed in a beforeModel in the unauthenticated-route-mixin.js mixin.

Any help would be greatly appreciated.




Download a CSV file in EmberJs

I have tried a myriad of different function calls, but can't seem to figure out how to trigger a download for a CSV in EmberJs.

Here is my latest code:

let endpoint = '/api/foo/';
let options = {
    url: endpoint,
    type: 'POST',
    data: {},
    dataType: 'text'
};
return new Ember.RSVP.Promise((resolve, reject) => {
  options.success = function(result) {
      var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
      window.open(uri, 'foo.csv');
  };
  options.error = (xhr, errorThrown) => {
    console.log('error');
    // return Ember.run(null, reject, this.didError(xhr, xhr.status, xhr.responseJSON, 1));
  };
  Ember.$.ajax(options);
});

This code doesn't raise any server or client side errors. It's getting a 200 response. No javascript errors, and doesn't console log anything, so I know it's not hitting the error block. But... it won't trigger the file download on the client. Does anyone know what is missing?

Thanks in advance.




Dynamically refreshing ember.js page after an action

I have the following in my ember.js controller file:

hello_world.js

actions: {
    setValue: function(x) {
            this.set('value', x);
    }
}

Here is my handlebars file:

hello_word.hbs

<button >
    foo
</button>

Whenever I click the button, it does not update the value until after I refresh the page manually. Is there a way to dynamically refresh the page once the action is performed?




Ember model hook won't wait to return results of ajax call

I'm going out of my mind trying to figure this one out. When I make an ajax call inside of a model hook where I want (need) to return the results of both the ajax call and data from the store, Ember only wants to return the data from the store and not wait on the results of the ajax call. Here's the code :

model: function() {
        var user = this.modelFor('application').user;
        var org_id = user.get('org').get('id');
        var current_org = this.store.peekRecord('org', org_id);
        var _this = this;
        var redAppsRiskTotal = 0;
        var amberAppsRiskTotal = 0;
        var greenAppsRiskTotal = 0;

        ajax({
            url: _this.modelFor('application').url + '/orgs/' + org_id + '/apps.json?auth_token=' + user.get('auth'),
            type: 'get'
        }).then(function(result) {

            var greenRisk = current_org.get('greenRiskThreshold');
            var redRisk = current_org.get('redRiskThreshold');


            result.forEach(function(app) {

                if (app.total_risk_score < greenRisk) { greenAppsRiskTotal += 1; } else
                if (app.total_risk_score < redRisk) { amberAppsRiskTotal += 1; } else
                { redAppsRiskTotal += 1; }
            });

            console.log(current_org.get('businessLineCount')); // these all display the correct result non-zero results
            console.log(redAppsRiskTotal);
            console.log(amberAppsRiskTotal);
            console.log(greenAppsRiskTotal);
        });

        return { current_org, redAppsTotal: redAppsRiskTotal, // but this only returns the current_org
                                                    amberAppsTotal: amberAppsRiskTotal, // the others are zero
                                                    greenAppsTotal: greenAppsRiskTotal };
    }

I'm totally aware that I'm doing something wrong asynchronously, and it's probably pretty basic, I just can't figure out what. I'm relatively new at Ember. I've tried all sorts of ways -- add a second '.then' to the ajax call, create a function out of the ajax call, call it, then add a '.then' to that, put my return statement inside the .then block, etc etc etc. Nothing works (all of those solutions result in having NO data returned). Please help! Thanks.




How to change a belongs to attribute of a model in controller

In my Ember application using ember-data and JSONAPISerializer, I have a task model and a priority model. A task belongs to a priority and a priority can have many tasks associated with it.

The models are as follows

app/model/task.js

export default DS.Model.extend({
    title: DS.attr ('string'),
    description: DS.attr ('string'),
    isComplete: DS.attr ('boolean'),
    priority: DS.belongsTo('priority')
});

app/models/priority.js

export default DS.Model.extend({
    title: DS.attr ('string'),
    description: DS.attr ('string'),
    tasks: DS.hasMany ('task'),
});

The user can edit the task and change any attribute including its priority. This is handled in the controller.

The editing form has a dropdown from which the priority can be selected. This drop down is populated by the controller by querying the store.

I have got the editing and saving part to work for all attributes except the priority. I am not able to make the changed priority stick when saving the task.

How to change the priority before saving the model?




mercredi 24 août 2016

Ember.js Component didRender Variable Scope

I am using an Ember Component's didRender() hook to implement some javascript that needs to run after the DOM is loaded. For Example:

didRender() {
  var signaturePad = new SignaturePad($("#sigElement"));
  signaturePad.clear();
}

This is working fine. However, I need to access the signaturePad variable from my actions in the same component to have buttons function appropriately. Such as:

actions: {
   clearSignature: function() {
     signaturePad.clear();
   }
}

Unfortunately, it seems my variable defined in the didRender() hook for the component does not pass to the actions.

How am I able to access this variable from my actions within the same component?




Ember controller test is not using prototype extension when called

I am trying to unit test an Ember addon that has already been written but unfortunately did not get tested at the time of its creation. I would really really like not to have to modify the existing codebase to fit the tests if possible.

Controller Code

foo() {
    return this.get('store').query('stuff', query)
        .then((data) => {
            this.setProperties({
                myList: []
            });

            data.get('content').mapBy('record').forEach((item) => {
                // fails here
                this.get('myList').pushObject(item);
            });
        });
    });
}

Test Code

beforeEach() {
    let data = Ember.Object.create({
        content: Ember.A([
            { record: { } },
            { record: { } }
        ]);
    });

    this.controller = this.subject({
        store: {
            query(property, query) {
                return new Ember.RSVP.Promise(function (resolve) {
                    resolve(data);
                });
            }
        }
    });
}

test('failing test case', function (assert) {
    this.controller.foo();
}

Error:

Uncaught TypeError: _this.get(...).pushObject is not a function

I did some research and found out that Ember extends object prototypes by default so that standard arrays ( [] ) become Ember arrays. I've checked my config/environment.js as mentioned in the how-to-disable prototype extension here and it only returns and empty object {}.

Why doesn't Ember wrap the array and allow me to use pushObject like I would expect in my tests?

PS: I've noticed that there's a package to disable prototype extension aimed at addon authors, but again I do not have this package
http://ift.tt/2bh2EhK




Deploy ember application in Bluemix

I am trying to deploy an existing ember-nodejs application into bluemix environment. I tried the following steps.

bluemix api http://ift.tt/QKImQk

bluemix login -u username -o org_name -s space_name

cf push app_name

I also tried the above command with an ember build pack from the list of compatible CF build packs

cf push app_name -b http://ift.tt/1f3K6iP

Uploading is successful, but the application doesnt start up. Is there a recommended way of deploying ember-node js application?




How can I run an ember.js application on Bluemix

Is it possible to run ember on Bluemix? I have not been able to find a buildpack for ember on Bluemix.




Model name with hyphen cannot be typed in ember route

I have a model named phone-session in ember and I am using the DRF underscore adapter to transform dash to underscore since the endpoint is

/v1/phone_session/

I am trying to return a dynamic segment model, as seen below

   model:function(params){
     return Ember.RSVP.hash({
       phone: this.store.findRecord('phone-session',params.phone-session_id),
       numbers: this.store.findAll('number')
     });
    }

unfortunately this is not working since ember is only reading session_id instead of phone-session_id and returning the error:

ember.debug.js:32096 ReferenceError: session_id is not defined

this is cause due to naming convetions that I cannot change now since my endpoints are named that way.

what can I do to solve this problem ?




How do I make jsPDF accessible in my Ember app?

I'd like to export PDF documents using jsPDF in an Ember app, but I can't figure out how to make the library available within the app.

So far, I've installed the library using bower:

bower.json

{
  "name": "myApp",
  "dependencies": {
    ...
    "jspdf": "~1.2.61"
  }
}

...and imported it in the ember-cli-build.js file:

ember-cli-build.js

...
app.import(app.bowerDirectory + '/jspdf/dist/jspdf.min.js');
...

However, when I try to use it (by calling var doc = jsPDF.new() in an Ember action), I get this:

ReferenceError: jsPDF is not defined

What am I missing?




Error 404 when directly access to a route in EmberJS distribution app

I have developed a web application with EmberJS and I want to deploy in a real server.

When I test in localhost with environment development and command ember severything is OK, but when I create the distribution package with ember build --environment=production and deploy it using a webserver (in my case python -m SimpleHTTPServer 4200) I get the following error when I try to access directly to a route.

Error response

Error code 404.

Message: File not found.

Error code explanation: 404 = Nothing matches the given URI.

If I enter in myaddress:4200 and navigate through links, nothing is wrong but if I want to refresh the web or change the url, the error 404 happened.




Ember controller actions does not get triggered if defined in it's mixin

My Ember controller looks like below;

import Ember from 'ember';
import SomeMixin from '../mixins/some-mixin';

export default Ember.Controller.extend(SomeMixin, {
    actions: {
        someAction: function() {
            // Why does this not get triggered if I have 'actions' object defined in SomeMixin
        }
    }
})

My question is if I defined actions object in SomeMixin (with some different action names), then the 'actions' defined in the controller are completely ignored and do not get triggered at all.

Again, the action names are not the same and I did try both with return and without any return from the controller action.

Also I have 2 mixins actually; SomeMixin1 & SomeMixin2




How to use Bootstrap JavaScript plugins (dropdowns, modals) in Emberjs

I can't get Bootstrap JavaScript plugins like dropdowns and modals to work out of the box in Ember. From the command line:

ember new test-app
ember install ember-bootstrap

ember generate route test
ember generate component jquery-test

app/templates/test.hbs:



app/templates/components/jquery-test.hbs (copied from getbootstrap.com):

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

app/components/jquery-test.js:

import Ember from 'ember';

export default Ember.Component.extend({
  didInsertElement: function() {
    console.log($("button").length);
  }
});

The log prints out 4, so jQuery is installed and working, right? But while the Boostrap button is styled like a Bootstrap button should be, it doesn't function. No modal appears when I click it. Same with a dropdown menu.

  • Ember v2.7.1
  • jQuery v2.2.4
  • Bootstrap v3.3.5



Get helper in hbs when getting nested object

suppose I have the following objects:

image: {
  size: {
    l: {
      url: 'l.jpg',
    },
    m: {
      url: 'm.jpg',
    },
    s; {
      url: 's.jpg',
    }
  }
},
mySize: 'm'

If I want to get corresponding image url in my template, how should I do that? I tried:



but it does not work. Thank you.




mardi 23 août 2016

Side-loading associations in pushPayload method (Ember)

I have an Ember CLI chat app with a Conversation object that has many Message objects. What I want to do is load all existing messages in the conversation on page load, then add new messages using a WebSockets connection. The setup looks like this:

Step 1. Load relevant messages in the route, and side-load associations

model: function(params){
  return {
    messages: this.store.query('message', {
      conversation_id: params.conversation_id,
      include: 'user,conversation'
    }),
    conversation_id: params.conversation_id
  }
}

Step 2: Create a messages array using peekAll and a filter, which should update dynamically when new messages are added:

setupController: function(controller, model){
    this._super(controller, model);
    controller.set('messages', this.store.peekAll('message').filter(function(x){
      return x.get('conversation.id').toString() === model.conversation_id.toString();
    }));
})

Step 3: When a message is received add it to the array:

function received(data) {
  this.store.pushPayload(data);
}

Step 4: Display the array

// messages.hbs

  


This almost works, but I am having trouble side loading the associated conversation object when I do store.pushPayload(data). The object pushed to the store doesn't have a loaded Conversation object, so is not filtered correctly when using peekAll('message').filter(...). Is there a way to pass associations in to the pushPayload method?

Many thanks




Ember: Cannot see embedded properties of model after serialization

Maybe someone can help me with that. I want to get JSON object from the server response. My model "tree" contains root ("child-node"), that may contain more of "child-node" and so on. But when I try to "serialize" the response, I cannot see the inner "child-node" . As you can see I'm using EmbeddeRecordsMixin

model tree.js
export default Model.extend({
  root: belongsTo('child-node'),
  selectedNodeId: attr('string'),
  openNodesIds: attr('array')
});

serializer tree.js
export default RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    root:{ embedded: 'always'  },
    openNodesIds:{ embedded: 'always' }
  }
});

model child-node.js
export default Model.extend({
  infoId: attr('string'),
  metricValues: hasMany('metric-value'),
  name: attr('string'),
  nodeType: attr('string'),
  children: hasMany('child-node')
});

serializer child-node.js
export default RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    metricValues:{ embedded: 'always' },
    children:{ embedded: 'always' }
  },
  normalize(model, hash/*, prop*/) {
    // debugger
    if(hash.metricValues) {
      hash.metricValues.forEach(function (itemValue) {
        itemValue.id = itemValue.name + ' ' + hash.id;
      });
    }
    return this._super(...arguments);
  }
 }

 This is the response from server
 tree: {
    id: "treeId",
    openNodesIds: ["instance1", "instance2"],
    selectedNodeId: "instance",
    root: {
        id: "instance",
        infoId: null,
        metricValues: null,
        name: "instance1",
        nodeType: "instance",
        children: {
            0:{id: "instance:query_hash", name: "SQL Statements", infoId: null, nodeType: "query_hash",…}
            1:{id: "instance:sql_handle", name: "TSQL Batches", infoId: null, nodeType: "sql_handle",…}
            2:{id: "instance:database_name", name: "Databases", infoId: null, nodeType: "database_name",…}
            3:{id: "instance:program_name", name: "Programs", infoId: null, nodeType: "program_name",…}
            4:{id: "instance:username", name: "Users", infoId: null, nodeType: "username", metricValues: null,…}
            5:{id: "instance:machine_name", name: "Client Machines", infoId: null, nodeType: "machine_name",…}
        }
    }
}




Authenticate user with external url, Ember Simple Auth after callback with token

I use an external service for authentication Stamplay ..

To authenticate with username and password, I have to make a post in ${config.host}/auth/v1/local/login The callback for this post contain the token, so I created a custom authenticator to handle it

Custom Authenticator

export default Base.extend({
  tokenEndpoint: `${config.host}/auth/v1/local/login`,

  // ... Omited 

  authenticate(options) {
    return new Ember.RSVP.Promise((resolve, reject) => {
      Ember.$.ajax({
        url: this.tokenEndpoint,
        type: 'POST',
        data: JSON.stringify({
          email: options.email,
          password: options.password
        }),
        contentType: 'application/json;charset=utf-8',
        dataType: 'json'
      }).then(function (response, status, xhr) {
        Ember.run(function () {
          resolve({
            token: xhr.getResponseHeader('x-stamplay-jwt')
          });
        });
      }, function (xhr) {
        Ember.run(function () {
          reject(xhr.responseJSON.error);
        });
      });
    });
  },

  invalidate(data) {
    return Ember.RSVP.Promise.resolve(data);
  }
});

And everything works fine.. but ...

My problem

For social logins, I need to redirect the user to http://ift.tt/2bgjIWF

EXTERNAL_SERVICE can be.. github, twitter, facebook...

Then, the user is redirect to service page, and after login, the callback will be http://ift.tt/2bCzMQZ

So, how can I capture the token and login the user with this token?




How to add rotation event to an ember highchart graph?

In the highchart site, they have an example of a draggable scatter box in which you can do 3d rotation

http://ift.tt/1sgVuuD

I was able to create the 3d graph using ember-highchart, however I have yet to figure out how to add the event of rotation in ember. What is the best way to do something like that ?

here is my component containing ember-highchart

threed-graph.hbs



threed-graph.js

chartOptions: Ember.computed('array', function(){
    return  {

      chart: {
         renderTo: 'container',
         margin: 100,
         type: 'scatter',
         options3d: {
             enabled: true,
             alpha: 10,
             beta: 30,
             depth: 250,
             viewDistance: 5,
             fitToPlot: false,
             frame: {
                 bottom: { size: 1, color: 'rgba(0,0,0,0.02)' },
                 back: { size: 1, color: 'rgba(0,0,0,0.04)' },
                 side: { size: 1, color: 'rgba(0,0,0,0.06)' }
             }
         }
     },
     title: {
         text: 'XYZ'
     },
     subtitle: {
         text: 'Click on point to find coordinates'
     },
     plotOptions: {
         scatter: {
             width: 10,
             height: 10,
             depth: 10
         }
     },
     yAxis: {
         min: -10,
         max: 10,
         title: null
     },
     xAxis: {
         min: -10,
         max: 10,
         gridLineWidth: 1
     },
     zAxis: {
         min: -10,
         max: 10,
         showFirstLabel: false
     },
     legend: {
         enabled: false
     },
     series: [{
         name: 'Reading',
         colorByPoint: true,
         data: this.get('array')
     }]

    }
  })




Ember.js Computed Property vs Observer vs didReceiveAttrs() in a Component

I have created a top navbar in my ember.js application and converted it to a component so that I can have a simple "Welcome " introduction once a user signs in. There are some other reasons why the navbar is going to be a component, but for now this is what I am trying to get working correctly. We are also using ember-simple-auth addon and I am using the session.isAuthenticated value to make this happen.

Of course I have a 'login' route, that when the user signs in, they are transitioned to the 'index'. For some reason it doesn't seem like the session.isAuthenticated value is caught right away during the transition to the 'index'. I don't know why this is, but that is another issue.

Anyway, I am using a lot of components in this application and most of those components get their values from the sessions and querying the store independently of the routes so that I can use these components on multiple routes. The navbar is no exception. Right now I have the following working code:

export default Ember.Component.extend({
    layout,
    session: Ember.inject.service(),
    currentUser: Ember.inject.service(),
    isAuthenticated: Ember.observer('session.isAuthenticated', function() {
        this.didReceiveAttrs();
    }),
    currentUserFullName: null,
    user: null,
    tagName: 'navbar-main',
    className: ['navbar', 'main'],
    didReceiveAttrs() {
        this._super(...arguments);

        if (this.get('session.isAuthenticated')) {
            this._setCurrentUser();
        }
    },
    _setCurrentUser() {
        this.get('currentUser').load().then(user => this.set('user', user));
    },
    onGetCurrentUser: Ember.observer('user', function() {
        this.getUser();
    }),
    getUser: function() {
        var user = this.get('user');

        if(user) {
            this.set('user', user);
            this.set('currentUserFullName', user.get('fullName'));
        } else {
            user = this.get('store').findRecord('user', 'me');
            this.set('user', user);
            this.set('currentUserFullName', user.get('fullName'));
        }
    }
});

Everything I am reading suggests to just use didReceiveAttrs() instead of an observer. Also, it says that computed properties are usually what you want to use over observers. However I can't seem to get anything to work without the following:

isAuthenticated: Ember.observer('session.isAuthenticated', function() {
    this.didReceiveAttrs();
}),

If I try to convert it to a computed property it doesn't seem to do anything on a property change unless I refresh the page after it has already transitioned to the 'index' route. If I try to use just the didReceiveAttrs() method with this.get('session.isAuthenticated') logic, a page refresh is still needed.

So what am I not understanding about how to use Ember.computedand didReceiveAttrs()? Can someone give me an example? Or show me a more efficient way to do what I am trying to accomplish?




Moment js format date with timezone

Hi I am using Ember+moment.js to format date in my ember helpers.

I am getting the following date from the service

Tue Aug 23 2016 09:43:53 GMT+0200 (W. Europe Daylight Time)

In my ember helper class i am able to format date using following code :

var formattedDate = moment(date).format('DD/MM/YYYY h:mm a');

I am getting the following output :

23/08/2016 9:43 am

Expected Output : 23/08/2016 9:43 am GMT

How can i specify the timezone flag in the format function?

Any help should be appreciated.




Ember Run Loop Clarification

I have a service that contains a queue. Anything that injects this service can add an object to the service's queue. I need the service to asynchronously remove items from this queue, and run them. It would be nice to have a periodic function that just calls like service.processQueue(). Is this a proper use case to use the Ember Run Loop? How can I add this permanently to the Ember.RunLoop, and not just ran once?




how to pass js variable from widget loader script inside ember.js app

i load the ember.js app via a widget loader script: Widget Loader Script

now i need to pass a variable from the script which calls the ember app inside ember to load a specifc JSON file

has someone a hint or working example

thanks in advance




EmberJS 2.7 assertion failed passing id of nested object

EmberJS 2.7 Error: Assertion Failed: id passed to findRecord() has to be non-empty string or number

app/templates/products/index.hbs: [inside the model/each loop I have this line]:

<a href=""></a>

app/router.js: [I have these routes defined]:

  this.route('products', function() {
    this.route('new');
    this.route('edit', { path: '/:product_id/edit' });
  });

  this.route('categories', function() {
    this.route('new');
    this.route('edit', { path: '/:category_id/edit' });
  });

It works when editing a product. But throws the above error when trying to edit a category.

If I delete the 'categories/edit' route and add this route instead:

this.route('category', { path: '/categories/:category_id/edit' });

and change the template to use that:

<a href=""></a>

Then it works. I understand why this second one works. But why does the first one not work?




Ember highcharts shared tooltip

I'm using highcharts plugin, I have about 5 charts on the page. Every chart is a separate component. I'm a new to ember, so I don't know how to make shared tooltip for all charts. I saw examples with jQuery, event on container and one function for all with sync tooltip. I tried to insert those function in component, but it doesn't really work. How it should be done in ember?

This is a mixin:

 export default Ember.Mixin.create({
 syncExtremes: function (e) {
    let thisChart = this.chart;
    if (e.trigger !== 'syncExtremes') {
      Highcharts.each(Highcharts.charts, function (chart) {
        if (chart !== thisChart) {
          if (chart.xAxis[0].setExtremes) { // It is null while updating
            chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' });
          }
        }
      });
    }
  },
  sharedRooltips: function () {
    Ember.$('#container').bind('mousemove touchmove touchstart', function (e) {

      let chart, point, i, event;

      for (i = 0; i < Highcharts.charts.length; i = i + 1) {
        chart = Highcharts.charts[i];
        event = chart.pointer.normalize(e.originalEvent); // Find coordinates within the chart
        point = chart.series[0].searchPoint(event, true); // Get the hovered point

        if (point) {
          point.highlight(e);
        }
      }
    });

    Highcharts.Pointer.prototype.reset = function () {
      return undefined;
    };

    Highcharts.Point.prototype.highlight = function (event) {
      this.onMouseOver(); // Show the hover marker
      this.series.chart.tooltip.refresh(this); // Show the tooltip
      this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
    };
  },

In component:

    ....
    this.sharedRooltips();
        _syncExtremes= this.syncExtremes;
     ....
     xAxis: {
            type: 'datetime',
            crosshair: true,
            events: {
              syncExtremes: _syncExtremes
            }
          },
    ....




Ember.js async Widget not getting indexed by google

We've made a "Journal-Widget" for our costumer, which is in the end only a short code-snippet like that one from google analytics and looks like:

<div id="t17-voucher">
<noscript><p>Unsere Gutscheine konnten leider nicht korrekt geladen werden, da Ihr Browser kein Javascript unterstützt.</p></noscript>
</div>
<script>
(function (w,d,u,f,s,fs)    {w['t17CouponWidgetObject']=f;w[f]=w[f]||function() {
(w[f].q=w[f].q||[]).push(arguments);},s=d.createElement('script'),
fs=d.getElementsByTagName('script')    [0];s.async=1;s.src=u;fs.parentNode.insertBefore(s,fs);
})(window, document, 'http://ift.tt/2bdwS2o', 't17Voucher');
t17Voucher('create', 'u3zy1nu9', 'de', 'testhotel-post');
</script>    

This snippet gets posts from our api and displays them as a widget. So our customers have a nice, fast way to integrate a blog in their website.

But we are not able to get the detail-links of the posts, which gets generated by that ember-widget, indexed by google. As you can see the widget does have normal links something like: /query-params?post=slug and not some hash-links or hashbangs.

I guess the posts-request to our api takes to long and so google thinks the website is fully loaded and does not wait for our widget to finish render, or the problem is that all is async.

In google webmasters the widget is getting rendered correctly if i let him test the website with render:

enter image description here

Due to the deprecation of google hashbang we are not gonna use it.

We know we could use the noscript tag like a lot of ember-websites (like the discuss-ember forum) but if the problem is the async api request that would not fix our issue, because we would need to make the same request and add links to the noscript-tag dynamicly.

Test-Site

Hopefully I described it well and someone knows the solution.