samedi 31 mars 2018

Ember: When is a controller instantiated

I was going through the Ember tutorial in https://guides.emberjs.com/v3.0.0/routing/preventing-and-retrying-transitions/#toc_storing-and-retrying-a-transition

Here, in order to store and retry a transition, they're setting an instance property previousTransition in loginController.

How does controllerFor work? Will loginController not be instantiated again when routed to the corresponding route?

How is previousTransition persisted so that they're accessing it in loginController?

I'm new to Ember. Could someone throw some light on this?




vendredi 30 mars 2018

Javascript - Scroll container with transcript while the aduio player

I have an audio player that plays an mp3 file and a container underneath that displays a transcript of the text. The audio file is split into 2 channels so there's one speaker on the left of the transcript and one on the right.

As the audio is playing, I'd like to be able to gradually scroll the container in sync with the audio so that the portion that is playing on the audio file is at the top of the transcript container at the time. I'd also like to be able to pause the scrolling as I pause the audio player, or jump to the portion of the transcript as I use the scrubber of the audio player.

In other words, I want the transcript container to stay in sync with the audio without having to manually scroll the container. I'm not sure the best way to go about doing this, but I know I'd like to avoid jQuery if possible.

Thanks, Brennan




jeudi 29 mars 2018

Localize Ember-power-select "No results found" text

I am having a hard time finding out how to localize this string that appears to be coming from ember-power-select: "No results found"

"No results found" text in dropdown

This string is nowhere to be found in our app's codebase.

Searching around google did not yield any results, so, while the solution may be in the docs, it'd be nice to have an easy to find stack overflow page linking to it.

EDIT: In the docs, I see I should use the noMatchesMessage: http://ember-power-select.com/docs/api-reference (I'll also be setting loadingMessage and searchMessage)

HOWEVER

I don't know how to set these options globally.




ember issue with template sidebar display

With Ember I have a login page that I do not want to display the header/sidebar navigation for my site. Once isAuthenticated then I want them to show. I can get this to work by checking for session.isAuthenticated in application.hbs. If true I show the header and sidebar if not I do not display them.

This all works but once I login and transition to the default authenticated route the javascript for the sidebar dropdown does not work. When I click the links nothing happens. If I then transition to a different route they work. I'm guessing it's since I am not generating them when I first load the page because I am not authenticated.

Is there a better way to handle this or force a reload of the javascript?




Checkbox focus is not showing in IE and Firefox while pressing Tab keys

The checkbox is not getting focus while pressing the Tab keys for the IE and Firefox. But if I press enter or using mouse, the checkbox is working fine. For the Chrome, the focus are showing clearly.

When I'm Inspect (F12) the checkbox, I have find the Id name called "delete-for-reals"

So I have find the id names on my projects in

CSS file:

.delete-for-reals img,
.delete-for-reals input {
  vertical-align: middle;
}
.delete-for-reals .rsuite-message {
  vertical-align: -2px;
}

Hbr File:


        <p class="delete-for-reals">
            <label for="delete-for-reals">
                
                
                
                    
                
                    
                
            </label>
        </p>
    

Dialog.less file:

.delete-for-reals {
    img, input {
        vertical-align: top;
    }
    .rsuite-message {
        vertical-align: -2px;
    }
}

I'm really don't know there is having problem with either ember javascript or CSS or anything.

Please anybody help me on this. Thank You




mercredi 28 mars 2018

I have an enum in my Typescript / Ember 3.1 app and I am getting import errors at runtime. What's going on?

I have an ember component that is importing an enum type as follows:

import { StateNames, CardSummary } from '../../types/snowcat/state-types'

the type file is as follows:

export enum CardState {
  error = 'error',
  new = 'new',
  okay = 'okay',
  warning = 'warning',
}

I'm then using the enum as follows in the component:

  @computed('cardSummary.cardState')
  get type(): string {
    if ([CardState.new, CardState.okay, CardState.warning].includes(this.cardSummary.cardState)) {
      return 'info'
    }
    return 'error'
  }

Everything seems fine with the code. I am not getting any TypeScript errors when the code builds, but I am getting a runtime error:

loader.js:247 Uncaught Error: Could not find module `types/snowcat/state-types` imported from `snowcat/models/certificate`
    at missingModule (loader.js:247)
    at findModule (loader.js:258)
    at Module.findDeps (loader.js:168)
    at findModule (loader.js:262)
    at requireModule (loader.js:24)
    at r (loader.js:176)
    at ember-data.js:39
    at Array.forEach (<anonymous>)
    at getDsModels (ember-data.js:36)
    at getModels (ember-data.js:66)

What's going on? How do I fix this?




JSONAPI-Serializer: Deserialize function doesn't update attributes key for nested objects

I am using JSONAPI-Serializer to serialize/deserialize my json object in Node js. See below the json object

