vendredi 29 décembre 2017

Connecting ember frontend with java backend

hi I am a beginner for ember js.I have a java backend implementation of my previous project.I have created front end using ember-cli and i have dist folder from production ready.I want to how can i put these thing to gether.I am using Tomcat server. can i have some suggestion that will help me move further.

thanks in advance..




jeudi 28 décembre 2017

EmberJS nested dynamic routes don't redirect as expected

Using Ember 2.17.0, I can't seem to get routes nested under other dynamic routes to load properly.

With the following file structure I'd like the stacks route to load a new page.

features/instances/
├── edit
│   ├── route.js
│   └── template.hbs
├── index
│   ├── route.js
│   └── template.hbs
├── new
│   ├── route.js
│   └── template.hbs
└── view
    ├── route.js
    ├── stacks
    │   ├── route.js
    │   └── template.hbs
    └── template.hbs

The URL for the stacks endpoint looks like /instances/view/91467053-ba03-33b9-8950-83f0e64b4688/stacks/123456

Where 123456 is the ID of the stack model. However at the moment when I trigger the link above the page doesn't reload and I'm still on the view route. If I put a tag into the view template, the content of the stacks is rendered there. But I want it on it's own page...

My router.js

Router.map(function () {
  this.route('instances', function () {

    this.route('view', {path: '/view/:instance_id'}, function () {
      this.route('stacks', {path: '/stacks/:stack_id'});
    });

    this.route('edit');
    this.route('new');
    this.route('all');

  });
  this.route('error');
});

What have I done wrong here? I can't find much about nested dynamic routes for ember 2.0+




Should the Ember hbs template pass in parameters from an input field to a function and if so how?

I have a form that has an input field and an associated button and I have a function that would like to have the value the user types into the input field. Should I be passing it somehow from the hbs template or should I just go and get it from the DOM in the function.

Is there something like this?






mercredi 27 décembre 2017

How to use ember.js for client side with struts as server side?

I have created an application of Student Details using Struts Framework Now I am given the task to use ember.js Framework in the same Application for client side. So Can someone explain how can i use both together?




How do we integrate ember with struts 2?

I want ember in the client side and struts 2 in the server side.Is there any way to do it??i have already made the struts 2 and my app is working greatly...my app is to create a log history in an office.




mardi 26 décembre 2017

Ember JS: select list with selected value

I am trying to create a select component. In which I need to select an option based on the value in object.

Found something similar here

Implemented same:

<select>
  <option value="" selected disabled >Select </option>
  
    <option value= selected=></option>
  
</select>

Here sourceType.id is id for current option and selectedOption is sourceType reference in source object. Type is number in REST service response for both of them.

When I tried to print value of eq sourceType.id selectedOption in option it is giving me false. Then I checked for eq documentation, it is a === b

  1. Why is it giving false even if value and type both are same.
  2. Is there any way to just check for value like a == b.



lundi 25 décembre 2017

Ember, can't assign a variable inside an AJAX call

So I am trying to assign a variable, it runs ok if there is no ajax call but trying to assign the response does not work (response data is ok, I can console.log it) Here is my component code, upon editing the objects array anywhere but in the ajax call it updates correctly.

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

export default Component.extend({

  objects: [],

  actions: {
    loadObjects: function() {
      Ember.$.ajax({
        url: 'http://ift.tt/2zsz6qg',
        type: "GET"

      }).then(function(resp) {
        this.set('objects', resp);
        console.log(resp);
      });
    }
  }
});

Any idea? Been smashing my head for hours




dimanche 24 décembre 2017

Ember-data: Create a record if one does not exist?

I have a computed property where I'm attempting to create a record if one does not exist, but keep getting a jQuery.Deferred exception when attempting to render the computed property.

Here's what I have so far:

deadlineDay: computed(function() {
  const oneWeekFromNow = moment().startOf('day').add(1, 'week');
  const store = this.get('store');

  return store.queryRecord('deadline-day', {
    filter: {
      date: oneWeekFromNow
    }
  }).then(result => {
    if (!result) {
      result = store.createRecord('deadline-day', {
        date: oneWeekFromNow
      });

      result.save();
    }

    return result;
  });
}),

Then in my templates I'm attempting to render with a simple helper:



The helper just calls return date.format('dddd, MMM Do')

It looks like Ember ignores the .then() block, instead attempting to render the first promise, which results in null being passed to the template.

This results in an error since .date is not a property of null.

I imagine this is an extremely common use-case, but that I have a lapse in understanding. Much help appreciated!

I'm not sure if it is relevant, but my backing store is sessionStorage via ember-local-storage




Creating a record with nested hyperlinked relationship Ember JS

I'm trying to create a record from my EmberJS app into a backend api. The backend api is running Django REST JSON API. Trouble is that I'm using Hyperlinked relationships and for some reason the commit is not able to resolve to the url of the nested resource properly.

For example:

I have an endpoint http://host:port/api/v1/users, user has a belongsTo field which points to group field. On the method that does the creation I am calling

let createdRecordUser = createRecord('user', {'name': 'someName'})

followed by:

createdRecordUser.set('group', groupModelObject)

And finally:

createdRecordUser.save()

This had the undesired effect of sending an OrderedDict into the request.data to Django which then raised an error saying

Type mismatch: Expected URL not OrderedDict

What I was expecting is that the resource would be resolved into it's url on POST.

What the post request is presently sending:

{'name': 'someName', 'group': OrderedDict(['id': 4, 'type': 'normal'])}

What the backend API is expecting:

{'name': 'someName', 'group': 'http://host:port/api/v1/groups/1'}

I'm very new to EmberJS (JS in general) and would appreciate any guidance on how to resolve this issue.

Thank you very much for your time.




samedi 23 décembre 2017

ember component increment/decrement value

I am stuck with increment and decrement a value in a component js. I got this in my template:

<div class="circleBase" > <p>   C </p> </div>

For now I just want to increment the heat value when I am clicking on the div. My component looks like this:

    init() {
        console.log('init');
        this._super(...arguments);
        this.errors = [];
      },
      didRender() {
        this.setProperties({
          heat: 0
        });
      },
    actions: {
        upHeat: function(a){
            this.set('heat', this.heat +1)
            //or
            this.setProperties({
                heat: this.heat +1
              });
           console.log(heat);
        }
      }

This is not working. Each time I click on my div the heat-value is incremented but not saved. My template still shows 0 as value.




vendredi 22 décembre 2017

Convert Array of Objects into Object containing key and value as Array of Objects

I am getting a response as Array of Objects

Array [Object, Object, Object, Object]

I want to convert it into an Object with some key and value as above Array of Objects

Object {someKey : Array[4]}

I am trying to do it like:

var someKeys = Object.map(a => a.arr_key); 

Object[someKeys[0]] = Object;

but failing, need some help here. Thank you!!




How to get the request payload from a PATCH request in express

I'm using Ember.js alongside an Express webserver. The default JSONApi adapter calls update records with a PATCH request to the server setting the Request Payload in the request to the server.

I'm having a hard time getting that data out of the request on my express server

Here is an example request Ember is sending to the server

enter image description here

The relevant code for the express server looks like this

app.route('/tags/:id')
  ...
  .patch(tag.updateTag);

// UpdateTag

function updateTag(req,res) {
  Tag.findById({_id: req.params.id}, (err,tag) => {
    if(err) res.send(err);
    Object.assign(tag, req.body).save((err,tag) => {
      if(err) res.send(err);

      res.json(TagSerializer.serialize(tag));
    });
  });
}




jeudi 21 décembre 2017

Not able to use the same model from previous page

In my first page, I am getting the model like :

model:function(){
        return this.get('store').findAll('offer').then(function(data){
            return data.get('firstObject');
        });
    },

when user click on next button, I am taking them in to next page. where i require the updated model from previous page. so I am trying to use the same model as what i updated like:

model:function(){
        var model = this.modelFor('HK.cs2i.cs2i.purchase.purchaseDetails');
        console.log('model is', model);
        return model;
    },

But on the console, I am getting the mode as undefied. is it require to do any workarounds or something else to access the previous mode?

any one help me here?




EmberCharts - Cannot read 'color' of undefined

I am trying to render a simple vertical bar chart using the Ember Charts add on but I can't get it to render on the page. I have been following the tutorial provided here with no luck.

\\ dashboard.hbs
<div class="chart-container">

<h1>text</h1>
</div>

\\ dashboard.js (controller)
import Controller from '@ember/controller';

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

    init: function() {
   this._super;
   this.get('ajax')
     .request('barchart').then((data)=>{
       this.set('bardata', data);

   })
 }

});

\\ ajax.js (service)
import Service from '@ember/service';
import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
  host:
   'http://server:port/api'
});

When I load the route there is an empty space where I would expect the chart to be.

When I investigate the Network developer tools I can see that the 'barchart' data is succesfully retrieved in the following format:

[
{"value":74,"label":"2017-12-20"},
{"value":16,"label":"2017-12-21"}
]

where value is an integer and label is varchar which seems to be correct as per the documentation.

Console produces the following error:

Uncaught TypeError: Cannot read property 'color' of undefined
    at colorable.js:89
    at vertical-bar-chart.js:412
    at Array.forEach (<anonymous>)
    at Class.<anonymous> (vertical-bar-chart.js:411)
    at ComputedPropertyPrototype.get (ember-metal.js:3252)
    at get (ember-metal.js:2594)
    at Class.get (observable.js:37)
    at Class.<anonymous> (vertical-bar-chart.js:441)
    at ComputedPropertyPrototype.get (ember-metal.js:3252)
    at get (ember-metal.js:2594)

I tried adding a manual selectedSeedColor but there was no change in the response.




PhantomJS 2.1 - Global error: ReferenceError: Can't find variable: Ember at http://localhost:4221/1400/tests/index.html?hidepassed

PhantomJS 2.1 - Global error: ReferenceError: Can't find variable: Ember at http://localhost:4221/1400/tests/index.html?hidepassed

Here is my result of ember version --verbose && npm --version && yarn --version




Sorting date not works as per expected

I am trying to sort the amount and date. But the date function not works properly. what is the correct way with ember sorting method?

