dimanche 19 février 2017

Ember: setting controller properties in init()?

Having a hard time figuring out why controller properties added in init() are added as 'undefined' rather than with default values. I guess you're supposed to do define in init() to avoid "leaking state"? I think I am missing something fundamental here.

When a controller property like an empty array is specified right on the controller it's added as 'Array[0]', which then allows you to pushObject stuff into it. When added in init() they are added as 'undefined' so pushObject fails.

See demo on this twiddle and/or the code below:

import Ember from 'ember';

export default Ember.Controller.extend({

    queryParams: ['q','sort_method','search_type','filter1','filter2'],

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

        Ember.set(this, 'q', null);
        Ember.set(this, 'sort_method', 'relevance'); // <-- sets default value to 'undefined'
        Ember.set(this, 'filter1', []); // <-- sets default value to 'undefined'
    },

  filter2: [], // <-- sets default values properly but will it cause state issues?
  search_type: 'bar'

});

Basically, I'm wanting to figure out how to declare my list of query params in ONE place (like in config file), rather than 3 places (route, controller queryParams array, and to the controller itself)

I created a twiddle to illustrate what I mean.




404 error on Ember file upload

I'm trying to upload a file with Ember.js. I have tried two plugins:

ember-file-upload and ember-uploader

Normally I would post my question on the appropriate github page, but I am getting the same error with both, so I suspect it is something I am doing and not an issue with the plugins themselves.

I have a folder called "uploads" in my public folder which I'm trying to save my file to. However, when I try to upload a file using either plugin, I get this error:

POST http://localhost:4200/uploads 404 (Not Found)

This is my my template with the component:



This is the component js:

import EmberUploader from 'ember-uploader';

export default EmberUploader.FileField.extend({
  filesDidChange: function(files) {
    const uploader = EmberUploader.Uploader.create({
      url: this.get('url'),
    });

    if (!Ember.isEmpty(files)) {
      // this second argument is optional and can to be sent as extra data with the upload
      uploader.upload(files[0]);
    }
  }
});

I have also tried to direct it to my assets folder as well as a folder called "files" within assets. I have tried absolute paths as well and I still get a 404. I 100% know that those folders exist because they show up in dist. Do I need to use a different path? Is there something else I have to set up that will allow that folder to be found?




Getting 'TypeError: user is null' when trying to validate form using ember-cp-validations

I am attempting to add form validation using ember-cp-validations and am following the basic steps in their video TypeError: user is null in the console. I am very new to ember and I am sure its something very basic I am overlooking.

register-form component

import Ember from 'ember';

export default Ember.Component.extend({
  user: null,

  actions: {
    save() {

      let user = this.get('user');

      user.validate()
        .then(({ validations }) => {

          if (validations.get('isValid')) {
            user.save();
          } else {
            alert("not valid");
          }

        });
    }
  }
});

user model

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

const Validations = buildValidations({
  firstname: validator('presence', true),

  email: [
    validator('presence', true),
    validator('format', { type: 'email' })
  ],

  username: validator('presence', true),

  password: [
    validator('presence', true),
    validator('length', {
      min: 4
    })
  ]
});

export default DS.Model.extend(Validations, {
  firstname:  DS.attr('string'),
  email:      DS.attr('string'),
  username:   DS.attr('stirng'),
  password:   DS.attr('string')
});




Generating Production Build index.html With Server Side App

I want to do something very simple that I am a little surprised people are not talking about more. I would like to generate on my server my own index.html from the files that are created from building ember for production. I use ember for part of my application and so when a certain URL is hit, I would then like my ember app to take over. I have tried generating my own index.html by changing the flag storeConfigInMeta in ember-cli-build.js.

storeConfigInMeta: false

This gets rid of the ember app having its configuration stored in a meta tag but the app still does not work and gives the error,

Uncaught ReferenceError: define is not defined

I have the latest version of ember and I am building ember with the command,

ember build --env production

My server generated index.html looks identical accept for the integrity attributes set on the include js and css scripts. Is their anything I am missing about approaching ember this way? Should I not be trying to do this?




Ember test generators do not generate files

The following command from the Ember tutorial doesn't create any files:

ember g acceptance-test list-rentals

It outputs only this single line:

super-rentals % ember g acceptance-test list-rentals
installing acceptance-test
super-rentals %

The application was create with this line from the tutorial:

ember new super-rentals

The versions are:

super-rentals % ember --version
ember-cli: 2.11.1
node: 6.9.5
os: darwin x64




Redirect to an ember page when exception occurs in my filter

My application has a filter that throws a user defined exception. So, whenever that user defined exception occurs, i want my application to redirect to an ember page. Something like, if( evil ) { throw myexception("exceptioncode") }

=>> Redirect user to an ember page




Ember POST request responding with XML jersey response in JAX-RS

I have an ember application trying to make a post request to my Restful Java Web Service (JAX-RS). However, the request doesn't seem to be hitting the endpoint. Instead, the Java web service is sending the following response to ember:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://ift.tt/1d3Sj3z">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.10 11/02/2011 04:41 PM"/>
    <grammars/>
    <resources base="http://localhost:3002/">
        <resource path="users">
            <method id="postUser" name="POST">
                <response>
                    <representation mediaType="application/json"/>
                </response>
            </method>
        </resource>
    </resources>
</application>

The web service itself prints the following message to the console

Feb 19, 2017 2:48:06 PM com.sun.jersey.server.wadl.generators.WadlGeneratorJAXBGrammarGenerator attachTypes
INFO: Couldn't find JAX-B element for class javax.ws.rs.core.Response
Feb 19, 2017 2:48:06 PM com.sun.jersey.server.wadl.generators.WadlGeneratorJAXBGrammarGenerator attachTypes
INFO: Couldn't find JAX-B element for class javax.ws.rs.core.Response
Feb 19, 2017 2:48:06 PM com.sun.jersey.server.wadl.generators.WadlGeneratorJAXBGrammarGenerator attachTypes
INFO: Couldn't find JAX-B element for class javax.ws.rs.core.Response
Feb 19, 2017 2:48:06 PM com.sun.jersey.server.wadl.generators.WadlGeneratorJAXBGrammarGenerator attachTypes
INFO: Couldn't find JAX-B element for class java.lang.String
Feb 19, 2017 2:48:06 PM com.sun.jersey.server.wadl.generators.WadlGeneratorJAXBGrammarGenerator attachTypes
INFO: Couldn't find JAX-B element for class javax.ws.rs.core.Response

The endpoint on JAX-RS looks like this:

@Path("/users")
public class Users {
    @POST
    @Produces("application/json")
    public Response postUser() {
        System.out.println("here");
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("{}").header("Access-Control-Allow-Origin", "*").build();
    }
}

Jersey Version: jax-rs-jersey-1.10

The adapter in ember looks like this:

   export default DS.RESTAdapter.extend({
        host: 'http://localhost:3002',
    });

Thank you in advance!

Edit: When testing the request in postman, it all works with no issues. Could be something to do with headers in ember?