{
"links": {
},
"meta": {
},
"data": [{}],
"included": [
    {
        "type": "obj1",
        "id": "",
        "attributes": {
            "newId": "",
            "type": "abc",
            "tag": [
                ""
            ],
            "systemTag": {
                "system_Tag": [
                    "mydeal"
                ]

At the end of this json you can see the "systemTag" key as camelCase and its value "system_tag" as snake_Case. When I serialize both key and value it is serialized to snake_Case as system_tag but When I deserialize only key is converted back to camelCase not the value as you can see in the above json.

While deserializing I have used the attribute "keyForAttribute: 'camelCase'" of JSONAPISerializer with my model object.

It would be great help!




How to remove records in store when they are not in server anymore

I have application which may lost connection with server for days and when it finally reconnect some record exist in store didn’t exist in server any more.

I try to fix it but can’t get any where.

store.findall didn’t seems to have option to delete record not returned by server.

I can’t find ways to chain store.unloadAll and store.findAll without have the blank state take effect on the screen and cause flickering

I also can’t find out how to get what actually returned by server without go completely manual (make my own ajax calls,which won’t scale obviously)

I am wondering what everyone else is using in this situation

Thanks for any help




Accessing Nested JSON in Ember Model

I'm trying to access a particular ID which is nested inside my model to make a belongsTo association. I have no trouble getting what I need in my template, but need image_id within my model. Below is my JSON and current model.

{
  content: {
      title: 'Title',
      header: 'Header',
      image_id: 1
  }
  slug: 'slug',
  title: 'Welcome'
}

Here is my current model...

import DS from 'ember-data';

const { attr } = DS;

export default DS.Model.extend({
  content: attr(),
  title: attr('string'),
});

Hope this makes sense!! Thanks!




Receiving 'bar.transition is not a function' error in d3 animated stacked bar chart

I am trying to create a stacked bar chart in D3v4 for my Ember project that can transition and uses the General update Pattern. I using this bl.ock example as a template base

I am failing at the last hurdle by struggling to draw the bars on the graph. The axis are fine and render correctly. When I try to draw the bars I get an error in the console to say that bars.transition is not a function.

The bars method is being imported correctly and if I comment out the transition and just try to draw the bars straight on, I receive a new error that bars.enter is not a function. I am guessing this is because somewhere I am referencing something incorrectly.

Any help greatly appreciated.

Chart code:

buildChart(){
let data = this.get('data')

let svg = select(this.$('svg')[0]),
    margin = {
      top: 20,
      right: 30,

      bottom: 30,
      left: 60
    },
    width = this.get("width"),
    height = this.get("height");
let x = scaleBand()
      .domain(data.map(function(d) {
        return d.label;
      }))
      .rangeRound([margin.left, width - margin.right])
      .padding(0.1);
let color = scaleOrdinal(["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f"]);
let y = scaleLinear()
        .rangeRound([height - margin.bottom, margin.top]);

var x_axis = axisBottom(x);
var y_axis = axisLeft(y)
svg.append("g")
            .attr("transform", "translate(0," + y(0) + ")")
            .attr("class", "axisWhite")
            .call(x_axis)

svg.append("g")
            .attr("transform", "translate(" + margin.left + ",0)")
            .attr("class", "axisWhite")
            .call(y_axis)

let columnKeys = ["count1", "count2", "count3"]

let stacks = stack()
            .keys(["count1", "count2", "count3"])
            .offset(stackOffsetDiverging)
            (data);

function stackMin(h) {
            return min(h, function(d) {
              return d[0];
            });
          }
function stackMax(h) {
            return max(h, function(d) {
              return d[1];
            });
          }
          var x_var = "label";

redraw(data)

function redraw(data) {
 //update Y scale
 y.domain([min(stacks, stackMin), max(stacks, stackMax)])

 svg.select(".y")
        .transition()
          .call(customYAxis);

          // each data column (a.k.a "key" or "series") needs to be iterated over
          // the variable columnKeys represents the unique keys of the stacks
          columnKeys.forEach(function(key, key_index){

            var bar = svg.selectAll(".bar" + key)
                        .data(stack(data)[key_index], function(d){ return d.data.label + "-" + key; });
                    bar
                      .transition()
                        .attr("x", function(d){ return x(d.data.label); })
                        .attr("y", function(d){ return y(d[1]); })
                        .attr("height", function(d){ return y(d[0]) - y(d[1]); });

                    bar.enter().append("rect")
                        .attr("class", function(d){ return "bar bar-" + key; })
                        .attr("x", function(d){ return x(d.data.label); })
                        .attr("y", function(d){ return y(d[1]); })
                        .attr("height", function(d){ return y(d[0]) - y(d[1]); })
                        .attr("width", x.bandwidth())
                        .attr("fill", function(d){ return color(key); })

                  });
}

function customYAxis(g) {
      g.call(y_axis);
      g.selectAll(".tick:not(:first-of-type) line").attr("stroke", "#777").attr("stroke-dasharray", "2,2");
      g.selectAll(".tick text").attr("x", 4).attr("dy", -4);
    }

}

Unfortunately I'm unable to set up a fiddle or a twiddle. I've never been able to set Ember components up in them correctly.

I import the D3 functions from the ember-d3 add on




Uploading canvas image to S3 through ember uploader

I was using ember uploader to upload file to S3. Now, I have a use case where I need to upload CANVAS image to S3. In this case, I don't have a file but just the image data

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAgAEl>EQVR4Xu1dd7xUxfU/r/fOoxd77y3GmFhiNFGsARtFEKQoTRFsKFhQsdAsgEoTEAUsWJNoEn9RY4nGEmLsUl7h8frj9bfl9zmz7LJ735Z7Z+/dvbN85x/.........."

Is there a way of doing this through ember uploader?




mardi 27 mars 2018

How to handle ember checkbox binding

I am new with ember and I have a question about checkbox binding.

Here is my js && hbs :

 CompletedToday(id){
          var today = new Date().toISOString().slice(0, 10);
           this.get('DS').findRecord('menu',id).then((recs) => {
              recs.get('completedDates').pushObject(today);
              recs.save();
            });
      },







Menu is a model has a attribute called Completed date, which is a array contains a list of dates(YYYY-MM-DD), there should be a constructor function to check if it’s completed TODAY, if it is completed, make the checkbox of that menu as checked. If not, user can check the specific checkbox I don’t know how to handle this actually, do i need to create another attribute for menu?

Any suggestion would be appreciated




Ember link-to on table row issue

I am trying to use a link-to around a whole table row. Here is how I am setting it up:


    
        <td>
        
        </td>
        <td>
        <strong></strong>
        </td>
        <td>
         
        </td>
    


I see the data but it is not a clickable link, just text. Any ideas on what I am doing wrong?




How to select option Ember Javascript from web browser developer tools

I am trying to select a desired value from dropdown menu in browser developer tools with Javascript. The following picture shows the content of the page.

Web content

But whenever I select another value with code and then click the save button, the changes are not actually saved. When I select normally with my mouse and click the save button, it changes normally.

I have tried the following stuff. These seemingly changed the value of selected dropdown menu (it shows 2 when I write the code) but cannot be saved afterwards.

1- document.getElementById('channel24g_ctrl')[2].selected = true

2- document.getElementById('channel24g_ctrl').options.selectedIndex = 2

3- document.getElementById('channel24g_ctrl').options[2].selected = true

4- document.getElementById('channel24g_ctrl').options[2].click()

5- document.getElementById('channel24g_ctrl').options[2].setAttribute("selected", "selected"); document.getElementById('channel24g_ctrl').options[1].removeAttribute("selected");

I might have tried some other combinations of those above. Only the fifth actually makes target option "selected" but it still doesn't work when save button is clicked. I am no expert with javascript or ember but I have done similiar things before with other websites and succeeded. So maybe the problem is with Ember Framework?

What else can I do?




Ember-moment how to format the date/time according to locale

I'm stick with how to format a date/time using ember-moment add-on using a browser locale. I defined the included locales in environment.jsas explained in their README: moment: { includeLocales: true } Then in a handlbars template I try to display the date: But the date is still displayed in US format: 03/27/2018 instead of the French one. Any ideas on how to fix that ? Thank you.




lundi 26 mars 2018

ember.js page context with multiple nested routes and hasMany relationships

I'm brand new to ember.js (started with 3.0) and struggling to achieve what I would expect is a fairly conventional use case without using what seems like unconventional methods or soon to be deprecated features.

The use case in Ember is to display, and paginate, multiple related resources on a parent resources page.

I'm really enjoying using Ember so far but a little exasperated that such a simple use case has been so difficult to overcome. Been ok with the learning curve with everything else so far, but I've hit a wall here.

I have a JSON API backend, with a reasonably complex, (mostly) normalized DB where there are a few key resources and multiple join tables describing the various ways they can relate to each other.

Stripped down setup below:

Models:

// app/models/label.js
export default DS.Model.extend({
  name: DS.attr(),
  contactInfo: DS.attr(),
  releases: DS.hasMany('release'),
  artists: DS.hasMany('artist'),
  //...
});

// app/models/artist.js
export default DS.Model.extend({
  name: DS.attr(),
  realname: DS.attr(),
  profile: DS.attr(),
  labels: DS.hasMany('label'),
  //...
});

// app/models/release.js
export default DS.Model.extend({
  title: DS.attr(),
  released: DS.attr(),
  label: DS.belongsTo('label'),
  //...
});

Router:

  // app/router.js
  //...

  // labels
  this.route('labels', function() {
    this.route('label', {path: '/:id'}, function(){
      this.route('artists');
      this.route('releases');
    });
  });
  // artists
  this.route('artists', function() {
    this.route('show', {path: '/:id'});
  });
  // releases
  this.route('releases', function() {
    this.route('show', {path: '/:id'});
  });
  // ...

Routes:

// app/routes/labels/label.js
export default Route.extend({
  model(params){
    return this.store.findRecord('label', params.id)
  }
});

// app/routes/labels/label/artists.js
export default Route.extend({
  model(){
    let label = this.modelFor('labels.label')
    return label.query('artists')
  },
});

// app/routes/labels/label/releases.js
export default Route.extend({
  model(){
    let label = this.modelFor('labels.label')
    return label.query('releases')
  },
)};

Templates:

// app/templates/application.hbs
<h1> Welcome to Ember! </h1>


// app/templates/labels/label.js
<h2></h2>

<h4>Artists</h4>
// insert sensible way to render artists here

<h4>Releases</h4>
// insert sensible way to render releases here


Strategies I've attempted so far:

  1. Calling a labels related artists and releases directly in the labels/label template, ignoring the nested routes for relations and passing the promise into a component, or using

This gets the context lazily onto the page, but pagination here was a nightmare. Using the ember-data-has-many-query extension I managed to cobble together a controller action for the labels.label route:

// app/controllers/labels/label.js
export default Controller.extend({
  queryParams: ['artistsPage'],
  artistsPage = 1,
  actions:{
    pageArtists(direction){
      // console.log(direction)
      const label = this.currentModel;
      if(direction == 'forward'){
        let artists = label.query('artists', {page: this.artistsPage+1});
        this.set('artistsPage', this.artistsPage+1);
      }else if (direction == 'back'){
        let artists = label.query('artists', {page: this.artistsPage-1});
        this.set('artistsPage', this.artistsPage-1);
      }

    }
  }
 });

This is very broken though in that the route knows nothing about the param being set in the action, so on any page refresh they decouple. I abandoned trying to get the labels.label routes model hook to play nicely with the controller params in lieu of another approach:

  1. Using nested routes (as shown above) to handle the relations independently of the parent, and load them in individually into the label route.

Status Quo:

I'm attempting to use named outlets, but haven't been able to get the context onto the page without hitting a single related resources url, eg /labels/123/artists or /labels/123/releases.

So :

  // app/routes/labels/label/artists.js
  // ...
  renderTemplate(){
    this.render({
      'into':'labels/label',
      'outlet':'artists'
    })
  }

Will get the context into the named outlet in templates/labels/label, but I can't repeat this for the releases relation because we are at /labels/123/artists.

Attempting to set renderTemplate in the labels.label route, ie:

this.render('labels/label/artists',{
  into: 'label/label',
  outlet: 'artists',
  controller: 'labels.label.artists'
})

doesn't actually render the route and/or send it to the outlet.

Ultimately I'm hoping to use a pagination approach similar to the one described by Balint Erdi here which implements nested routes and some custom adapter logic to handle the pagination for related resources.

The desired behaviour is for the relationship contexts to be displayed, along with pagination at the url labels/123.

I've exhausted looking through the guides, API documentation, discourse forum and here, and still at a loss.

What (assuming multiple things) am I doing wrong here?




samedi 24 mars 2018

EmberJS - How to remove an object from hasMany relationship and then repush it?

I try to remove a model from a relationship and later import it again by using pushPayload.

The relationship is only updated on one side but not an the reverse side.

this.get('store').pushPayload({
  folder: {
    id: 1,
    name: 'My folder'
  }
});

this.get('store').pushPayload({
  item: {
    id: 2,
    name: 'My item',
    parentFolder: 1
  }
});

var folder = this.get('store').peekRecord('folder', 1);
var item = this.get('store').peekRecord('item', 2);

console.log('Parent folder id: ', item.get('parentFolder.id'), 'Items length', folder.get('items.length'));
item.get('parentFolder').get('items').removeObject(item);
console.log('Parent folder id: ', item.get('parentFolder.id'), 'Items length', folder.get('items.length'));

this.get('store').pushPayload({
  item: {
    id: 2,
    name: 'My item',
    parentFolder: 1
  }
});
console.log('Parent folder id: ', item.get('parentFolder.id'), 'Items length', folder.get('items.length'));

I would expect to get the following output:

Parent folder id:  1 Items length 1
Parent folder id:  undefined Items length 0
Parent folder id:  1 Items length 1

But I get this one:

Parent folder id:  1 Items length 1
Parent folder id:  undefined Items length 0
Parent folder id:  1 Items length 0

The issue is the last Items length.

https://ember-twiddle.com/d58d95d5be0cc8750282b9cc48db6489




How to load model data i application template for authenticated users

I followed ESA dummy app example steps to implement implicit grant authentication. It works fine, but I wonder how to proceed in the below situation: - usually we define navbar, in the application template - application.js route is defined like that - I need to load all the shops in a drop-down list in the navbar of application template only if a user us authenticated. - in application.hbs template I defined the select list as follows:


        <li class="nav-item">
          <select>
            
              <option value=></option>
            
          </select>
        </li>
      

  • if I add a model hook to the application.js router:

    model() {
        if (this.get("session.isAuthenticated")) {
          return this.store.findAll('shop');
        }
      },
    
    

it works, but I have to refresh the page to have the drop-down list populated. Any ideas ? Thank you.




vendredi 23 mars 2018

ember handlebars: find which addon is defining a helper (Not present in app/helpers)

Having a hard time finding out where a helper not in app/helpers is defined. The helper was very generically named, I searched my package.json for the helper name but there was nothing. I was stuck hunting around with google to try and figure out what addon defined it.

Given some helper () how would one go about finding where it's defined?

(I happen to be on Ember 2.13)

(Note: the helper was contains defined in ember-composable-helpers, so it would have been a LITTLE helpful to search package.json for "helper" but that is a pretty tedious in-direct way of searching, which have may not even yielded the answer)




Ember.computed.sort on belongsTo properties

I am trying to use Ember.computed.sort and can't figure out how to sort by the name of a belongTo property. I have been on GOogle for hours and can't find the right combination. help please!

// my model
export default DS.Model.extend({
        targetName: DS.attr(),
        targetType: DS.attr(),
        rack: DS.belongsTo('rack', {async: true}),
});

// this works:
export default Ember.Controller.extend({
    sortedTargets: Ember.computed.sort('model', 'sortDefinition'),
    sortDefinition: ['targetType']
});

// this doesn't work :
export default Ember.Controller.extend({
    sortedTargets: Ember.computed.sort('model', 'sortDefinition'),
    sortDefinition: ['rack.name']
});




Where does "this.get('filter')" comes from?

I've been following tutorials from Embers website and at certain point they do:

let filterInputValue = this.get('value');
let filterAction = this.get('filter');
filterAction(filterInputValue).then((filterResults) => this.set('results', filterResults));

And as far as I know this.get('filter') is the same thing as doing this.filter or this['filter'], right? I've been looking to their documentation about Component and its base object, since attributes/functions can be inherited, to find out about this filter but was unable to find it.

So, where does filter comes from?




Ember helper is not defined

I can't figure out why the helper I created in app/helpers/shop-name.js:

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

export function shopName(shop) {
  return shop.identifier + '-' + shop.name;
}

export default helper(shopName);

is not available in my template application.hbs:

<select>
  
    <option value=></option>
  
</select>

I get the template compilation errors.

I'm using Ember 3.0. Thank you.




Ember js -- remove duplicates from an array

I am trying to clean up a validation script.

So if the file type uploaded is wrong -- like an image instead of a pdf. I need the alert to say -- Wrong file type uploaded, only pdf accepted.

https://jsfiddle.net/mf78otve/37/

so the validation string looks like this

"application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf"

but really need to clean it up -- pdf, x-pdf, vnd.pdf, pdf, x-pdf

then remove duplicates to then pdf, x-pdf, vnd.pdf

var validations = "application/pdf, application/x-pdf, application/acrobat, applications/vnd.pdf, text/pdf, text/x-pdf";

console.log("validations", validations);

var res = validations.split("/");
console.log("res", res);


var uniqueArray = function(arrArg) {
  return arrArg.filter(function(elem, pos,arr) {
    return arr.indexOf(elem) == pos;
  });
};


console.log(uniqueArray(res));




Ember js -- validating file type

Is there a file type validation in Ember js. I've tried to find a validator - but only found more generic validators.

https://www.npmjs.com/package/ember-validations

https://www.npmjs.com/package/ember-file-upload

I am looking to invoke a validator to check for particular accepted file types -- like pdf, ppt.




Uncaught TypeError: form.get is not a function while submitting the form

I'm having issue while executing the below code while submitting the form

finally {
  var form = params.data.form;
  var collider = params.data.collider;
  form.get(0)[collider](); //error line
}

The error which I'm getting as:

Uncaught TypeError: form.get is not a function
at HTMLIFrameElement.winLoader (iframe-transport.js:147)
at HTMLIFrameElement.dispatch (jquery-2.1.3.js:4437)
at HTMLIFrameElement.elemData.handle (jquery-2.1.3.js:4123)

Please help me on this issue. Thanks in advance.




Ember convert PATCH call to PUT

I am using ember 2.18, in this the update requests are PATCH. However, the backend is in SAILS and it does not support PATCH. Hence, I have to convert patch request to PUT.

I saw this issue and people seems to have solved it there. But it does not work for me. The code is as follows:

import App from './../app';
import DS from "ember-data";
import { computed } from "@ember/object";
import { camelize } from '@ember/string';

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

export default DS.JSONAPIAdapter.extend({
  coalesceFindRequests: true,
  host: App.GPT.Configuration.restServer,
  methodForRequest: ({ requestType }) => {
    console.log('Log')
    if (requestType === "updateRecord") {
      return "PUT";
    }

    return this._super(...arguments);
  },
  pathForType(type) {
    return camelize(type) + 's';
  },
  headers: computed(function () {
    if (!App.StoreUtil.getSessionId()) {
      if (App.GPT.ApplicationController) {
        App.GPT.ApplicationController.set("hasMessages", [
          {
            message: "Session expired."
          }
        ]);
        App.GPT.ApplicationController.transitionToRoute("/");
      } else {
        window.location = "/";
      }
    }
    return {
      sid: App.StoreUtil.getSessionId()
    };
  }).volatile()


});

The code added to convert the request to PUT is :

methodForRequest: ({ requestType }) => {
    console.log('Log')
    if (requestType === "updateRecord") {
      return "PUT";
    }

    return this._super(...arguments);
  }

However, the method is not called at all. The funny part is pathForType is called for every request.




jeudi 22 mars 2018

How to set focus to a dynamically generated input field (textbox) in ember

I have two textboxes which are dynamically generated, below is the html of the textboxes

enter image description here

two text boxes

How do i focus any 1 textbox ?

i tried the below code

    $('.answer_1').focus();

but that dosent seem to be work, is there any other way where i can set focus to the textbox programmatically?




Call a nested Rails route from Ember App

How to call a nested Rails route from Ember app if I don't need nested templates ? I have the following routes in Rails router:

# routes.rb
resources :shops do
  resources :shop_languages
end

So to get a list of shop languages the shops/:shop_id/shop_languages should be hit.

Here is ShopsLanguagesController:

# controllers/shop_languages_controller.rb
class ShopLanguagesController < ApplicationController
  before_action :find_shop

  def index
    json_response @shop.shop_languages, :ok, include: 'language'
  end

  private

    def find_shop
      @shop = Shop.find(params[:shop_id])
    end
end

In Ember app I have the routes defined as follows:

# router.js
Router.map(function() {
...
  this.route('languages', { path: '/shops/:shop_id/shop_languages'});
});

In Ember application.hbs template the languages link is defined as follows

# application.hbs

..


In Ember languages.js route handler, I'm trying to load shop languages:

# routes/languages.js
model(params) {
  return this.store.query('shop-language', { shop_id: params.shop_id })
}

Ember hits /shop-languages end-point instead of the nested one shops/:shop_id/shop_languages.

Of course, I've defined the corresponding models on Ember side:

# models/shop-language.js
import DS from 'ember-data';

export default DS.Model.extend({
  shop: DS.belongsTo('shop'),
  language: DS.belongsTo('language'),
  modified_by:  DS.attr('string')
});

What is wrong with that and how to get it work? Thank you




Filtering using dropdown based on the uniq event name

i would like to add a filtering for my records of my table based on the value that I selected on my dropdown.Btw, I am using power-select. This is how my template looks like

  <table>
    <tr>
      <th>
        Event Name
        
          
        
      </th>
    </tr>

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

And on my route.js this is how it looks like

 model() {
  const { date } = this.paramsFor('dashboard.route-name');
  return this.queryModel(date);
 },

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

   const { date } = this.paramsFor('dashboard.route-name');
   controller.set('selectedDate', date);
 },

 queryModel(date) {
   date = date || moment().format('YYYY-MM-DD');

   return this.store.query('modelName', {
    filter: {
      'created-at:between': `${date} 00:00:00,${date} 23:59:59`
    },
      sort:    'updated-at'
   });
  }

and on my controller.js I have the following below

 import Ember from 'ember';

 export default Ember.Controller.extend({
   modelNames:    Ember.computed.alias('model'),
   eventNames:    Ember.computed.mapBy('modelNames', 'eventName'),
   uniqEventName: Ember.computed.uniq('eventNames'),

   actions: {
    selectDate(date) {
      this.transitionToRoute({ queryParams: { date }});
    },

    selectEventName(eventName) {
      console.log(eventName);
    }
  }
 });

My question is How would I filter my records based on the eventName that I selected on my dropdown? Any suggestions and approach is much appreciated, hoping someone could help as I am still noob on ember. Thank you

This is my power-select

 
   
 




mercredi 21 mars 2018

Trouble importing custom library from a repository into an Ember project as a dependency

I am developing a WebGL library that I would like to import into an EmberJS project as a dependency. Unless I'm mistaken, I believe that I can do this via the repository directly without having to make an npm package but I am having trouble getting it to work.

I have made a watered down library and ember project in a couple repos here and here respectively to demonstrate my problem.

If you clone the library and run npm run build it'll make a test bundle which can be called by the test html file packageTest.html. It should print out 'Hello World Test Member is: 5'.

In the Ember project I have a component in which I would like to import the 'HelloWorld' class from the library and call one of its member methods.

import Ember from 'ember';
//import HelloWorld from 'npm-package-test';
export default Ember.Component.extend({
  isWide: false,
  actions: {
    toggleImageSize() {
      // var h = new HelloWorld();
      // console.log(h.print());
      this.toggleProperty('isWide');
    }
  }
}); 

When I uncomment the import statement I get the console error

Error: Could not find module 'npm-package-test'

I'm still pretty new to npm packaging and how dependencies work (and know next to nothing about Ember) but from my limited understanding I feel like this method should work the way I currently have it.

For the library, I have the source files being babeled into ES5 in its lib folder. As you can see in the package.json for the library below I have the main set to the index file in the lib folder so that the Ember project can pull the babeled modules.

Library: package.json

{
  "name": "npm-package-test",
  "version": "1.0.0",
  "description": "JibJab Render Library for eCards",
  "main": "lib/index.js",
  "scripts": {
    "prepublishOnly": "npm run build",
    "build-test": "browserify test.js > demo/testbundle.js",
    "build": "babel ./src -d ./lib && npm run build-test",
    "lint": "eslint ./src",
    "test": "nyc mocha --require babel-core/register"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/nhoughto5/NPM_PackageTest.git"
  },
  "author": "JibJab",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/nhoughto5/NPM_PackageTest/issues"
  },
  "homepage": "https://github.com/nhoughto5/NPM_PackageTeste#readme",
  "devDependencies": {
    "babel-cli": "6.26.0",
    "babel-preset-env": "1.6.1",
    "eslint": "4.19.0",
    "mocha": "5.0.4",
    "nyc": "11.6.0"
  },
  "nyc": {
    "reporter": [
      "lcov",
      "text"
    ]
  },
  "dependencies": {
    "domready": "^1.0.8"
  }
}

For reference, here is the lib/index.js which should be the entry point of my library:

Library: lib/index.js 'use strict';

module.exports = {
  TestClass: require('./TestClass'),
  HelloWorld: require('./HelloWorld')
};

In the ember project I have the library repository listed as a dependency:

Ember: package.json

{
  "name": "test-ember-app",
  "version": "0.0.0",
  "description": "Small description for test-ember-app goes here",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "repository": "",
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^3.0.0",
    "ember-browserify": "1.2.1",
    "ember-cli": "2.13.1",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-babel": "^6.0.0",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-eslint": "^3.0.0",
    "ember-cli-htmlbars": "^1.1.1",
    "ember-cli-htmlbars-inline-precompile": "^0.4.0",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-mirage": "0.4.3",
    "ember-cli-qunit": "^4.0.0",
    "ember-cli-shims": "^1.1.0",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-tutorial-style": "2.0.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "^2.13.0",
    "ember-export-application-global": "^2.0.0",
    "ember-load-initializers": "^1.0.0",
    "ember-resolver": "^4.0.0",
    "ember-source": "~2.13.0",
    "ember-welcome-page": "^3.0.0",
    "loader.js": "^4.2.3"
  },
  "engines": {
    "node": ">= 4"
  },
  "private": true,
  "dependencies": {
    "npm-package-test": "git+https://github.com/nhoughto5/NPM_PackageTest.git"
  }
}

When I run npm install in the ember project I can see that the folder structure from the library appears in the node_modules folder. To my limited experience, everything seems correct but for some reason I am still getting this undefined module error.

Is there a step I've missed or some crucial detail I'm missing?




Attribute binding not working - Ember.js

The href attribute scope binding is not working in Ember.js. PFB the code.

home.hbs

<ul>
    
        " item=fruit onitemclick=(action "handleFruitsDetail")}}
    
        <li>Loading!</li>
    
</ul>

list-item is a custom component where I am passing and binding href's. PFB the code for it.

list-item.hbs

<li>
    <a href="" onclick=></a>
</li>

Thanks in advance.




Ember trigger action between child components

In my Ember app, I have a parent component 'A' which has two child components 'B' & 'C' My question is how do I trigger an action from component B to component C (i.e. communication betwen the 2 child components)

Just to add, this.sendAction from B to C is not working




EMBERJS How to access Model properties from within a template?

Recently I've been learning Ember and I've got a system setup so that I have a local .JSON file being fed into ember store. (Since I don't have a backend API yet and since I'm learning I'd rather focus on ember and just simulate the API side of things.)

Now that the data is flowing, I've noticed I'm unable to access the model properties. For example;



Was hoping someone could perhaps explain this to be a little better since I'm still learning and this seems to be giving me a lot of trouble.

models/user.js

import DS from 'ember-data';

export default DS.Model.extend({
    username: DS.attr('string'),
    avatar: DS.attr('string'),
});

components/app-nav.js


  
  
    
      
      Home
      Test
      Test 2
    
    
      
        
           
            <div class="avatar"><img src= width="32" height="32" alt=""></div>
            <div class="user"> <span class="caret"></span></div>
          
          
            Home
            Test
          
        
      
        <div class="login-button pr-3 text-center">
          <a class="btn btn-primary btn-lg" href="#" role="button">Login</a>
        </div>
         
    
  





ember injection doesnt work on ember in repo engine

i've move all the service file from ember app (parent app) to ember in repo addon. the question is how to inject (inject in inject initializer) the service from addon to my ember in repo engines app... , i try this but it doesnt work :(( , i can't get this.commonService from route (on ember in-repo-engine)

import commonService from 'commons/services/common-service';
export function initialize(application) {
  application.register('common-service:main', commonService);
  application.inject('route', 'commonService', 'common-service:main');
}
export default {
  name: 'engine-initializer',
  initialize
};




mardi 20 mars 2018

Ember non-cli application, how remove #(hash ) from url?

How to remove #(hash) from URL in ember application (non - CLI). I am using ember v2.15.




Why does Ember 3.1 have trouble dealing with Ember Data proxied objects?

I have an ES6 class in Ember 3.1 which is being handed an ember data object called certifciate. I would like to be able to call .reload() on that certificate as follows:

  @action
  showCertificateInfo(this: DomainCard, certificate) {
    this.setProperties({
      isShowingCertificateModal: true,
      selectedCert: certificate,
    })
    certificate
      .reload()
      .then(() => {
        this.set('isShowingCertificateModal', true)
      })
      .catch(e => {
        // TODO: handle this
      })
    }

However, if I do this, then Ember gives the following error/warning:

Assertion Failed: You attempted to access the 'reload' property 
(of <DS.PRomiseObject:ember796>)... However in this case4 the object 
in quetstion is a special kind of Ember object (a proxy). Therefore,
it is still necessary to use` .get(‘reload’)` in this case.

If I do as the code suggests and call .get('reload') instead, then I get an internal Ember error that this is not defined when calling this._internalModel. I get the same error when doing:

const reload = certificate.get('reload').bind(certificate)
reload().then()
...

What do I need to do to be able to reload this ember data object properly?




ember handlebars: find where component/helper/variable is defined

Given some handlebars code like this:



How could I find out where ui.select is defined?

(I happen to be on Ember 2.13)




How to specify sections in main template of Ember application

Is there a possibility to specify named sections in Ember application main template (application.hbs) and then to override them in route templates?




Metadata as parameter in route

I have my playload serialized:

count:949
next:null
previous:null
results: Array(949)
[0 … 99]
[100 … 199]
[200 … 299]
[300 … 399]
[400 … 499]
[500 … 599]
[600 … 699]
[700 … 799]
[800 … 899]
[900 … 948]
length: 949

The url parameters is limit and offset. As default it's display 20 records each, like http://localhost/data?limit=20. My router is this.store.query('model', {limit:949}); to return all data that i need, but if new records are added i have to change the limit value and this is not good.

Is there a way to pass the "meta: count" as query parameter in
this.store.query('model', {limit: meta:count}); to return all data? Or




How can I disabled a global ember error handler?

Someone (not me) has implemented a global ember error handler as a mixin that is used on all controllers:

export default Ember.Mixin.create({
    handleErrors: function (error) {
        alert(error);
    }
});

import ErrorHandler from '../mixins/error-handler';

export default BaseController.extend(ErrorHandler , {
  ....
});

I'm making an ajax call and under certain circumstances I want it to fail (record is locked in the backend and user shouldn't be able to continue).

I'm return a HTTP error code to my ajax call:

return Ember.$.ajax({
        url:url,
        method:'GET',
        cache:false,
        xhrFields: {
            withCredentials: true
         }
    })
    .fail(( jqXHR) => {
        if (jqXHR.status === 409){
            alert('This record is locked and you cannot create a New Revision until the lock is released by the person currently editing it.');
        }

    })
    .then((response) => {
        this.get('store').pushPayload(response);
        return response;
    });

I want to handle this state here and only here, I want to prevent the error bubbling up to the handleErrors call. I can't figure out how to prevent handleErrors from getting called though.

How can I get this to resolve to an unerror state?

Due to complicated (and overly complicated design not done by myself...) reasons I can't remove the mixin and most of the time this is doing an ok job.




Addon asset url's wrong when server ember app at different rootUrl

I created a custom addon.

A couple of images in vendor/assets/img folder, which I import in my index.js's included method app.import('vendor/assets/img/loading.gif'); And then use it in my addon as img src, such as img src="/assets/img/loading.gif" id="searchSpinner" style="display:none" />

This works fine when I test it in my dummy app. It also works fine when I use it in an ember app after linking the addon.

However, what I'm doing is have an asp.net mvc app serve up my ember app (result of a prod build) I had some issues there with css/img/js links but sorted it out with the app itself (basically just setting ENV.rootUrl in environment.js) However the image links in my add on (addon in emberapp in mvc app) is wrong.

Is there another step to ensure the urls of your addon assets is correct, no matter where it's being used?

For instance now, in my ember app the link to it's own js is correct: <script src="/mymvcapp/testember/assets/site-app-bbaea1133474bb804e19476f27eeda30.js"></script> However the link to an image futher down in my addon used in the ember app is wrong: <img src="assets/img/loading-5fe0e55f8e19bc4cc3201876dce7b224.gif" id="searchSpinner" style="display:none">




lundi 19 mars 2018

Ember-CLI post form data

I have an ember-cli front-end application from which I want to send data to my Flask based backend. How do i do it? Can someone explain it to me with ease. I'm kid of stuck into it right now. The form contains files as well as fields.




"Unable to get property 'extend' of undefined or null reference" affecting to open the IE11

My local host (http://localhost:8080/) is working fine with Internet Explorer 11 (IE11) version. But context root (http://localhost:8080/context-root) is not working in IE11??

While opening the product through IE11 the http://localhost:8080/context-root, its not showing any page, it's simply showing blank page. In that there is showing below two errors

SCRIPT5007: Unable to get property 'extend' of undefined or null reference
File: context.js, Line: 20561, Column: 1

Context.component.SectionView.extend().named("Admin.navigators.Administration.Roles").reopen({classNameBindings:["working"],working:function(){var loadState=this.get("model.loadState")
if(!loadState){return true}if(loadState!=="loaded"&&loadState!=="error"){return true}return false}.property("model.loadState"),model:function(){return Context.model.SimpleResultSet.create({fetch:function(){return Admin.rolesService.request().send()},sortBy:"name",insensitive:true})}.property(),pagination:function(){return Ember.Object.extend(Ember.ActionHandler,{view:this,contentPageStart:0,contentPageLengthBinding:"Context.model.resultsConfig.resultsPerPage",resultSetBinding:"view.model",_actions:{setPage:function(page){this.set("contentPageStart",page.start)}}}).create()}.property(),headerViews:[Context.component.PrimaryTile.extend({direction:"row",classNames:["view-selector"],controllerBinding:"parentView.pagination",contains:[Ember.View.extend({classNames:["spacer"]}),Context.component.Pager,Ember.View.extend({classNames:["spacer"]})]})],attachPublishAction:function(){this.set("controller.publishAction",{view:this,method:"reload"})}.on("didInsertElement"),detachPublishAction:function(){if(this.get("controller.publishAction.view")===this){this.set("controller.publishAction",null)}}.on("willDestroyElement"),reload:function(){return this.get("model").reload()},loadModel:function(){return this.get("model").reload()}.on("init"),scrollable:"scrollable-tile always-y",bodyView:Context.component.ObjectTable.extend().named("Admin.RolesView").reopen({controllerBinding:"parentView.pagination",modelBinding:"controller.resultSet",displayStartBinding:"controller.contentPageStart",displayLengthBinding:"controller.contentPageLength",hasHeader:true,paginated:true,leadingColumns:[{type:"itemNumber",inspect:false,reload:true}],trailingColumns:[],columns:[{name:"name",label:"Role"},{name:"description",label:"Description"}],getColumnView:function(column){if(column.type==="itemNumber"){return Context.view.Activity.ItemNumberView}if(column.name==="name"){return this.constructor.RoleNameColumn}return Context.view.Activity.GenericDataView},getHeaderView:function(column){if(column.type==="itemNumber"){return Context.component.ObjectTable.ItemNumberHeader.extend({click:function(){this.get("controller").send("publish")}})}return Context.view.Activity.GenericHeaderView},clickRow:function(event,role){console.warn("Role inspect: Not implemented")
return false}}).reopenClass({RoleNameColumn:Ember.ContainerView.extend({tagName:"td",childViews:[Admin.AutoActionsMenuButton.extend({menuContext:function(){return{roleObject:this.get("parentView.rowView.object")}}.property("parentView.rowView.object"),actionsBase:"Context:admin:role"}),Ember.View.extend({tagName:"span",template:Ember.Handlebars.compile("")})]})})}).reopenClass({linkable:true,getGlobalActionMenuModel:function(){var model=Context.model.Menu.extend({content:[Context.model.Menu.Item.create({label:"Create Role",icon:["duplicate","add_overlay"],invoke:function(){return new Promise(function(resolve,reject){var dlg=Admin.CreateRoleDialog.create({menuContext:Context.Action.Context.create()}).dialogShow().done(function(state){var data=Context.pivot(state.data)
var name=data.name[0]
data=Context.pivot(data)
Context.services({service:"admin/roles",type:"post",json:true,data:state.data}).done(function(result){resolve(result)
Context.notify({title:"Role created",message:'Role "'+result.name+" created"})
dlg.dialogClose()}.bind(this)).fail(function(xhr,status,reason){reject(reason||status)}).always(function(){Admin.getController().send("publish")}).fail(function(xhr,status,reason){Context.Error.show(reason||status)
dlg.dialogClose()})}).fail(function(){resolve()
dlg.dialogClose()})})}})]}).create()
model.set("loadState","loaded")
return model}})

Please help me on this. Thanks in advance. Its working fine with chrome and Mozilla.




dimanche 18 mars 2018

Ember js - saving models with relationship

My server is returning a json data and I have no problem loading the models (page.js, event.js, choice.js) with Ember Data. But when the form is submitted, the JSON data submitted to the server doesn't contain the related models (event.js, choice.js).

Below are my files and the json data.

Json data returned by backend api:

{
   "data":    {
      "type": "pages",
      "id": "12345",
      "attributes":       {
         "guest_id": null,
         "name": null,
         "email": null,
         "address": null
      },
      "relationships": {"events": {"data":       [
                  {
            "type": "events",
            "id": "67891"
         },
                  {
            "type": "events",
            "id": "90908"
         }
      ]}}
   },
   "included":    [
            {
         "type": "events",
         "id": "67891",
         "attributes":          {
            "event_id": "67891",
            "name": "Event 1"
         },
         "relationships": {"choices": {"data":          [
                        {
               "type": "choices",
               "id": "67891-11111"
            },
                        {
               "type": "choices",
               "id": "67891-22222"
            }
         ]}}
      },
            {
         "type": "events",
         "id": "90908",
         "attributes":          {
            "event_id": "90908",
            "name": "Event 2"
         },
         "relationships": {"choices": {"data":          [
                        {
               "type": "choices",
               "id": "90908-11111"
            },
                        {
               "type": "choices",
               "id": "90908-22222"
            }
         ]}}
      },
            {
         "type": "choices",
         "id": "67891-11111",
         "attributes":          {
            "choice_id": "67891-11111",
            "name": "Diet choice",
            "value": "0"
         },
         "relationships": null
      },
            {
         "type": "choices",
         "id": "",
         "attributes":          {
            "choice_id": "67891-22222",
            "name": "No. of adult guest",
            "value": "0"
         },
         "relationships": null
      }
            {
         "type": "choices",
         "id": "90908-11111",
         "attributes":          {
            "choice_id": "90908-11111",
            "name": "Diet choice",
            "value": "0"
         },
         "relationships": null
      },
            {
         "type": "choices",
         "id": "90908-22222",
         "attributes":          {
            "choice_id": "90908-22222",
            "name": "No. of adult guest",
            "value": "0"
         },
         "relationships": null
      }
   ]
}

JSON data submitted to the server

    {
        "data": {
            "id":"e47e8358-0f18-4607-b958-2877155bf5be",
            "attributes":{
                "guest_id":null,
                "name":"my name",
                "email":"myemail@gmail.com",
                "address":"myaddress"
            },
            "relationships":{
                "events":{
                    "data":[
                        {
                            "type":"events",
                            "id":"67891"
                        },
                        {
                            "type":"events",
                            "id":"90908"
                        }
                    ]
                }
            },
            "type":"pages"
        } 
}

/pages/show.hbs

<p>
    <label>Name: </label>
    
</p>


    <h3>
        
        <!-- Rounded switch -->
        <label class="switch">
          <input type="checkbox" class="switch_input" id="">
          <span class="slider round"></span>
        </label>
    </h3>

    
        
            <p>
                <label for="diet_choice">:</label>
                <select id="diet_choice" value=choice.value>
                    <option value="anything">Anything and Everything</option>
                    <option value="vegetarian">Vegetarian</option>
                    <option value="hala">Hala</option>
                </select>
            </p>
        
        
            <p>
                Adult guest
                <div>
                    <button type="button" name="btnMinusGuest" >-</button>
                    
                    <button type="button" name="btnPlusGuest" >+</button>
                </div>
            </p>
        
    


<p>
    <label for="email">Email:</label>
    
</p>
<p>
    <label for="address">Address:</label>
    
</p>
<p>
    <input type="submit" name="btnSubmit" value="Submit"  />
    <input type="submit" name="btnCancel" value="Cancel"  />
</p>


/routes/pages/show.js

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

export default Route.extend({
    queryParams: {
        event: ''
    },
    model(params) {
        return this.get('store').findRecord('page', params.page_id, { adapterOptions: {query: {'event': params.event}}});
    },
    actions: {
        submit() {
            // Create rec
            page.save().then(function() {
                console.log('submitted');
            }).catch(function(reason) {
                console.log(reason);
            });
        },
        cancel() {
            alert("Are you sure?");
        },
        addCounter(item, max_val, msg) {
            let current_val = parseInt(item.get('value'));
            if (current_val >= max_val) {
                alert(msg)
            } else {
                item.set('value', current_val + 1);
            }
        },
        minusCounter(item, min_val, msg) {
            let current_val = parseInt(item.get('value'));
            if (current_val <= min_val) {
                alert(msg);
            } else {
                item.set('value', current_val - 1)
            }
        },
    }
});

/models/page.js

import DS from 'ember-data';

export default DS.Model.extend({
    guest_id: DS.attr(),
    name: DS.attr(),
    email: DS.attr(),
    address: DS.attr(),
    is_e_invite: DS.attr(),
    data_time_submitted: DS.attr(),
    events: DS.hasMany('event')
});

/models/event.js

import DS from 'ember-data';

export default DS.Model.extend({
    event_id: DS.attr(),
    name: DS.attr(),
    choices: DS.hasMany('choice')
});

/models/choice.js

import DS from 'ember-data';

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




Create fake routes to test component's link-to

I have a component that gets menu items and renders navbar. So now I'm writing integration test, and I want to make sure, that component renders right links and labels. First of all, I added router initialization to make link-to display href prop:

moduleForComponent('main-menu', 'Integration | Component | main menu', 
{
  integration: true,
  setup() {
    const router = getOwner(this).lookup('router:main');
    router.setupRouter();
  }
});

Now I want to create some fake routes to test component, and to be independent from application router's setup. So I try to use map function:

moduleForComponent('main-menu', 'Integration | Component | main menu', {
  integration: true,
  beforeEach() {
    const router = getOwner(this).lookup('router:main');
    router.map(function() {
      this.route('link1');
      this.route('link2');
    });
    router.setupRouter();
  }
});

And I get Promise rejected before "it renders": router.map is not a function. Has anyone had experience in this?




Send additional data in model.save to sails js model

I'm working with ember js and sails js, now i have a little issue

i have a save function that stores data using model.save() and i want to

send some data along with the model.save() method to the sails js model

and receive it there in the afterCreate method

my ember js controller

save(model, invoice) {
    model.save().then(() => {
    this.get('modalManager').remove(this.get('modal'))
})

my sails js model

afterCreate : function(data, cb) {
    /* I Want to get the invoice object from the Ember controller 
    and do something like */
    Invoice.create({ visit : data.id, paid : 'Amount Set in the invoice Object })
}

How can i send the invoice object to the model ? i tried passing it in the save parameters like model.save(invoice) and logged 3 parameters in the afterCreate method like function(data, invoice, cb) but i got the model itself, the callback and undefined

Help me in this please.




samedi 17 mars 2018

Error: Assertion Failed: You must include an 'id' for member in an object passed to 'push'

I've looked this up on Stackoverflow and still haven't been able to figure out how to get rid of this error. Basically I'm trying to use the Wordpress API and connect it to my Ember App by following this tutorial https://www.codesandnotes.com/ember-js/ember-wordpress/

I'm getting this error:

Error Screenshot

I can't figure out why it is showing up or how to get rid of it. I can't think of anywhere/one else to ask so any help would be really appreciated. Here's my code:

app/router.JS

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

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

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

export default Router;

app/routes/member.js

import Ember from 'ember';

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

app/models/member.js

import DS from 'ember-data';
import PostModel from 'ember-wordpress/models/post';

export default PostModel.extend({

});

app/config/environment.js

/* eslint-env node */
'use strict';

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

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },
    wordpressHost: 'http://wordpress.daughtersofeve.org/'
  };

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

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

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

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

  if (environment === 'production') {

  }

  return ENV;
};

app/package.json

{
  "name": "doe-site",
  "version": "0.0.0",
  "private": true,
  "description": "Small description for doe-site goes here",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "repository": "",
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.5",
    "ember-ajax": "^3.0.0",
    "ember-cli": "~2.15.1",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-babel": "^6.3.0",
    "ember-cli-dependency-checker": "^2.0.0",
    "ember-cli-eslint": "^4.0.0",
    "ember-cli-htmlbars": "^2.0.1",
    "ember-cli-htmlbars-inline-precompile": "^1.0.0",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-qunit": "^4.0.0",
    "ember-cli-shims": "^1.1.0",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "~2.15.0",
    "ember-export-application-global": "^2.0.0",
    "ember-load-initializers": "^1.0.0",
    "ember-resolver": "^4.0.0",
    "ember-source": "~2.15.0",
    "ember-welcome-page": "^3.0.0",
    "ember-wordpress": "^0.1.7",
    "loader.js": "^4.2.3"
  },
  "engines": {
    "node": "^4.5 || 6.* || >= 7.*"
  }
}



ember-cli-mirage and babel error

I am following this tutorial: https://guides.emberjs.com/v2.8.0/tutorial/installing-addons/

and when i get to adding ember-cli-mirage it comes up with a build error and wont load the app:

Richards-MacBook-Air:super-rentals rpt$ ember s
WARNING: Node v8.9.1 has currently not been tested against Ember CLI and may result in unexpected behaviour.

Just getting started with Ember? Please visit http://localhost:4200/ember-getting-started to get going

Livereload server on http://localhost:49154
Serving on http://localhost:4200/
{ Error: read ECONNRESET
    at _errnoException (util.js:1024:11)
    at TLSWrap.onread (net.js:615:25)
 code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
File: ember-cli-mirage/utils/inflector.js
The Broccoli Plugin: [broccoli-persistent-filter:Babel] failed with:
SyntaxError: ember-cli-mirage/utils/inflector.js: Unexpected token (4:14)
export { singularize, pluralize } from 'ember-inflector';

export { Ember.String.capitalize as capitalize, Ember.String.camelize as camelize, Ember.String.dasherize as dasherize, Ember.String.underscore as underscore };
    at Parser.pp.raise (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/location.js:24:13)
    at Parser.pp.unexpected (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/util.js:82:8)
    at Parser.pp.expect (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/util.js:76:33)
    at Parser.pp.parseExportSpecifiers (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:772:12)
    at Parser.pp.parseExport (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:701:28)
    at Parser.parseExport (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/plugins/flow.js:713:20)
    at Parser.pp.parseStatement (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:115:90)
    at Parser.parseStatement (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/plugins/flow.js:655:22)
    at Parser.pp.parseTopLevel (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:30:21)
    at Parser.parse (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/index.js:70:17)
    at Object.parse (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/index.js:45:50)
    at Object.exports.default (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/lib/helpers/parse.js:36:18)
    at File.parse (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/lib/transformation/file/index.js:574:40)
    at File.parseCode (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/lib/transformation/file/index.js:691:20)
    at /Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/lib/transformation/pipeline.js:167:12
    at File.wrap (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/lib/transformation/file/index.js:639:16)
    at Pipeline.transform (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/babel-core/lib/transformation/pipeline.js:165:17)
    at /Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/lib/parallel-api.js:123:26
    at initializePromise (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:567:5)
    at new Promise (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1039:33)
    at Object.transformString (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/lib/parallel-api.js:117:12)
    at Babel.transform (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/index.js:110:22)
    at Babel.processString (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/index.js:216:15)
    at Promise.then.result.output (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/broccoli-persistent-filter/lib/strategies/persistent.js:41:23)
    at initializePromise (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:567:5)
    at new Promise (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:1039:33)
    at /Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/broccoli-persistent-filter/lib/strategies/persistent.js:40:18
    at tryCatch (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:525:12)
    at invokeCallback (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:538:13)
    at publish (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:508:7)
    at flush (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:2415:5)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)


The broccoli plugin was instantiated at: 
    at Babel.Plugin (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/broccoli-persistent-filter/node_modules/broccoli-plugin/index.js:7:31)
    at Babel.Filter [as constructor] (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/node_modules/broccoli-persistent-filter/index.js:64:10)
    at new Babel (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/broccoli-babel-transpiler/index.js:37:10)
    at EmberApp._addonTree (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/broccoli/ember-app.js:910:29)
    at EmberApp._processedVendorTree (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/broccoli/ember-app.js:944:20)
    at EmberApp._processedExternalTree (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/broccoli/ember-app.js:975:21)
    at EmberApp.appAndDependencies (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/broccoli/ember-app.js:1071:30)
    at EmberApp.javascript (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/broccoli/ember-app.js:1201:34)
    at EmberApp.toArray (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/broccoli/ember-app.js:1606:10)
    at EmberApp.toTree (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/broccoli/ember-app.js:1628:30)
    at module.exports (/Users/rpt/projects/super-rentals/ember-cli-build.js:23:14)
    at Class.setupBroccoliBuilder (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/models/builder.js:74:19)
    at Class.init (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/models/builder.js:54:10)
    at Class.superWrapper [as init] (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/core-object/lib/assign-properties.js:32:18)
    at new Class (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/core-object/core-object.js:32:33)
    at Class.run (/Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/tasks/serve.js:15:19)
    at /Users/rpt/projects/super-rentals/node_modules/ember-cli/lib/commands/serve.js:76:24
    at tryCatch (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:525:12)
    at invokeCallback (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:538:13)
    at /Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:606:14
    at flush (/Users/rpt/projects/super-rentals/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:2415:5)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Can anyone point me in the right direction as to whats going wrong?

Im using ember 2.8.0 and using the latest version of ember-cli-mirage.

Please bare in mind I am really new to ember.




vendredi 16 mars 2018

Include Property In Object Relationship in Ember

How can I return all the fields regarding to a relation in Ember ? I'm using JSONAPI but only ID and type are on the relation.

enter image description here




Context Root is not working in Internet Explorer 11 version

My local host (http://localhost:8080/) is working fine with Internet Explorer 11 (IE11) version. But context root (http://localhost:8080/context-root) is not working??

While opening the product through IE11 the http://localhost:8080/context-root, its not showing any page, it's simply showing blank page. In that there is showing below two errors

SCRIPT1003: Expected ':'

File: context.js, Line: 1980, Column: 50

{
                        iframe = $('<iframe src="' + jsFalse + '" name="' + name + '" style="display:none"></iframe>');
                        iframe.addClass('iframe-transport');
                        form.attr('accept-charset', 'utf-8');
                        $("body").append(iframe);
                        iframe.append(form);
                        iframe.bind("load", {form,collider} ,winLoader);
                    }

The iframe.bind was mentioned in the error and another error is

SCRIPT5009: '$' is undefined

File: default.js, Line: 1, Column: 1

$(function () {
    context.start(context.view.Application);
});

But the same localhost cite is working fine with chrome and Mozilla. Can anyone help me on this. I'm new with the ember. Thanks in advance




Ember jQuery detach issue

In my Ember app, I am trying to do some DOM updates (detatching some element & append it somewhere else)

var comp = Ember.$(this.element).detach();
Ember.$("#some-sec").append(comp);

However for some reasons, the earlier event handling goes for a toss after doing this. Am I doing something wrong ? Is this to be done in a different way for an Ember app ?




jeudi 15 mars 2018

What is the proper way to write a computed property using TypeScript and Ember?

I have a relatively small Ember/TypeScript app that I have been working on for about six months. I used to define computed properties as follows:

   @computed('styleNamespace', 'status')
   statusClass(componentClassName: string, status: string): string {
     return `${componentClassName}--${status}`
   }

But I have never been able to get this to pass TypeScript checking properly. After reviewing Chris Krycho's Emberconf training materials, it seems that the "proper" way to do this is as follows:

   @computed('styleNamespace', 'status')
   get statusClass(this: CertificateCard): string {
     return `${this.get('styleNamespace')}--${this.get('status')}`
   }

Is this correct? I seem to be missing something, though because I am still getting errors like this:

Error: Assertion Failed: Attempted to apply @computed to statusClass,
but it is not a native accessor function. 
Try converting it to `get statusClass()`




Handling Mixins with Ember CLI Typescript

Just wondering how / what is the best way to properly handle mixins with a typed ember application. Obviously eliminating mixins from the application would be best; however, most addons do not support typescript yet. With that said, what would be the best way to utilize ember-simple-auth application route mixin (or any of their mixins for that matter). I have not tested the following code but my guess is that something along these lines should work; however, it just feels a bit odd:

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

export default class ApplicationRoute extends Route.extend(ApplicationRouteMixin, {
  // Prototype Code Here?
}) {
  // Class TS Code Here?
}

Once again, I have not tested this and am just beginning to embark on the TS journey so bear with me. Any help and clarification would be appreciated.




How to set semantic-ui-ember dropdown value?

I have a model, called assessmentTestModel, that is a list of assessmentTests. Each assessmentTest contains a unique identifier id, and form that is a reference to another object called form. Form also has a unique identifier, id.

For every assessmentTest in assessmentTestModel, I want to render a drop-down on the screen that's menu-items are all of the forms (I've already accomplished this). I also want them to have the selected default value of assessmentTest.form (This is the issue). Currently, when each drop-down is rendered, it displays the default text 'Select an Assessment Test'.

Here's an example of assessmentTestModel:

{ assessmentTestModel: [
      {
          id: '1029',
          form: '85'
      },
      {
          id: '1030',
          form: '87'
      },
      {
          id: '1031',
          form: '85'
      }
 ]
}

Here is my current .hbs file. I've tried setting the value attribute of the ui-dropdown to the id of the form, and the form object itself. Neither have worked.

<div class="field">
    <label>Assessment Tests</label>
    <ol>
        
            <li>
                
                    <div class="default text">Select an Assessment Test</div>
                    <i class="dropdown icon"></i>
                    <div class="menu">
                        <div data-value="" class="item">All Items</div>
                        
                            <div data-value="" class="item">
                                
                            </div>
                        
                    </div>
                
            </li>
        
    </ol>
</div>




Ember Way to Add Rss Feed without third party widget, Front-end only

I am using Ember 3.0 at the moment. Wrote my first lines of code in ANY language about 1 year ago (I switched careers from something totally unrelated to development), but I quickly took to ember. So, not a ton of experience, but not none. I am writing a multi-tenant site which will include about 20 different sites, all with one Ember frontend and a RubyOnRails backend. I am about 75% done with the front end, now just loading content into it. I haven’t started on the backend yet, one, because I don’t have MUCH experience with backend stuff, and two, because I haven’t needed it yet. My sites will be informational to begin with and I’ll build it up from there.

So. I am trying to implement a news feed on my site. I need it to pull in multiple rss feeds, perhaps dozens, filtered by keyword, and display them on my site. I’ve been scouring the web for days just trying to figure out where to get started. I was thinking of writing a service that parses the incoming xml, I tried using a third party widget (which I DON’T really want to do. Everything on my site so far has been built from scratch and I’d like to keep it that way), but in using these third party systems I get some random cross domain errors and node-child errors which only SOMETIMES pop up. Anyway, I’d like to write this myself, if possible, since I’m trying to learn (and my brain is wired to do the code myself - the only way it sticks with me).

Ultimately, every google result I read says RSS feeds are easy to implement. I don’t know where I’m going wrong, but I’m simply looking for:

1: An “Ember-way” starting point. 2: Is this possible without a backend? 3: Do I have to use a third party widget/aggregator? 4: Whatever else you think might help on the subject.

Any help would be appreciated. Here in New Hampshire, there are basically no resources, no meetings, nothing. Thanks for any help.




EmberJs - how to iterate included json data

the backend api is returning a sideloaded data like the following:

{
   "data":    {
      "type": "rsvps",
      "id": "e47e8358-0f18-4607-b958-2877155bf5be",
      "attributes":       {
         "user_id": "e47e8358-0f18-4607-b958-2877155bf5be",
         "name": "Foo bar"
      },
      "relationships": null
   },
   "included":    [ // I want to print this array of data
            {
         "type": "events",
         "id": "78e399ac-645a-4e51-90f4-278b2cd27b2c",
         "attributes":          {
            "event_id": "78e399ac-645a-4e51-90f4-278b2cd27b2c",
            "name": "event 1"
         }
      },
            {
         "type": "events",
         "id": "ec93f9c4-757d-4ff8-8fdc-31bc3cca07b5",
         "attributes":          {
            "event_id": "ec93f9c4-757d-4ff8-8fdc-31bc3cca07b5",
            "name": "event 2"
         }
      }
   ]
}

In the .hbs file, how can i print out the included data?




mercredi 14 mars 2018

Assertion Failed: The key provided to set must be a string

I have a that passes an ID to the details.js route. This route findRecord my model passing the ID. The payload loads all the data, but when the page finishes loading it comes the error. I didn't find the "key" and i don't have a pokemon.detalhes controller.

Error: Assertion Failed: The key provided to set must be a string, you passed (generated pokemon.detalhes controller).

My Code: adapter.js

import DS from 'ember-data';
import { computed } from '@ember/object';

export default DS.RESTAdapter.extend({

    host: 'http://127.0.0.1:8000',
    namespace: 'api/v2',
    headers: computed(function () {
        return {
            'accept': 'application/json'
        };
    }),

    pathForType(type) {
        return type;
    },
/*
    query(store, b, query) {
        store.serializerFor('pokemon').set('pageSize', query.limit);
        const url = `${this.get('host')}/${this.get('namespace')}/pokemon`;
        console.log(url);
        return this.ajax(url, 'GET', {data: query});
    },
*/
    updateRecord(store, type, snapshot) {
        const data = snapshot.record.serialize();
        const headers = Object.assign({}, this.get('headers'), { "pokemon-edit": true });
        const url = this.buildURL(type.modelName, snapshot.id, snapshot, 'updateRecord');
        return this.ajax(url, 'PUT', { headers, data });
    }
});

serializer.js

import DS from 'ember-data';
import _ from 'lodash';

export default DS.RESTSerializer.extend({

normalizeResponse(store, primaryModelClass, payload) {
  debugger  
  return  {
        meta: {
          count: payload.count,
          previous: payload.previous,
          next: payload.next 
        },

        data: 
            payload.results && _.map(payload.results, item => {
              return {
                id: (/.+\/([0-9]+)\//.exec(item.url) || [])[1] || 0,
                type: 'pokemon',
                attributes: item
              }
            }) || {
                    type: 'pokemon',
                    id: payload.id,
                    attributes: Object.assign(payload) 
                  }
    };
  },
});

route/index.js

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

export default Route.extend({
    model(){
        return this.store.query('pokemon', {limit: 2});
    }
});

index.hbs

<table class="table table-striped">
    <thead class="thead-dark">
        <tr>
        <th scope="col">Id</th>
        <th scope="col">Pokemon</th>
        <th scope="col">Ações</th>
        </tr>
    </thead>
    <tbody>
        
            <tr>
                <th scope="row"></th>
                <td></td>
                <td><p class="btn btn-success">Detalhes</p></td>
            </tr>
        

    </tbody>
</table>

payload data from index route

{…}
count: 949
next: "http://127.0.0.1:8000/api/v2/pokemon/?limit=2&offset=2"
previous: null
results: […]
0: {…}
  name: "bulbasaur"
  url: "http://127.0.0.1:8000/api/v2/pokemon/1/"
1: {…}
  name: "ivysaur"
  url: "http://127.0.0.1:8000/api/v2/pokemon/2/"
length: 2

route/pokemon/details.js

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

export default Route.extend({
    model(params) {
        return { params };
    },

    setupController(controller, model) {
        this.store.findRecord('pokemon', model.params.id).then(response => {
            this.set(controller, 'model', response);
            return response;
        })
    }
});

pokemon/detail.hbs

<div class="card" style="width: 20rem;">
    <img class="card-img-top" src= alt="Card image cap">
        <div class="card-body">
        <form>
            <div class="form-group">
                <span class="alert-primary">Pokemon:</span>
                <span class="form-control"></span>
            </div>
            <div class="form-group">
                <span class="alert-primary">XP Base:</span>
                <span class="form-control"></span>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>  
        </div>
</div>

model/pokemon.js

import DS from 'ember-data';
import { computed, get } from '@ember/object';

export default DS.Model.extend({

    name: DS.attr('string'),
    url: DS.attr(),
    height: DS.attr('number'),
    weight: DS.attr('number'),
    base_experience: DS.attr('number'),
    sprites: DS.attr(),

    image: computed('sprites', function(){
        const img = get('sprites');
        return img.get('sprites.front_default');
    })
});

payload data from details route with id=1

{…}
abilities: Array [ {…}, {…} ]
base_experience: 64
forms: Array [ {…} ]
game_indices: Array [ {…}, {…}, {…}, … ]
height: 7
held_items: Array []
id: 1
is_default: true
location_area_encounters: "/api/v2/pokemon/1/encounters"
moves: Array [ {…}, {…}, {…}, … ]
name: "bulbasaur"
order: 1
species: Object { url: "http://127.0.0.1:8000/api/v2/pokemon-species/1/", name: "bulbasaur" }
sprites: Object { back_default: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/1.png", back_shiny: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/1.png", front_default: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png", … }
stats: Array [ {…}, {…}, {…}, … ]
types: Array [ {…}, {…} ]
weight: 69




mardi 13 mars 2018

How to elegantly query for a record and create it if it does not exist yet?

The Goal

The goal of startChat(partner_profile) is to get the id of a chat between two users to then be able to redirect to this chat. There are two different cases:

  1. a chat between them already exists

    a) partner_profile is first participant

    b) partner_profile is second participant

  2. the chat between them needs to be created first

What I got so far

I know how to get an ID for each of the above listed cases, but I do not know how to combine them all. Here is my code so far:

 startChat(partner_profile) {
      // case 1a
      this.get('store').queryRecord('chat', {
              first_participant: partner_profile.id
       }).then(function(chat) {
              let id = chat.get('id');
              onSaveSuccess(id);
       }).catch(function(){
      });

      // case 1b
     this.get('store').queryRecord('chat', {
             second_participant: partner_profile.id
     }).then(function(chat) {
            let id = chat.get('id');
            onSaveSuccess(id);
            return;
     }).catch(function(){
         // **error handling* 
    });

    // case 2
    let chat = this.get('store').createRecord('chat', {
        second_participant: partner_profile
    });

    let onSaveSuccess = (id) => this.transitionToRoute('chats.chat',id);

    chat.save()
        .then(function(success) {
            let id = success.get('id');
            onSaveSuccess(id);
         })
        .catch((error) => {
           // **error handling*
      }
    });

How can I combine those cases?

Right now it's really ugly, because every case is executed and of course two of them fail. How could I do this in a nicer way? Is there a way to get_or_create a record at once (like there is in Django)? Thank you for your help :-)




How to Edit a todo task on same component in Ember

I want to edit a todo task on same list style tag without affecting the other todo present.

Below is the an image of the todo add todo

The second image below is when the edit button is clicked. Delete todo

What I want to achieve is when the edit button is clicked on a particular todo, I want an input field with the data to appear in the text field and the todo itself to disappear. I want it to happen to one particular todo and not affect all of them.

The code below is what I have tried.

This code tell if it is in edit mode it should display the text input field esle display the todo

todo.hbs

<ul class="list-group">
        
          <li class="list-group-item ">
            
              <div class="text-input">
                
                <span class="text-info right edit" ><i class="far fa-edit"></i></span>
              </div>
            
              <span class="round">
                
                <label for="checkbox"></label>
              </span>
              <span>
                 - <span class="date "></span>
              </span>
              <span class="text-danger right delete" ><i class="far fa-trash-alt"></i></span>
              <span class="text-info right edit" ><i class="far fa-edit"></i></span>
            
          </li>
        
      </ul>

todo.js

export default Controller.extend({
  isEdit: false,
  actions: {
   editTodo: function(todo) {
     this.toggleProperty('isEdit');
   },
   cancelEdit: function () {
     this.toggleProperty('isEdit');
   }
 },
})

how can I do what i want to do without affecting other todos?




Ember how to use multiple adapters?

I have an ember app that hooks into a rails-api. I am using devise for authentication and have an application.js adapter set up for the authorization. Now I want to connect to my rails DB model and display some data. I need to add the ActiveModelAdapter to connect. How do I add in a second ActiveModelAdapter so I can use it? I'm just getting started with Ember so I wasn't sure.

    import DS from 'ember-data';
    import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
    import ActiveModelAdapter from 'active-model-adapter';

    export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
      authorizer: 'authorizer:devise'
    });