my code :

import Ember from 'ember';

export default Ember.Controller.extend({
  appName: 'Ember Twiddle',
  sortingDate: ['date-of-purchase:desc'],
    sortingAmout: ['amount:desc'],
    sortByAmountSpent:Ember.computed.sort('model', 'sortingDate'),
    sortByDateOfPurchase:Ember.computed.sort('model', 'sortingAmout')
  ,actions:{
    sortByAmount:function(){
      this.set("model", this.get('sortByAmountSpent'));
    },
    sortByDate:function(){
       this.set("model", this.get('sortByDateOfPurchase'));
    },
  }
});

here is my try :

Twiddle-link




HTML scrolling issue in dialogs on iOS

I'm developing a web application based on EmberJS, that should be running on multiple device types. The application includes dialogs, that are handled using the ember-modal-dialog and liquid-wormhole addons.

When opening the dialog on an iPhone, scrolling within the dialog eventually stops working, and instead of scrolling the content, some underlaying(?) elements are overlapping the dialogs content from the top or bottom (depending on the scroll direction). It's actually hard to explain, so I've made a video:

http://ift.tt/2COMirG

Also, you can try it yourself. Click on the following link, and then on the button of the first item on the page.

http://ift.tt/2BHXYx2

Does anyone knows or have an idea, how to fix the problem?




mercredi 20 décembre 2017

Facing issue in using ember-light-table

I am learning ember js and I came across ember-light-table as an alternative of data-tables.

I just want to display some static data into table. So instead of creating mixin and component, I am writing code directly into route file. (Not sure things will work in this way or not).

Below is my route file

import Route from '@ember/routing/route';
import Table from 'ember-light-table';
import { computed } from '@ember/object';

export default Route.extend({
  table : null,
  columns: computed(function() {
    return [{
      label: 'Email',
      valuePath: 'email'
    }, {
      label: 'Name',
      valuePath: 'name'
    }];
  }),

  rows: computed(function() {
    return [{
      "email":"abc@gmail.email",
      "name":"Abc"
    }, {
        "email":"xyz@gmail.email",
        "name":"Xyz"
    }];
  }),

  init(){
    this._super(...arguments);
    let table = new Table(this.get('columns'),this.get('rows'));
    console.log("table = ",table);
    this.set('table', table);
  }
});

Template file


    

    
    


I am getting below error in console:

Error: Assertion Failed: [ember-light-table] table must be an instance of Table

I have seen code of document and other blog also, code seems identical, but not sure Am I missing something or not.

Thanks in advance.




Ember JS for SCORM Compliance

Is there any references that explain how to make Ember JS Learning Content that will be used in the LMS (SCORM Compliance). I've already tried to ember build and put the imsmanifest.xml on the root folder(/dist). When I upload all the /dist folder's content to the LMS (cloud.scorm.com), the Ember JS app is not shown.

Is there any suggestion to make learning content using SCORM Compliance and Ember JS? I will use SCORM 2004 4th Edition. Thank you very much.




Create a polymorphic record in ember front and rails back

I'm having some troubles creating a polymorphic record with emberjs for a rails backend. My little project is about cars. Please need some help.

This is my rails backend. All of their controllers were generated by scaffolds. So, they're the same.

class Vehicle < ApplicationRecord
  belongs_to :concess
  has_many :comments, as: :commented
end

class Concess < ApplicationRecord
  has_many :vehicles, dependent: :destroy
  has_many :comments, as: :commented
end

class Comment < ApplicationRecord
  belongs_to :commented, polymorphic: true
end

And these are my emberjs models and the main issue (comment controller)

vehicle model:

import DS from 'ember-data';
import Commented from './commented'

export default Commented.extend({
  model: DS.attr('string'),
  concess: DS.belongsTo('concess')
});

concess model:

import DS from 'ember-data';
import Commented from './commented'

export default Commented.extend({
  name: DS.attr('string'),
  createdAt: DS.attr('date'),
  vehicles: DS.hasMany('vehicle')
});

comment model:

import DS from 'ember-data';

export default DS.Model.extend({
  body: DS.attr('string'),
  commented: DS.belongsTo('commented', {polymorphic: true}),
  concess: DS.belongsTo('concess'),
  vehicle: DS.belongsTo('vehicle')
});

commented model:

import DS from 'ember-data';

export default DS.Model.extend({
  comments: DS.hasMany('comment')
});

Finally the comment controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    createComment: function(params){
      let body = this.get('body');
      let concess = this.get('store').findRecord('concess', params.id)
      var comment = this.store.createRecord('comment',{
        body: body,
        commented: concess
      });
      comment.save();
      this.transitionToRoute('concesses.show', params.id);

    }
  }
});




What is the best way for all instances of an Ember component to share a variable?

I have an Ember component which is essentially a panel. There can be multiple instances of this panel on a page, but only one can be "active" at any given time. Each instance of the component must be aware if any of the other panels become "active" so they can remove their "active" state. I would really rather not move the JavaScript to make this happen to a parent component. Instead, I would like to keep it within this component. In Angular, I used to use a static variable to do this. What is best way to do this in Ember?




Selecting Multiple element with condition with toggle approach

In my list, I have more than 5 fruit. user can select max as 5 fruit. once the 5 fruits reach, I would like to show them a alert to say your 5 selection is over.

also, user can deselect the fruit already which they selected, by clicking again ( toggling )

how to achieve this?

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  selectedIndex:null,
  appName: 'Ember Twiddle',
   actions:{
    select:function(index){
     console.log('index is', index );
    }
  }
});

here is my try : Live Demo

Any one help me here?




mardi 19 décembre 2017

Ember Nested Data in JSON Response

I'm having some trouble accessing some nested data in one of my Ember models. Below is the JSON response...

{
  "fields": {
    "header": {
      "name": "header",
      "type": "text",
      "localize": false,
      "options": []
    },
    "body": {
      "name": "body",
      "type": "textarea",
      "localize": false,
      "options": []
    }
  },
  "entries": [
    {
      "header": "header test",
      "body": "body test body test body test",
      "_mby": "5a395e8430c2ddoc683600766",
      "_by": "5a395e8430c2ddoc683600766",
      "_modified": 1513709605,
      "_created": 1513709605,
      "_id": "5a3960253d578doc735798511"
    }
  ],
  "total": 1
}

I'm trying to get the Entries in my template. Perhaps I need some help serializing this with NormalizeResponse? I'm very stumped so please share if you have any ideas!

Thanks!!




Ember-Rails gem in production on Heroku

I am using Ruby On Rails 4 and Ember-Rails gem. Everything works fine in development. In production deploying on Heroku, I get this particular error initializer.initialize is not a function and routes/templates aren't rendering.




Send Ember application as response from Java HTTP server?

I'm new to Ember. I'm using Ember for front-end and Java for back-end. On typing localhost:8080, I need to show the Ember homepage index.html. Previously, I used Node.js and the below line did the trick

res.sendfile('./public/index.html');

Now on shifting to Java, I'm unable to achieve the same result. I tried the below code.

public static void main(String[] args) throws Exception 
{
    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.createContext("/", new HHandler());
    server.createContext("/getbookarray", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
}

static class HHandler implements HttpHandler 
{
    @Override
    public void handle(HttpExchange t) throws IOException 
    {
        File file = new File("..\\public\\index.html");
        String response = FileUtils.readFileToString(file);
        String encoding = "UTF-8";
        t.getResponseHeaders().set("Content-Type", "text/html; charset=" + encoding);
        t.getResponseHeaders().set("Accept-Ranges", "bytes");
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes("UTF-8"));
        os.close();
    } 
}

But, unfortunately I'm getting the below error on trying to load the home page. "Uncaught SyntaxError: Unexpected token <"

The same Ember application when processed using Node.js works fine. I guess I'm not sending the HTTP response properly. Any help is appreciated.




Ember component what is layout and how to write the functions?

I created a component, it gives the output as :

import Ember from 'ember';
import layout from '../templates/components/sample-work';

export default Ember.Component.extend({
  layout
});

When i try to add some init method like :

import Ember from 'ember';
import layout from '../templates/components/sample-work';

export default Ember.Component.extend({
  layout,
  init(){
    alert.log('hi');
  }
});

My component not at all called. what is the issue here? what is the correct way to handle the component here?




lundi 18 décembre 2017

Unsure how to retrieve data from a custom endpoint?

Context to this post is I'm a java developer attempting to teach myself Ember. It isn't going well. I realize this question is pretty vague so I apologize, I'm not even sure what I should be asking...

I need to pull data into a model, i.e. via some sort of query, from a heroku json endpoint. In the application.js file, I have the following:

import DS from ‘ember-data’;

export default DS.JSONAPIAdapter.extend({
    host: 'http://ift.tt/2yTc7Vd'
});

Ideally I would like to pull this data into a user model, then display that data on a page as a sort of proof of concept. This unfortunately gets me nothing. Nor am I even sure I'm going about this correctly. Should I be doing something different than attempting to use Host Customization? Any guidance would be much appreciated!




Ember Handlebars Get helper won't accept words with hyphens

This question builds off of Get helper in hbs when getting nested object where I have a nested data object. Problem is that the Ember Handlebars 'get' helper does not work with strings that contain hyphens as a parameter and I am unsure why.

Here is how I'm templating this out:

<h3>The selected office:</h3>
<h4></h4>
<h3>The concat thing</h3>
<h4></h4>
<h3>The amazing title:</h3>
<h4></h4>

Here, the selected office comes from a select menu and populates, and so does the concatination string below.

When there is no hyphen in the selectedOffice variable, the specialthing will populate as well.

But when there is a hyphen such as "Kitchener-Waterloo", the specialThing will not populate.

The data structure I am working with is similar to:

"funnelContent": {
    "City": {
        "testing_attribute": Hello City!",
        "one_number": 0,
        "other_number": 0
    },
    "Other City": {
        "testing_attribute": Hello Other City!",
        "one_number": 0,
        "other_number": 0
    },
   "Kitchener-Waterloo": {
        "testing_attribute": Hello Kitchener-Waterloo!",
         "one_number": 0,
         "other_number": 0
    }
}




