mercredi 21 juin 2017

Google Maps Autocomplete InvalidValueError: not an instance of HTMLInputElement

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

../components/auto-complete.js

import Ember from 'ember';

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

../components/auto-complete.hbs

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

My console output

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




Rails + Ember: Nested models incorrect format

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

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

which outputs:

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

and my ember app pulls this in through:

import Ember from 'ember';

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

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

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

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

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




Multiple javascript components inside Ember.js

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

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

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

I have two questions concerning how to go about this.

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

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

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

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

Thanks guys!




How do I integrate client side and server side javascript?

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

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

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

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

// app/routes.js

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

Currently my router looks a bit like this:

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

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

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

module.exports = router;

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

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




Ember: catch not working with ember-data findRecord error

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

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

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

This is the 'add' method:

// cart methods
add(item) {

    let self = this;

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

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

},

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

enter image description here

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

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




Ember addon custom build

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




Component runtime compile

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

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

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

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