Ember model hook with a Promise.All and several findAll()

I thought I understood how the store.findAll and the Promise.All works. But I have run into some strange behavior. I have two findAll(), but only one of them is fullfilled after the Promise.All gets into the then()-part.

See this code

export default Route.extend({
model() {
    var self = this;
    return Ember.RSVP.Promise.all([
        self.store.findAll('contact'),
        self.store.findAll('message')
    ]).then(function(values) {
        var contacts = values[0];
        var messages = values[1];
        var numberOfContacts = contacts.get('length');  // This is 39 as expected.
        var numberOfMessages = messages.get('length');  // This is 0. Expected is 1. 
        ...

There must be something different with messages and contacts, but I cannot figure out what it is. They have very similar models and they have very similar backend API handling. From the network traffic I can see that a message object is returned and if I call (later in the code, after the model hook):

store.peekAll('message');

I get the message object I expect.

I use ember 3.0.0




Ember error Modified twice in a single render

In my Ember app, I have a hbs template defined as below (simply iterates through an array 'myContainers' & prints some fields);

         
                   


Also my component JS is as below (Iterates through server response 'gridItems' prop & finally returns an array );

myContainers: function(){
    var self = this;        
    let gridItems = this.get('secInfo.gridItems');        
    Ember.set(this.get('secInfo'), 'myRows', Ember.A([]));
    Ember.set(this.get('secInfo'), 'myRowsToRender', Ember.A([]));

    this.get('secInfo.myRows').pushObject(gridItems);
    var updatedContainers = [...gridItems];
    Ember.set(this.get('secInfo'), 'myRows', updatedContainers);

    self.get('secInfo.myRows').forEach(function(container) {
        // Iterate & set field values
    });
    Ember.set(this.get('secInfo'), 'myRows', this.get('secInfo').myRowsToRender);
    return this.get('secInfo').myRows;
}.property('secInfo.gridItems'),

Now my question is with the above code, everything works fine & I am able to see the data on screen.

But the moment, I try to update my hbs by wrapping in 'my-accordion' component;


    
                 
                           
        
    
   

You modified 'someAttr' twice in a single render error & I cannot see any data.

PS: It is surely not an issue with the my-accordion component as the same is tested in other places.

Please help.