Trim or hide Highchart legends based on number of legends

Is there an option or formatter to hide or trim Highcharts v6 legends based on number of legends or text count?




EmberJS - Ember Simple Auth Oath2 'grant _type' not defined

I've been following the Ember Simple Auth walkthrough available here. I have added the various code snippets as instructed but when I submit my login form I receive a 'grant_type' not defined error.

Here is the current setup:

// Login Form
        <form >
          <label for="identification">Login</label> 
          <br>
          <label for="password">Password</label> 
          <br>
          <button type="submit" class="btn btn-default">Login</button>
        </form>

        
          <p>
            <strong>Login failed: </strong>
            <code></code>
          </p>
        

//index.js controller

import Controller from '@ember/controller';

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

  actions: {
    invalidateSession() {
      this.get('session').invalidate();
    },
    authenticate() {
      let {identification, password } = this.getProperties('identification', 'password');
      this.get('session').authenticate('authenticator:oath2', identification, password).catch((reason) => {this.set('errorMessage', reason.error)
    })
    }
  }

});

//application route

import Route from '@ember/routing/route';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Route.extend({

});

// authenticators/oath.js

import OAuth2PasswordGrantAuthenticator from 'ember-simple-auth/authenticators/oauth2-password-grant';

export default OAuth2PasswordGrantAuthenticator.extend({
  serverTokenEndpoint: 'http://server:port/api/token',


});

//api endpoint

var tokenRouter = express.Router();

tokenRouter.post('/api/token', function(req, res) {


  if (req.body.grant_type === 'password') {
    if (req.body.username === 'letme' && req.body.password === 'in') {
      res.status(200).send('{"access_token": "secret token!"}');
    } else {
      res.status(400).send('{ "error": invalid_grant_type" }')
    }
    } else {
      res.status(400).send(' { "error": "unsupported_grant_type" }')
    }

})

app.use('/', tokenRouter)

The request is successfully sent to my endpoint and the 500 error is generated with the message that grant_type is not defined. Looking at the request, it doesn't look like the username or password are being sent either.

As far as I can tell my code is identical to the code from the documentation and supplementary video but I am obviously missing something.




dimanche 17 décembre 2017

Change in Query Param not refreshing the route

I have set the queryParam setting in the route to refresh the model if the query param changes. However when the query param changes setupController is not called. Any idea why this is happening?

export default Route.extend({
  queryParams: {
    id: {
      refreshModel: true
    }
  },

  setupController(controller) {
    controller.start(); // fetches data synchronously from api
  }
});




ember automatic fetch by name convention

I am building a smarthone app to learn ember. A user got households which got rooms and so on. When I click on a user I want to show his households and after that I want to click on a household to show all rooms in that household. My Router.js looks like this:

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

  this.route('users', function() { //Lists all the users, URL looks like /users
    this.route('single', { path: '/:user_id' }, function() { //Actually i did not use this route
      this.route('households', function() { ;// Shows all households a user with user_id has, URL looks like /users/123/households
        this.route('single', { path: '/:household_id' }, function() { // Shows a single household, URL looks like /users/123/households/456
          this.route('rooms', function() { // Shows all rooms a household with household_id has, URL looks like /users/123/households/456/rooms
            this.route('single', { path: '/:room_id' }, function() {
              this.route('devices', function() {});
            });
          });
        });
      });
    });
  });
});

If I call the route ‘households’ is called. This is fine. In this route i need access to the user.id. This is working with the following statement in the household-route model hook.

var parentModel = this.modelFor(‘users.single’);

complete route:

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

export default Route.extend({
    model(){
        console.log('household route');
        var parentModel = this.modelFor('users.single');

   return Ember.RSVP.hash({

            user: parentModel,

            household: this.get('store').findAll('household').then(results => results.filter((site) => {
            return site.get('member').filter(x => x == parentModel.id).length > 0;
       })),
          });
    }
});

Now I am surprised cause of the name-convention or automatic data fetch. My child-route users.single is never called. In my understanding this is because of the naming convention user_id. For listing my data from the mirage server this woks fine but I want to understand the way it works.

I think it have to be possible to change user_id to ‘useridnumber’. But when I am doing this:

this.route(‘single’, { path: ‘/:useridnumber’ }, function() {

my route user.single is even never called and my data listing is not working.

I really can´t figure out why my route user.single is never called.




ember refresh/reload model after change data in mirage

I need to refresh/reload my model-hook again after I did changes like add or edit my modal by an action. I have seen a lot of topics like this but either there are deprecated or not working in my case.

This is my component.js-file called "listing.js":

import Component from '@ember/component';

export default Component.extend({
    actions: {
        togglePower: function(a){
            console.log(a);
            var data = new Array();
            data.push(a);
            $.ajax({
                cache:false,
                type: 'POST',
                url: "/api/device",
                data: JSON.stringify(data),
                contentType: "application/json"
                })

                this.get('users.single.households.single.rooms.single.devices.single').send('refresh');
        }
      }
});

Mirage receives my data and is able to work with it. But for now I need to reload my page to see my changes. So I tried to add the last line in the listing.js which is

this.get('users.single.households.single.rooms.single.devices.single').send('refresh');

But this doesn´t work for me. The console comes up with:

TypeError: this.get(...) is undefined

This is my route:

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

>     }




samedi 16 décembre 2017

set 'didValidate' true only for selected fields

Environment

  • Ember Version: 2.0
  • Ember CLI Version: 2.13.0
  • Ember CP Validations Version: 3.4.0

Steps to Reproduce

hbs:

<div>
  <label> Email: <label>
  
  <label> Password: <label>
   
  <button >Submit</button>
</div>

<div>
  <label> Confirmation Token: <label>
  
  <button >Verify</button>
</div>

js:

import Ember from 'ember';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
  new_email: [
    validator('presence', true),
    validator('format', { type: 'email' })
  ],
  current_password: [
    validator('presence', true)
  ],
  confirmation_token: [
    validator('presence', true),
  ]
});

export default Ember.Component.extend(Validations, {
  changeEmail: function() {
    this.validate().then(() => {
      if (this.get('validations.attrs.new_email.isValid') && this.get('validations.attrs.current_password.isValid')) {
        ...
        ....
      } else {
        this.set('didValidate', true);
      }
  });
});

Now when I click submit, changeEmail action is called and if validation fails it sets this.set('didValidate', true); which enables all the three validated-input field and shows validation error for even confirmation_token field. But i need to show validation error message only for current_password and new_email. vice versa when verify action is called




Emberfire session not recognising any functions

I'm using emberfire to authenticate to a firebase database following the ember tutorial exactly with the following config:

//pods/application/route.js

  beforeModel: function() {
    return this.get("session").fetch().catch(function() {});
  },

  actions: {
    signIn: function(provider) {
      this.get('session').open('firebase', {
        provider: 'password',
        email: 'test@example.com',
        password: 'password1234'
      });
    },
    signOut: function() {
      this.get("session").close();
    }
  }



//app/torii-adapters/application.js
import ToriiFirebaseAdapter from 'emberfire/torii-adapters/firebase';
export default ToriiFirebaseAdapter.extend({
  firebase: Ember.inject.service()

});

"emberfire": "^2.0.8",
"torii": "^0.9.6"


//config/environment
    firebase: 'http://ift.tt/2kC83n1',
    torii: {
      sessionServiceName: 'session'
    },

I get the following error:

router.js:936 Error while processing route: index this.get(...).fetch is not a function TypeError: this.get(...).fetch is not a function

Does anybody have any idea what's going on? I'm copying the tutorial to the letter.




Ember Data unable to pass params to Rails properly via createRecord

I'm trying to set up an Ember Data call to create a signup object, which just contains an email and nothing more. Something is funky with my Ember Data setup because the params seem to be passed but Rails is unable to receive them. Not sure what's wrong.

Ember frontend:

  var signup = this.get('store').createRecord('signup', {
    email: this.get('emailAddress')
  });
  console.log(this.get('emailAddress')); --> prints fine
  console.log(signup); --> data is empty, somewhat alarming/confusing
  console.log(signup.get('email')); --> however, this also prints fine
  signup.save();

Request payload:

{"data":{"attributes":{"email":"gg@gg.com"},"type":"signups"}}

Rails backend:

  def create
    @signup = Signup.new({ email: params[:email] })
    p params
    # prints <ActionController::Parameters {"controller"=>"signups", "action"=>"create"} permitted: false>

    p @signup --> prints Signup object with nil for email
    @signup.save!
    render json: @signup
  end

Response payload:

{"data":{"id":"3","type":"signup","attributes":{"email":null}}}




ember map object from ember data store

I am trying to map an object in the model hook. I have this object provided by mirage.

let temp = {"users": [
    {
        "id":1,
        "forename":"Test",
        "surname":"Name"
    },
    {
        "id":2,
        "forename":"Hans",
        "surname":"Solo"
    },
    {
        "id":3,
        "forename":"Peter",
        "surname":"Pan"
    }
]

};

In the model hook I want to use this:

return this.get('store').findAll('user').then(x => x.map(x => x.id + x.forename + x.surname));

I am getting this:

1[object Object][object Object] 2[object Object][object Object] 133000[object Object][object Object] 3[object Object][object Object]

And I am using this in the template (at the moment just for test if it works):





I tried to just map to the ID and this works fine. Furthermore it works fine if I will declare the temp directly in the model hook. Is there anything with promise which impede my map?

I need this working because I am implementing a ember power select multiselection and I want to show the user the id, forename and surename.




unable to update the input field once the value is dropped to that input field value

i am using jquery builder in my ember app. i m using jquery drag and drop function to drop the value to the input field . my drag nd drop functionality is working fine but once the value is dropped to the input field of the query builder and then upon saving i m getting this error "Cannot read property 'condition' of null". This eventually means that particular input fieldis not accepting the drpped value. how to fix this issue??

my code in controller:

$('#buildQuery').on('dragleave', function(event) {
  if(event.target.className == "form-control"){
  $('.rule-value-container > input[name='+event.target.name+']').val("");
  $('.rule-value-container > input[name='+event.target.name+']').val("item name");
  }
});




vendredi 15 décembre 2017

Assertion Failed: Attempting to inject an unknown injection: 'service:session'

I have an EmberJS app, where for one of my controllers I'm getting an error Assertion Failed: Attempting to inject an unknown injection: 'service:session'

I'm using a session service that utilizes the library ember-simple-auth. I have used the session service so I know that it works, but I am still getting this error? Does it have anything to do with any of the node ember modules being updated ?

Controller

import Controller from '@ember/controller';
import { get, set } from '@ember/object';
import $ from 'jquery';
import config from '../../../config/environment';
import { inject as service } from '@ember/service';

export default Controller.extend({
  session: service('session'),
  actions: {
    merge(preserve) {
      let ExpList = [];

      // To-Do Make this a computed property
      get(this, 'model.experiences').forEach(function(exp) {
        ExpList.pushObject(exp.id);
      });

      this.get('session').authorize('authorizer:django', (authKey, authToken) => {

        $.ajax({
          url: `${config.APP.API_HOST}/api/v0.1/`,
          type: 'POST',
          headers: {
            'Authorization': authToken
          },
          data: {
            'experience_ids': ExpList,
            'name': get(this, 'model.newExp.name'),
            preserve,
            'module': get(this, 'moduleExp')
          }
        }).then(() => {
          this.transitionToRoute('route');
        }).catch(function(error) {
          this.set('errorMessage', error.error || error);
        });

      });
    }
  }
});




Ember app visible when running in host, but not in container

I'm attempting to containerize an Ember app for local development. I have ports 4200, 3529 (live reload), and 8443 (api) exposed in my Dockerfile.

I'm basing my image on Node 6.9.4 (specified in the project). When I run the app outside Docker, I can see the app when I navigate to it in my browser. When it's running inside Docker, it just hangs and the page loading spinner spins forever. I put in some logging, and it looks like the server is not seeing the request at all.

Dockerfile

FROM node:6.9.4

# open up the ports we need for the app to run
EXPOSE 4200 35729 4080 8443 9999

WORKDIR /usr/src/app

ENV PATH=/usr/src/app/bin:$PATH

ADD . /usr/src/app

RUN set -ex \
  && npm install -g ember-cli \
  && npm install -g grunt-cli \
  && npm install -g bower \
  && npm install -g protractor \
  && npm install -g check-dependencies

# set up Phantom
RUN \
  mkdir /tmp/phantomjs &&\
  curl -L http://ift.tt/1Rirpaz | tar -xvj -C /tmp/phantomjs --strip-components=1 phantomjs-2.1.1-linux-x86_64/bin &&\
  mv /tmp/phantomjs/bin/phantomjs /usr/bin &&\
  rm -rf /tmp/phantomjs

# set up Watchman
RUN set -ex \
  && export WATCHMAN_VERSION=3.0.0 \
  && curl -SL "http://ift.tt/2zuikIX" | tar -xz -C /tmp/ \
  && cd /tmp/watchman-${WATCHMAN_VERSION} \
  && ./autogen.sh \
  && ./configure \
  && apt-get update && apt-get install -y --no-install-recommends python-dev \
  && make \
  && make install \
  && apt-get purge -y --auto-remove python-dev \
  && rm -rf /var/lib/apt/lists/* \
  && rm -rf /tmp/*

docker-compose.yml

version: "2"

services:
  web:
    image: pnr
    build:
      context: .
      dockerfile: Dockerfile
    command: ember server --ssl=true
    entrypoint: /usr/src/app/development-entrypoint.sh

    volumes:
      # Mount the app code inside the container's `/usr/src/app` directory:
      - .:/usr/src/app

    # Keep the stdin open, so we can attach to our app container's process
    # and do things such as debugging, etc:
    stdin_open: true

    # Enable sending signals (CTRL+C, CTRL+P + CTRL+Q) into the container:
    tty: true

    ports:
      # Bind the host's 4200 port to the container's ember app server
      # port 4200:
      - 4200:4200
      # Bind the host's 35729 port to the container's ember cli live reload
      # server port 35729:
      - 35729:35729

      # api
      - 8443:8443

development-entrypoint.sh

#! /bin/bash

# The Docker App Container's development entrypoint.
# This is a script used by the project's Docker development environment to
# install the app dependencies automatically upon runnning.
set -e

: ${APP_PATH:="/usr/src/app"}
: ${APP_TEMP_PATH:="$APP_PATH/tmp"}
: ${APP_SETUP_LOCK:="$APP_TEMP_PATH/setup.lock"}
: ${APP_SETUP_WAIT:="5"}

# 1: Define the functions lock and unlock our app containers setup
# processes:
function lock_setup { mkdir -p $APP_TEMP_PATH && touch $APP_SETUP_LOCK; }
function unlock_setup { rm -rf $APP_SETUP_LOCK; }
function wait_setup { echo "Waiting for app setup to finish..."; sleep $APP_SETUP_WAIT; }

# 2: Specify a default command, in case it wasn't issued:
if [ -z "$1" ]; then set -- ember server --ssl=true "$@"; fi

# 3: Run the setup routine if the command is 'ember':
if [[ "$1" = "ember" ]]
then

  # 3.1: 'Unlock' the setup process if the script exits prematurely:
  trap unlock_setup HUP INT QUIT KILL TERM EXIT

  # 3.2: Wait until the setup 'lock' file no longer exists:
  while [ -f $APP_SETUP_LOCK ]; do wait_setup; done

  # 3.3: 'Lock' the setup process, to prevent a race condition with
  # another container trying to install dependencies:
  lock_setup

  # 3.4: Check or install npm/bower dependencies:
  check-dependencies

  # 3.5: 'Unlock' the setup process:
  unlock_setup
fi

# 4: Execute the given or default command:
exec "$@"

Thanks in advance!




Google Auto Complete CORS issue when called from ember

I am trying to call google api making a ajax call like below:

fetch(){
let url=`http://ift.tt/2yqGGB3`
return Ember.RSVP.resolve(Ember.$.ajax(url,{
method: 'GET'
}))
.then(
(response)=>{
console.log("google suggested places:",response);
return response;
})

But i am getting " Failed to load http://ift.tt/2yqGGB3: No 'Access-control-Allow_origin'header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I tried many options like below: in app/services/service.js dataType: 'jsonp' jsonp: "json_callback", jsonp : "callback", jasonpCallback: 'jsonpcallback' cache: false/'false'

but none of them resolved my issue.

Also i tried the following: in app/services/service.js

var restRequest = gapi.client.request({
'path': 'http://ift.tt/2kvO1L3'
});

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://ift.tt/2kvO1L3');

and I did the following to install gapi-client: npm install --save gapi-client and have this in my service.js

import gapi from 'gapi-client'

but i get an error in console " could not find module ' gapi-client' imported from 'projectname/services/servicename'

What is that i am doing wrong or am i missing anything?

A old thread to this is below: response undefined when calling google api thru emberjs




Cant get property of an ember object

Ember version 1.9.1

Doing this.get('wallet.bank_account_format') i get undefined.

Doing this.get('wallet') i get

__ember_meta__: Object { descs: {…}, watching: {…}, cache: {}, … }
...
bank_account_format: "bban-se"
...
__proto__: Object { … }

But the most confusing part is that if i try to do this.get('wallet.bank_account_format') over the dev tools i correctly get "bban-se".

What i'm doing wrong?




Can't Display Records from Ember.js Data in Template

I want to show records from the Ember.js data store in the my template. In my controller I have the following code:

orders: null,

[...]

openOrderModal: function(name) {
  $('.ui.' + name + '.modal').modal('show');
  var orders = this.get('store').peekAll('orders');
  console.log(orders);
  this.set('orders', orders);
},

I peek all records from the data store and save it to a variable. In the template i have a loop. But it doesn't work.


   


Can you help me?

Kind regards




jeudi 14 décembre 2017

Ember.js Wildcard URL

Any ember-way ideas to make a manual transition to a wildcard route with a dynamic segment at the end */:category_name, so I can manually build a "breadcrumbish url version" example, suppose a user enters to /banana I need to transition the user to /Groceries/Healthy/Fruit/Banana.... groceries, healthy, fruit might be entered as well so /Fruit would be transitioned to /Groceries/Healthy/Fruit... I was able to make it work using window.history.replaceState on the model hook of the route but strange enough it only works if it's being refreshed or type in by user, not while transitioning in template, thanks in advance guys

Route as is

this.route('products', function(){
   this.route('wildcard_handler', {path: '*/:category_name'});
   this.route('handler', {path: '/:category_name'})
});

Recap of cases:

Case 1:

User enters /products/banana

-Redirect to /products/groceries/healthy/fruit/banana

User enters /products/fruit

-Redirect to /products/groceries/healthy/fruit

Case 2:

User enters /products/groceries

-All good, it's correct.

Case 3

User enters /products/groceries/snacks

-doesn't exists so, 404 redirects.

All of this trouble is only for making a better UX for a new ecommerce I'm building, the normal suggested way is to just use one dynamic segment

Like

this.route('products', function(){
   this.route('handler', {path: '/:category_name'})
});

It's fair, but it's way nicer to build the breadcrumbish url

Again, thanks in advance




Emberjs receiving and creating embedded records with emberfire

I'm trying to add embedded records into fire base with the ember fire adapter without any luck. So I've got a post and a comment model and I would like it to look like this in firebase:

{
  "posts": {
    "post_id_1": {
      "comments": {
        "comment_id_1": {
          "body": "This is a comment"
        }
      }
    }
  }
}

I've currently got this:

{
  "posts": {
    "post_id_1": {
      "comments": {
        "comment_id_1": true
      }
    }
  },
  "comments": {
    "comment_id_1": {
      "body": "This is a comment",
      "post": "post_id_1"
    }
  }
}

I've tired following the documentation Docs but can only get the Async working but the not the embedded relationship to work. I'm working with an existing fire base database so I can't change the data structure on the backend it needs to be in the embedded format.

Finally is this best of way of doing this or is there a better way of doing?

I've also tried doing this as suggested here Docs

let post = this.get('post');
let newComment = this.store.createRecord({
  body: 'My super fun embedded comment'
});

post.get('comments').then(function(comments) {
  comments.addObject(newComment);
  // The comment is automatically saved when we call save() on the parent:
  return post.save();
});

Error in console:

Error: Assertion Failed: Passing classes to store methods has been removed. Please pass a dasherized string instead of [object Object]




Ember Window Event Listener not working

I added a window event listener in the route because I want to detect when a user is in another tab or not - focus vs blur state. So I used the init method to do this but .. its not being triggered at all or not working.

  init() {
   this._super(...arguments);
   window.addEventListener('blur,focus', e => {
     switch (e.key) {
       case "blur":
         this.get('player').pauseVideo();
         break;
       case "focus":
         this.get('player').playVideo();
         break;
     }
   });
  }

any ideas to what im doing wrong here to make this work in ember




Ember loading substate not working from addon

I have an Ember addon that is npm linked with a project.

If I create the file app/pods/application-loading/template.hbs in the addon, the loading HTML is not rendered from the base-project. However, if I create the exact same file in the base-project itself, the loading HTML is rendered.

My understanding is that the addon's app folder should be merged with the base-application's app folder, so this shouldn't be possible. What's going on?




Ember Promise Many Array

I'm trying to get assets from a Contentful backend. I have a picture gallery and would like to loop through all assets in a given field (Contentful has an asset field that allows multiple images).

Currently I'm getting:

<DS.PromiseManyArray:ember527> 

when trying to get the images in my template and in Ember Data.

Still a bit new to the Contentful thing and having trouble iterating through this..

Any ideas?

Thanks!!




What does the key param do in an computed properties set and get?

import Ember from 'ember';
export default Ember.Component.extend({
  firstName: '',
  lastName: '',
  fullName: Ember.computed('firstName', 'lastName', {
    get(key) {
        return `${this.get('firstName')} ${this.get('lastName')}`;
    },
    set(key, value) {
        let [firstName, lastName] = value.split(/\s+/);
        this.set('firstName', firstName);
        this.set('lastName', lastName);
        return value;
    }
  })
});

Considering this example, why would one have a need for the key param?




mercredi 13 décembre 2017

response undefined when calling google api thru emberjs

I am trying to call google api for getting place suggestions from ember js. like below: this is the service module

fetch(){
let url=`http://ift.tt/2yqGGB3
return Ember.RSVP.resolve(Ember.$ajax(url,{
method: 'GET'
}))
.then(
(response)=>{
console.log("google suggested places:",response);
return response;
})

*the above url when served with API_KEY and pasted in browser, a JSON response is returned with the suggested places.

also, i am seeing JSON response in newtwork tab of developer tools but the .then is not able to capture that resonse, and printing in console as response undefined.

ref : http://ift.tt/2AGMOuY

What am i doing wrong?




Can't access parent model value when building url for async loading of data

I have three models:

// mode/order.js
DS.Model.extend({
    start: DS.attr('string'),
    end: DS.attr('string'),
    referral: DS.hasMany('order/referral')
});

// model/order/referral.js
DS.Model.extend({
    stop: DS.attr('string'),
    go: DS.attr('string'),
    log: DS.belongsTo('order/log', {async: true})
});

// model/order/log.js
DS.Model.extend({
    log: DS.attr('string'),
    referral: DS.belongsTo('order/referral')

});

The referrals have only the id of a log and have been setup this way:

// serializers/order/referral.js
DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        log: { serialize: false, deserialize: 'ids'}
    }
});

I have an adapter setup to get an order and embedded referrals. All of this loads fine but I want the logs to load async:

model.referral[0].log

This causes the call to be made but I need the referral id as part of the url I build in

// adapters/order/log.js
DS.RESTAdapter.extend({
    urlForFindRecord (id, modelName, snapshot) {
        // build base url
            var  base_url = ....

            // ---- need referral field 'stop' to build log url ----
            base_url += referral.stop + '/log/' + id;

        return base_url
    }
});

the referral values don't get passed into urlForFindRecord for the log adapter. How can I get the referral values to make the url for the log call when requesting the log?




ember 2.17: calling a jquery document.ready() function

I am really new to Ember, which I am asked to do and well, love to learn. Basically, the current project uses Gentelella Admin Dashboard. I being trying to get the dashboard to load properly but failed.

After I login, I get redirected to /dashboard/ route, which basically loads the main dashboard interface. Now the problem is I can't click-expand the menus on the sidebar nor toggle the sidebar menu. And the main page is not extended to fill the space, as in our current application.

I know the function init_start() takes care of the resize and the click, which is already added to vendor.js from custom.js but I can't seem to call the function from ember at all.

My latest attempt was using mixins but it failed too:

             import Ember from 'ember';

export default Ember.Mixin.create({
  activate: function() {
    this._super();
    init_sidebar();

  }
});

then from dashboard.js route:

        import HandleTempLoadMixin from '../mixins/handle-temp-load';
        export default Route.extend(AuthenticatedRouteMixin,HandleTempLoadMixin, {

});

but still the function is not executed.

I have read that it is best to avoid working with jquery inside ember in SO but I have pretty much many JQuery functions that I cant transfer right now (nor sure why exactly since it says somewhere in the documentation jquery is built into ember itself).

Anyway, what is the best way to initailize the dashboard interface?




handlebars dynamic table row

I am using Ember with Handlebars. I have a situation where I need to dynamically create new table rows after 3 iterations of an array.

<table>

    <tr>
        <td></td>  
    </tr>

</table>

For the sake of example, please assume that there will always be a factor of 3 in the items array. When I try to save this code, I'm getting a syntax error that there is no close tag matching the open tag. How can I dynamically create the and without the syntax error?

I'm using ember CLI version 2.9.1.




Properly formatting Ember custom serializer response for sideloaded JSON API data

I want to try serving sideloaded data to my Ember app. I have a city model which hasMany fireStations. I changed my hasMany relationship to have an { async: false } option to coincide with sideloading, since the data will no longer be loaded asynchronously.

I use a custom serializer, and I am logging the response from normalize(). It looks like this for my data.

{  
  "data":{  
      "id":"3",
      "type":"city",
      "attributes":{  
        "name":"Anytown USA"
      },
      "relationships":{  
        "fireStations":{  
            "data":[  
              {  
                  "id":"17",
                  "type":"fire-station"
              },
              {  
                  "id":"18",
                  "type":"fire-station"
              }
            ]
        }
      }
  },
  "included":[  
      {  
        "id":"17",
        "type":"fire-station",
        "attributes":{  
            "name":"North Side Fire Station"
        },
        "relationships":{}
      },
      {  
        "id":"18",
        "type":"fire-station",
        "attributes":{  
            "name":"East Side Fire Station"
        },
        "relationships":{}
      }
  ]
}

I think my sideloaded data is properly formatted. It seems to match the example in the guides. The included array is populated with all my sideloaded data, and it all seems to be formatted as needed.

However, I'm hitting this error in my app.

Assertion Failed: You looked up the 'fireStations' relationship on a 'city' with id 3 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async ('DS.hasMany({ async: true })')

I can't figure out what the issue is here. I forked ember-data locally and I do indeed see this assertion is triggered.

If I manually loop over the manyArray in has-many.js, I see that each record is marked as isEmpty being true

Why are the has-many records returning isEmpty === true? What might I be doing wrong that is preventing sideloading from working correctly?




Can DjangoRestFramework accept JWTs that have more than username/password in payload?

I have a Django application that uses the Django Rest Framework. At first I was just using Session, and Token authentication, but now want to implement JWT Token authentication. I downloaded a package called djangorestframework-jwt that allows you to use JWT for authentication in DRF. The crux of the problem is that my client side application is using Auth0 which can return a lot of different information, first name, last name, userid, etc. We are using Auth0 with gmail as an identity provider to log into our client side EmberJS application. For our data adapters to get data from Django though, we are using 1 consistent token that we configured in our Auth0 account that is tied to a user in Django. What I would like to accomplish is to use the JWT returned from Auth0, instead of this 1 token, to authenticate all our requests to Django. Can you authenticate yourself in Django without using a Django User object?




Ember Mirage retreving DB Data

i have problem with retreving data in unit test from store by service method. Here is my code:

This is my test:

import { moduleFor, test } from 'ember-qunit';
import startMirage from '../../helpers/setup-mirage-for-integration';

moduleFor('service:filter-by-ingredients', 'Unit | Service | filter by ingredients', {
  needs: ['model:recipe', 'model:category'],
  beforeEach() {
    startMirage(this.container);
  },
  afterEach() {
    window.server.shutdown();
  }
});

test('should find recipe with title', async function(assert) {
  let recipe = server.create('recipe', {
    categories: server.createList('category', 5),
  })
  let service = this.subject();
  let result = await service.findRecipesWithContent();
  assert.equal(result.get('firstObject').get('categories').get('firstObject'), 10);
});

This is my service:

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

export default Service.extend({
  store: service(),
  findRecipesByWithContent() {
    return this.get('store').findAll('recipe');
  }
});
My mirage config:

  export default function() {

  this.get('/recipes', function(schema){
    return schema.recipes.all();
  });

  this.get('/categories', function(schema){
    return schema.categories.all();
  });

  this.post('/recipes', (schema, request) => {
    const attrs = JSON.parse(request.requestBody);
    return schema.recipes.create(attrs);
  });

  this.post('/categories', (schema, request) => {
    const attrs = JSON.parse(request.requestBody);
    return schema.categories.create(attrs);
  });
}

My factories:

import { Factory, faker, hasMany } from 'ember-cli-mirage';

export default Factory.extend({
  title: faker.list.random('omelette', 'chicken with salad', 'toasts', 'risotto', 'penne', 'spaghetti'),
  portionAmount: faker.list.random(1, 2, 3, 4, 5, 6),
  preparationTime: faker.list.random(5, 10, 15, 30, 45, 60),
  description: 'this is the description',
  calories: faker.list.random(100, 150, 200, 300, 400, 500),
  categories: hasMany('category'),
  rating: faker.list.random(1, 2, 3, 4, 5, 6),
});

Category factory

import { Factory, faker } from 'ember-cli-mirage';

export default Factory.extend({
  name: faker.list.random('dinner', 'breakfast', 'vegan', 'vegetarian', 'supper'),
});

And finally my models:

category

import DS from 'ember-data';

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

recipes

import DS from 'ember-data';
import { hasMany } from 'ember-data/relationships';

export default DS.Model.extend({
  title: DS.attr(),
  portionAmount: DS.attr(),
  preparationTime: DS.attr('number'),
  description: DS.attr(),
  calories: DS.attr('number'),
  categories: hasMany('category', { async: true }),
  rating: DS.attr(),
});

If i print:

console.log(server.db.recipes)

It shows all recipes with categories, one in my case, but when i call

service method findRecipeWithContent(), result.get('firstObject').get(categories).get('length') 

is 0. I can't get to this relationships.

If anyone can help me i would be very gratefull. Greetings!




Ember - Force https with heroku

I've made a ember app deployed on heroku. Heroku provides me an ssl certificat so https is working on my website.

I want to force visitors to uses https. I've found some answer telling to do-it in a client side, but since the client can modify JS he will be able to pass-by the force https.

I'm thinking about doing it in a beforeModel of the ember app. What's the best approach ? Many thanks




How to wait for image before calling res.send()

I have a route in express that returns an image with res.send() to an ember frontend. I have another route which I intermitently use to save an image using a Raspberry Pi. Sometimes when I call the route which wishes to return the image, there is no image available.

How would I go about waiting for the image to be saved before returning the image back to the user instead of sending them back error: no image.

The image is saved in backend/images inside of my express application. So far I have tried to us FS but with no avail!

Thanks in advance!




Share authentication between rails 4 (devise) and ember.js

In our company we decide to move our monolithic application currently developed in rails 4.2 to ember.js. And keep all back-end in rails. The first step I see, is authentication.

How to share devise authentication with my new fresh ember.js 2.17 app, without re-authenticate?

Thanks!




How can i pass data in my own format to an ember component, and have that take it and render it as desired?

I am trying to create a "code panel" component for my ember app. This will format code to look like what you might expect from an IDE (basic syntax highlighting, line numbers etc)

I have created the component code-panel, and I have added


    //Test Code Panel
    function n(a){
        var g = a + 1;
        return g;
    }


to my index.hbs, as this is the way I ideally want to invoke this component... however I am having issues understanding how I can then take this and turn it in to what I want in the component? Is there some way I can access the value I would get from having in the code-panel.js file, and then use that the generate all the HTML that would be needed to render it highlighted and line numbered?




how to get selected user id in ember

I am trying to add # for hastag and @ for user and I am using below package for that in ember package: ember-cli-mentionable

# is working but @ is not working

  const hashTags =[{
                searchProperty: 'name',
            values: []
            },{
                token: '#',
                values: this.get('hashTagList')
            }];
        this.set('hashTags',hashTags);
        let hashMapOfItems=new Ember.RSVP.Promise((resolve) => {
                resolve(this.get("userList"))
            })
        this.set('hashMapOfItems',hashMapOfItems);
 

here I am trying to get selected user but user list is showing empty when I write @

didSelectValue(selected) {
        console.log('selected',selected); // contains the object that was chosen.
    }

Please help me to find the solution for multiple token




EmberJS Behind the scenes. Application route trigger and addons

I'm new to EmberJS. I google a lot but I'm finding it a bit hard to learn the in-depths of EmberJS.

I have 3 questions:

  • How does the application route gets triggered?
  • How are addons loaded?
  • How does everything get loaded. I have a pod structure. But pod structure aside, how does ember know what is what by path? routes(app/pods//route.js or app/routes/.js), templates, templates, models, adapters (etc)

Basically, I'm ready to read the whole codebase of ember just to understand how everything works ;)


PS: this seems to be a duplicate for the first question




mardi 12 décembre 2017

Response Mapping in servlet

How does response mapping work in a Servlet? (i.e) How does each response know to flush out the output on that particular HTML or handlebars?




limit one user only for @Users on textareas

I am adding @ for user and I am using below package for that in ember package: ember-cli-mentionable

mixedConfig=
  {
    values: ['Johnny', 'Syd', 'Steve', 'Paul']
  }

I want to limit one user at a time, please help me to resolve this




Ember-idx-accordion throwing console error

using this for an app for a friend's business, this is within an hbs template.


    
        Item
    
    
        Item 2
    
     
        Item 3
    


Their docs are here: http://ift.tt/2BYusBZ

Through the inspector I see this error

consoleError

This is the file the Object.initialize hits.

define('carolin-rn-r/initializers/idx-accordion-config', ['exports' 'ember-idx-utils/config'], function (exports, _config) {
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
var Em = Ember;
exports.default = {
    name: 'ember-idx-accordion',
    initialize: function initialize() {
        var Config = Em.IdxConfig = Em.IdxConfig ? Em.IdxConfig : _config.default.create();

        var defaultConfig = Config.getConfig('default');
        if (!defaultConfig) {
            Config.addConfig('default');
            defaultConfig = Config.getConfig('default');
        }

        //Bootstrap
        var bsConfig = Config.getConfig('bs');
        if (!bsConfig) {
            Config.addConfig('bs');
            bsConfig = Config.getConfig('bs');
        }
        bsConfig['accordion'] = {
            classes: ['panel-group'],
            itemClasses: ['panel', 'panel-default'],
            itemSelectedClasses: ['active'],
            panelHeaderClasses: ['panel-heading'],
            panelTitleClasses: ['panel-title'],
            panelTogglerClasses: ['accordion-toggle'],
            panelBodyContainerClasses: ['panel-collapse', 'collapse'],
            panelBodyClasses: ['panel-body']
        };
    }
};
});




EmberJS - Printing model properties when multiple models on a route

I currently have two models being loaded from the same route using the following code:

    model(params) {
    return Ember.RSVP.hash({
      sginp: this.get('store').query('sginp', params),
      weekdayplan: this.get('store').query('weekdayplan', params),
        });
  },

  setupController(controller, models) {
    controller.set('sginp', models.sginp);
    controller.set('weekdayplan', models.weekdayplan);

  }

Both of the models load correctly in Ember Data.

I would like to be able to display the values of different model properties in different parts of my page.

As per a previous question I have been doing this with when I have had one single model and it works fine.

I assumed I would be able to do something like:

 
 

But these (and a number of permutations) do not display anything when used and no errors are generated in the console.




Style @Users and #hashtags on textareas

I am trying to add # for hastag and @ for user and I am using below package for that in ember package: ember-cli-mentionable

    let hashTags = {
          token: ['#',@'],
          values: [hashTagList,userList]
        };


only hash are coming when I am writing # but when I am writing @ nothing is coming




how to provide callback with context in emberjs

I am using jquery to record a keydown event for an app. I need to use this.sendaction inside it. When used, it shows an error "this.send actions is not a function"

Could someone help me with this please. Thanks

here is my code:

import Ember from 'ember';

const {
  Component,
  $,
  run
} = Ember;


export default Component.extend({

  classNames: ['digital-token-menu'],




didInsertElement() {
          this._super(...arguments);
          $(document).on('keydown', this._keydownHandler);
      },

  willDestroyElement() {
      this._super(...arguments);
      $(document).off('keydown', 'document', this._keydownHandler);
  },

  _keydownHandler(e) {
    if(e.keyCode === 8) {
      this.sendAction('onClose');
    }
  },

actions:{




Emberjs adding `.property()` in a function attribute of a controller/route

I'm trying to do the same as this question

My real question is why did he have to add .property() at the end of the function in the errorClass attribute? And can someone please point me to a documentation on how this work?




lundi 11 décembre 2017

ember-data: loading records in hasMany relationship

I am trying to code feature that allows logged-in users to add products to a "saved item" list. The model is:

//saveditem.js model
export default DS.Model.extend({
    user: belongsTo('user'),
    product: belongsTo('product', { async: true }),
    dateAdded: attr('string')
});

On the saveditems route where the saved items are displayed, the model() hook is:

model() {
    return this.get("store").findAll('saveditem');
}

the api is returning records with JUST the ids:

{
    "dateAdded": "Mon, 11 Dec 2017 20:59:10 GMT",
    "id": 4458,
    "product": 4458,
    "user": "me"
},
{
    "dateAdded": "Sun, 10 Dec 2017 10:26:02 GMT",
    "id": 3657,
    "product": 3657,
    "user": "me"
}
...

How can I get the hasMany relationship to load the actual products, using the IDs?




Encountered "categories" in payload, but no model was found for model name "category"

Hi when i try to load category product from REST API I get this warning "Encountered "categories" in payload, but no model was found for model name "category" (resolved model name using (unknown mixin).modelNameFromPayloadKey("categories"))" and data is not print.

Data I get from the API:-

{
    "categories": [{
        "id": 6737,
        "category_id": 1,
        "product_id": 3954,
        "product": {
            "id": 3954,
            "seller_id": null,
            "sku": "UN1185",
            "product": "Party",
            "description2": "Disclaimer: ",
            "mrp": 795,
            "price": 1499,
            "off": "75",
            "stock": 1,
            "total_products": 5,
            "catalogType": null,
            "weight": "1",
            "delivered_in": null,
            "chart_id": null,
            "stitching": 0,
            "seo_title": "Buy Now Party wear Light Peach Khadi Art Silk Plain Saree",
            "seo_description": "Shop",
            "keyword": "saree",
            "position": 1503,
            "status": 1,
            "product_images": [{
                "product_id": 3954,
                "url": "UN1185.jpg"
            }]
        }
    }, {
        "id": 6735,
        "category_id": 1,
        "product_id": 3953,
        "product": {
            "id": 3953,
            "seller_id": null,
            "sku": "UN1933",
            "product": "Party wear Pink Khadi Art Silk Plain Saree",
            "slug": "party-wear-pink-khadi-art-silk-plain-saree-un1933",
            "description": "Party wear Pink Khad..",
            "description2": "Disclaimer",
            "mrp": 795,
            "price": 1499,
            "off": "75",
            "stock": 1,
            "total_products": 4,
            "catalogType": null,
            "weight": "1",
            "delivered_in": null,
            "chart_id": null,
            "stitching": 0,
            "seo_title": "Buy Now Party",
            "seo_keyword": "saree",
            "keyword": "saree ",
            "position": 1503,
            "status": 1,
            "product_images": [{
                "product_id": 3953,
                "url": "UN1933.jpg"
            }]
        }
    }],
    "paging": {
        "prevPage": false,
        "nextPage": true,
        "currentPage": 1,
        "resultCount": 22
    }
}

My categories.js serializer

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    normalizeResponse(store, primaryModelClass, payload, id, requestType) {
        //console.log(payload.categories);
        payload = {
            categories: payload.categories
        };

        //console.log(payload);
        return this._super(store, primaryModelClass, payload, id, requestType);
    }
});

When I View categories page i get bellow warning and did not print any data

WARNING: Encountered "categories" in payload, but no model was found for model name "category" (resolved model name using (unknown mixin).modelNameFromPayloadKey("categories"))




Put data in ember store and mirage

I am pushing my data in a controller to the ember store like this:

    this.get('store').pushPayload({
        "user": [
            {
                "id":2,
                "name":this.get('name'),
                "passwort":this.get('admin')
            }
        ]
      });

This works temporally fine but after a reload on a route which uses findAll to get all users from mirage the new user is deleted out of the store. So is there any possibility to hold the new user into the ember store or to push the new object into the mirage database? I´ve tried to send a post-request on my own like this:

$.ajax({
  cache:false,
  type: 'POST',
  url: "api/test",
  data: myData,
  contentType: "application/json",
  success:  function(data) {            
  //
    }
  });

But for now there occurs an error in the console saying :

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

My config.js part:

this.post('/test', function(schema, request) {
    console.log('foo');
  });




Ember component function outside of action function

I have a problem calling a function outside action functions from an actions function. As you can see from the code below, I have a selectClient action that calls two functions, createCompanyAccount and createPrivateAccount. But I always get a this.createPrivateAccount is undefined. I have tried using self, but to no avail. Weirdly, I thought I would have to use self.createCompanyAccount, but then I get a self.createCompanyAccount is not defined.

I use Ember 2.12 and Ember Data 2.16.3.

import Ember from 'ember';

export default Ember.Component.extend({
    store: Ember.inject.service(),
    tagName: '',

    /**
     * Actions
     */
    actions: {
        // Select from selectList
        selectClient(element) {
            let self = this;

            if (element.company) {
                this.get('store').query('account', { 'filter' : {'orgnumber': element.orgNumber}}).then(
                    (accounts) => {
                        /* Organisation exist already */
                    },
                    (error) => {
                        let code = Number(error.errors[0].status);
                        if (code === 404) {
                            // company does not exist, so lets create it, and an account.
                            this.createCompanyAccount(element).then(
                                (account) => {
                                    /* Do stuff... */
                                }
                            );
                        }
                    }
                );
            } else {

                this.createPrivateAccount(element).then(
                    (anonUser) => {
                        /* Do stuff... */
                    }
                );

            }
        }
    },

    createCompanyAccount(company) {
        let account = this.get('store').createRecord('account', {
            type: 'company',
        });

        // Check if postal address is set on result
        if (typeof company.addressObject !== 'undefined') {
            let postAddress = this.get('store').createRecord('address', {
                address: company.addressObject.streetName,
                zip: company.addressObject.zip,
                postal_address: company.addressObject.postalAddress
            });
            account.get('addresses').pushObject(postAddress);
        }

        this.get('store').createRecord('company', {
            name: company.name,
            org_number: Number(company.orgNumber),
            account: account
        }).save().then((new_company) => {
            return new_company.get('account');
        });

    },

    createPrivateAccount(person) {
        let account = this.get('store').createRecord('account', {
            type: 'anonuser'
        });

        // Check if postal address is set on result
        if (typeof person.addressObject !== 'undefined') {
            let postAddress = this.get('store').createRecord('address', {
                address: person.addressObject.streetName,
                zip: person.addressObject.zip,
                postal_address: person.addressObject.postalAddress
            });
            account.get('addresses').pushObject(postAddress);
        }

        this.get('store').createRecord('anonUser', {
            first_name: person.firstName,
            sur_name: person.surName,
            email: person.email,
            phone: person.phone,
            account: account,
        }).save().then((new_person) => {
            return new_person.get('account');
        });
    }

});

Can anyone see where I go wrong? I can note that there is a few other functions that I have removed for clarity.

Thank you, Tommy




dimanche 10 décembre 2017

click to call action using in ember js

Am using ember-bootstrap nav component. The sidebar(on mobile view) is not collapsing when am using <a href='tel:'123-456-7890' class="">Call Us. While searching on their official site, I found that with we can achieve this. But when am giving it a try its giving errors Assertion Failed: You attempted to define a '' but did not pass the parameters required for generating its dynamic segments. There is no route named tel: 123-456-7890". Any suggestions?




ember-data: error re-adding a previously-deleted record

When trying to add back a record that was deleted from the store with destroyRecord() I get this error:

Attempted to handle event 'loadingData' on <saveditem:4139> while in state root.deleted.saved. Called with {_id: 74001, _label: Fetching saveditem' with id: 4139, _state: undefined, _result: undefined, _subscribers: }.

I've tried the method the docs recommend:

this.get('store').findRecord('saveditem', product.id, { backgroundReload: false }).then(item => {
    item.destroyRecord();
});

and also:

let item = this.get('store').peekRecord('saveditem', product.id);
if (item) {
    item.deleteRecord();
    item.save();
}

But it's the same result. Any help appreciated.




Validate From time To Time in ember using ember-cp-validations

I have two fields, "From time" and "To time". I want to validate From time should be lesser than To time and To time should be grater than From time.

Means validation should be depend on both the fields. Is there any way to validate such a scenario ?

'fieldData.FROM_TIME': function(keyToGetData){
    return validator(function(value, options, model) {
        let fromTime = value;
        let toTime = model.get(keyToGetData);
        if(fromTime){
            let fromHours = fromTime.hours;
            let fromMins = fromTime.minutes;

            // make validation only if toTime is there
            if(toTime){
                let toHours = toTime.hours;
                let toMins = toTime.minutes;
                if(fromHours > toHours || ( fromHours===toHours && fromMins > toMins) ){
                    return 'From time must be earlier than To time.';
                }
            }
            return true;
        }
        return 'This field can not be blank';
    });
},

'fieldData.TO_TIME': function(keyToGetData){
    return validator(function(value, options, model) {
        let fromTime = model.get(keyToGetData);
        let toTime = value;

        if(toTime){
            let toHours = toTime.hours;
            let toMins = toTime.minutes;

            // make validation only if fromTime is there
            if(fromTime){
                let fromHours = fromTime.hours;
                let fromMins = fromTime.minutes;

                if(fromHours > toHours || (fromHours===toHours && fromMins >= toMins) ){
                    return 'To time must be later than From time.';
                }
            }
            return true;
        }
        return 'This field can not be blank';
    });
}

With the above code I can validate fields with happy path.

But, if we set From time as 11:20am & To time as 11:20am so error will show on To time field. Now if we change From time as 11:19am so still it shows me error on To time. I want solution on such a scenario.

I am using ember-cp-validations.

Thanks.




ember: computed property on ember-data store

I am setting up a "saved item" feature for logged-in users. I have the modeling worked out already (it relates the saved item list to both the user and products). But I am having trouble with how to have a computed property on my saveditem model. The model:

// saveditem.js model
export default DS.Model.extend({

    user: belongsTo('user'),
    product: belongsTo('product'),
    dateAdded: attr('string')

});

I am currently using the product id as the id of that model.

I need a computed property on that model because anytime a product is shown on the site, the UI needs to reflect whether the item is already in the saveditem ember-data store or not.

Example of if the item is not on the list (but can be added): enter image description here

Example of an item that is on the list (but can be removed): enter image description here

I was thinking that on my userprofile service which manages the user's data across the app, I could have a computed property that outputs an array of ids from the saveditem model:

savedItemsList: computed('WHAT.IS.DEPENDENT.KEY?.[]', function() {
    return this.get('store').peekAll('saveditem').map(item => item.id);
}),

And then in the template I could use a composable helper to see if the item being displayed is in the list or not:


    ...show already-saved button...

    ...show save button...


The question: what would the dependent key be for this computed property? OR...is this method stinky and and there's a better way to do it?

I have tried:

savedItemsList: computed('store.saveditem.[]', function() {

(after of course injecting the store). Seems like the obvious one but it doesn't update when records are added or removed from the saveditem store. Also tried 'store.saveditems.[]', permutations with and without array brackets, and NO dependent key - all no worky.

Makes me wonder whether this is not possible for a good reason ;) I might be "fighting the framework" here. Any help appreciated!




samedi 9 décembre 2017

Difference between action and closure action

As a newbie I was wondering how to understand the differences between action and closure action.More important thing I would like to know is when do we use which one and why?




vendredi 8 décembre 2017

ember JSONAPISerializer methods not working

I have an underscored API response and in my JSONSerializer i’m overriding keyForAttribute but it is not working and i placed a debugger in keyForAttribute function it is not firing at all.

I also tried adding attr properties but it is not working as well.

here is my Serializer:

import DS from "ember-data";
import { underscore } from "@ember/string";

export default DS.JSONSerializer.extend({
  keyForAttribute(attr) {
    return underscore(attr);
  },


 attrs: {
   documentType: 'type',
   coverUrl: "cover_url",
   mainTopic: "main_topic",
   publicationDate: "publication_date",
   globalReads: "global_reads",
   localReads: "local_reads"
 },
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    return {
      data: payload.documents.map((item, index) => {
        return {
          id: index,
          type: "document",
          attributes: item
        };
      })
    };
  }
});

and here is my model

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  coverUrl: DS.attr('string'),
  authors: DS.attr(),
  institution: DS.attr('string'),
  documentType: DS.attr('string'),
  publicationDate : DS.attr('date'),
  mainTopic: DS.attr('string'),
  globalReads: DS.attr('number'),
  localReads: DS.attr('number'),
});

and here is part of my API response:

    {"title": "World War 2",

    "frequency": "Monthly",
    "type": "THESIS",
    "languages": [
        "ENGLISH",
        "ARABIC"
    ],
    "doi": "10.1000/182",
    "descriptors": [
        "ARTS",
        "PSYCHOLOGY"
    ],
    "keywords": [
        "history",
        "adolf hitler",
        "war"
    ],
    "affiliation": "history",
    "isbn": "978-92-95055-02-5",
    "institution": "History Palace",
    "eissn": 2312,
    "pissn": 1595,
    "document_id": "1",
    "publication_date": 1512346539773,
    "main_topic": "ARTS",
    "document_abstract": "some document abstract here",
    "cover_url": "http://ift.tt/2BQ9khs",
    "content_url": "http://ift.tt/2BQ9khs",
    "global_reads": 244,
    "local_reads": 102,
    "translated_title": "الحرب العالمية الثانية",
    "dewey_number": "900-999",
    "program_type": "MASTER",
    "publishing_country": "NEW_ZEALAND"
},

any help would be very appreciated.

Thank you.




Dividing code between Rails and a MVC JS framework

When making a Ruby/Rails SPA app with an MVC JS framework such as Angular or EmberJS, I am unsure how to divide the code between the Rails and the JS framework, as both are MVC.

Rails 5.1 is a lot better with a JS MVC framework compared to Rails 5.0, but it is still clear that Rails wants the view part to be thin. The problem then is the JS framework wants the backend to just be pretty much just an data backend.

So the question is, when using Rails with a MVC JS framework, how to divide and structure the code as the two have fundamentally different opinion how the app should be structured?

Or is the answer, don't use Angular or EmberJS with Rails, but rather something such as VueJS which only does the View part?

Are there books, online courses, or perhaps blogs posts that explains this dilemma?




Nested routes in ember with several ids

I am at the start of creating a new ember application. I am quite familiar with Ember 1.x, but this is my first real dive into 2.x.

I am not quite sure about what is nesting and what is not in the terms of ember routing, but what I think I am trying to accomplish is a bit of a nested route.

Perhaps easier if I tell you about how I'd wish it too look through the url. https://localhost:4200/modules/123/block/123/version/123 where modules is the main route which will list specifically all modules. When I click on a specific module, I want it to load the module in the right column of the page with the sidebar still intact to the left. From there I can click onto one of the blocks which is in relationship to the module, and then to the version.

How can a nested routing like this most easily be setup? I am not clear about the terms here, so feel free to correct me.

This is basically how I thought so far, without success:

Router.map(function () {
  this.route('modules', () => {
    this.route('module', { path: '/modules/:module_id' }, () => {
      this.route('block', { path: '/block/:block_id' }, () => {
        this.route('version', { path: '/version/:version_id' })
      });
    });
  });

  this.route('login');
});




How to use nested routes with several parameters in ember 2.17

I am trying to build an smarthome app and I am stuck with calling nested routes with serveral parameters. I want to show an information which user is logged in and below that template which is in my parent route i want to render child pages for showing households. After a specific household is chosen, i want to show the rooms in the household and then devices. This is my router.js

    Router.map(function() {
      this.route('about');
      this.route('users', function() {
      });
      this.route('households', { path: '/:user_id' }, function() {
        this.route('index', { path: '/:user_id' })
        this.route('rooms',{ path: '/:household_id' });
        this.route('devices', { path: '/:room_id' });
      });
    });

export default Router;

I link to households like this

  <h3></h3>

and now I want to declare a model in the route of households.js which returns an user from the ember data store and render the parent template. Afterwards the model should redirect to households.index with the user.id too and the households.index.hbs should render all households below the parent template. My households.js route looks like this:

export default Route.extend({
  model(params){
    {
      return this.get('store').findRecord('user', params.user_id);
    }
  }
});

and my household.index route like this

export default Route.extend({
    model(params) {
       return this.get('store').findAll('household').then(results => results.filter((site) => {
           return site.get('member').filter(x => x == params.user_id).length > 0;
       }));
      }
});

Actually the following error occurs:

Error: Assertion Failed: You attempted to define a but did not pass the parameters required for generating its dynamic segments. You must provide param user_id to generate.

In general I need serveral parameters in all nested routes/subroutes, because I need the user_id for example in the route devices for checking if the calling user is a admin. If he is an admin he would be able to add and edit devices. And i need the room_id to show only devices which are in the chosen room.

Is there any way to pass serveral parameters or using the controllers in a way, I can handle my purpose?




Include node_module into Ember component

I am trying to add wavesurfer to my application. I did exactly according to the instructions. at: http://ift.tt/2y82gKw

After I did bower install I had wavesurfer.js folder inside my node_modules

import WaveSurfer from 'wavesurfer.js';

Theoretically WaveSurfer class should be available on my component. But after I include above code I have this error

Uncaught Error: Could not find module wavesurfer.js
at requireModule (loader.js:58)
at reify (loader.js:41)
at requireModule (loader.js:69)
at Class._extractDefaultExport (ember-resolver.js:390)
at Class.resolveOther (ember-resolver.js:122)
at Class.superWrapper [as resolveOther] (ember.debug.js:17407)
at Class.resolve (ember.debug.js:4597)
at Registry.resolve [as resolver] (ember.debug.js:4437)
at resolve (ember.debug.js:2109)
at Registry.resolve (ember.debug.js:1715)

I killed almost a week on this.

How can I make that class available for my component

Thanks




Ember build rename images in public/assets folder

I work on employees contact listing app. I use firebase database to store employees data like name, phone, email as well as a path to employee picture. For an employee picture, I use images stored at assets/employees and store that image path in a user profile stored in firebase database. Everything works well on local server but when I build my app so I can deploy it to firebase, ember build rename images in dist folder. public/assets/employees/john-doe.jpg => dist/asstes/employees/john-doe-6d468a6c10b6d17b6a4dc3b4633378dd.jpg

After deploying to firebase, user images aren't shown (because of renaming).

Can I prevent ember build to rename files? Thanks.




Using Rest Client in Ember JS without ajax call

I am actually new to ember js.I have a requirement such that i have to invoke a external service using post and get the json data.And i should be doing it like how we do in java to invoke the sevices using restclient.I am not supposed to make an ajax call for that.I was able to find some document which states we can use DS.RESTAdaptor.The sample code snippet is as below

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    host: 'https://api.example.com'
});

So I am able to figure out some way i can utilize it.But still i am not able to figure out how i can send my JSON Data in POST method and also how to get the response.Can anyone help me out how to do it in ember without using a ajax call.




jeudi 7 décembre 2017

Cytoscape add custom image to node with clickable items on it

I am building a charting tool in ember using cytoscape js and I can render chart data however I do not know how to set each node to display with a image that has other images/buttons that function within it. Basically I want it to look like this:

enter image description here

In the image there are two buttons (I will most likely add icons as well) and also there are labels that exist within the node which I don't know how to do either.

Here is the code I currently have.

Template:

<div class="container" >
  <div id="cy"></div>
</div>

Component JS:

import Ember from 'ember';


export default Ember.Component.extend({
tagName: '',

map: Ember.computed('model.map_data', function()
{
 if(this.get('model.map_data')){
   return JSON.parse(this.get('model.map_data').data)
  } else {
   return {};
  }
 }),
cytoscape_data: Ember.computed('model.sub_apps.[]',function() {
var ret = {
        nodes: [],
        edges: []
};
var red = 50;//replace with threshold
var green = 25;//replace with threshold
var _this = this;
this.get("model").map_data.forEach(function(node) {
  var y= 0;
  var x = 0;
  var color = 'green';
  if(node.value >= red ){
    color = 'red';
  }else {
    if(node.value > green){
      color = 'orange';
    }
  }
  var position = _this.get("map")["app" + node.id];
  if(position){
    x = parseInt(position.split(',')[0]);
    y = parseInt(position.split(',')[1]);
  }
  ret["nodes"].push({
          data: {
                  id: node.id,
                  label: node.name,
                  node_type: 'app',
                  tooltip: node.description,
                  color: color
          },
          position: {
                  x: x,
                  y: y
          }
  });
  if(node.relations) {
    node.relations.forEach(function(parent) {

      ret["edges"].push({
        data: {
          source: node.id,
          target: parent.app_to_id
        }
      });
    });
  }
});

 return ret;
}),

didInsertElement: function() {
 this._super();
var cy = cytoscape({
  container: Ember.$('#cy')[0],
  elements: this.get("cytoscape_data"),
  zoom: 1,
  pan: { x: 0, y: 0 },
  fit: true,
  randomize: false,
  layout: {
      name: 'preset'
    },
  style: [
    {
      selector: 'node',
      style: {
        'content': 'data(label)',
        'text-opacity': 0.8,
        'text-valign': 'center',
        'text-halign': 'right',
        'width': '200px',
        'height': '200px',
        'border-color': 'green',
        'border-width': 3,
        'border-opacity': 0.5,
        'background-image': 'url(../assets/images/base_node_image.svg)'
        // 'background-color': 'data(color)'
      }
    },
    {
      selector: 'edge',
      style: {
        'width': 6,
        'border-color': 'green',
        'target-arrow-shape': 'triangle',
        'target-arrow-color': 'red',
        'opacity': 1,
        'curve-style': 'bezier'
      }
    },

    {
      selector: ':selected',
      style: {
        'background-color': 'orange',
        'opacity': 1
      }
    },

    {
      selector: '.faded',
      style: {
        'opacity': 0.0,
        'text-opacity': 0
      }
    },
  ],

});
Ember.run.scheduleOnce('afterRender', this, function(){
  cy;
});
cy.on('click', 'node', function(evt){
  var node = evt.target;
  console.log( 'clicked ' + node.data('label') );
   });
  },
});

The chart this code renders looks like this:

enter image description here

I can display a background-image however it displays in a circle which I dont know how to get rid of. The color of the circle is determined by some logic above which was a test to see if it works and that is fine (going to use that for one of the icons on the node later). I can also display the label for the node but I don't know how to display that within the node itself.

Any help is appreciated, thanks!