Quantcast
Channel: Ember.JS - Latest topics
Viewing all 4748 articles
Browse latest View live

Reflexive relation with nested data

$
0
0

@ldalves wrote:

Guys, I’m sorry if this is a basic question, but since I’m quite new to ember, I’d like to know if there is any best practice for a case like this. For example, I have the follow endpoints that returns the payloads below:

https://api.example.com/v1/user

[
    {
        "user": "user1",
        "firstName": "Foo1",
        "lastName": "Bar1",
        "url": "https://api.example.com/v1/user/user1"
    },
    {
        "user": "user2",
        "firstName": "Foo2",
        "lastName": "Bar2",
        "url": "https://api.example.com/v1/user/user2"
    }
]

And each of the “url” endpoint returns something like this:

https://api.example.com/v1/user/user1

{
    "user": "user1",
    "firstName": "Foo1",
    "lastName": "Bar1",
    "age": 21,
    "address": "User1 Address"
    ... more info ...
}

We see that some properties in “/user” are repeated in “/user/user1”.

What would be the best practice to create the “user” model?

Should I have two models? Like for example a “users” model for the “/user” and a “user” model for “/user/user1”?

Could somehow have just one model “user” that would fit both endpoints?

Thanks in advance,

  • Leandro

Posts: 1

Participants: 1

Read full topic


Really Simple Single-File-Component Support for Ember 3.x+

$
0
0

@josiahbryan wrote:

Hey everyone! I’m designing a new hobby project, and I really wanted to work with single file components, so I took an hour or so of my Sunday afternoon and put together this script:

https://gist.github.com/josiahbryan/fb9022d79ab909a7173c5d4855facadf

This is, as it says on the tin, really simple single-file-component support. What does it do?

  • Take one file (my-component.hbs) with <template>, <script>, and <style> tags (see sample below)…
  • And write out each tag into it’s own file where Ember expects to find it:
    • The <template> gets written to app/templates/components/my-component.hbs
    • The <style> gets written to app/styles/components/my-component.scss (NB .scss not .css - feel free to edit the script if you’re not using SASS)
    • The <script> gets written to app/components/my-component.js

When you combine this scripts built-in support for watching the files for changes and re-writing those files above, combined with ember serves built-in live reloading during development, then development on your Single-File-Component is just as simple as editing your single file app/sfcs/my-component.hbs and this script will write out those three files automatically, and ember will auto-detect and auto-rebuild your app bundle when it sees those files changed.

Feedback / suggestions all welcome!

To integrate into your Ember project, save the script from the gist above somewhere. (I created a folder called myproject/utils/ and put it there.) Then, add this line at the top of ember-cli-build.js: require('./utils/debundle-sfc').watchAndRebuild();

IMPORTANT: You will HAVE to change the config.appRoot value embedded in the script, because it’s set for my app, and I’m guessing you don’t have the exact same folder path as I do. Notes about appRoot:

  • appRoot must end with a slash (/)
  • appRoot must be the root of the Ember app (e.g. where the components/ folder is, etc.)

This script assumes you put your single-file-components in a folder under app/ called sfcs. Change config below to change where they’re stored. Note this script expects your component files to have .hbs as the extension.

Obviously, you’ll have to create the sfcs folder (app/sfcs) manually since Ember doesn’t generate it.

You can run this script manually from the command line, either one-time (node script.js) or with a --watch argument to start the file watcher and rebuild (node script.js --watch) (Note: We watch the app/sfcs folder, not the individual files, so you can create new files in that folder and the script will automatically process those as well.) Note, we don’t REMOVE the generated files if you remove the component from app/sfcs - that’s an idea for future improvement, of course.

Obviously, when you add it to ember-cli-build with the .watchAndRebuild() call as shown above, you don’t have to run it manually on the command line during development (assuming you have ember serve) running in a console somwhere as you work.

Note: I use Atom as my text editor, and it’s built-in syntax highlighting for HBS “just works”.

Example single-file-component, I put the contents in app/sfcs/hello-world.hbs:

    <template>
       <h1 local-class='header'>
           Hello, <b {{action 'randomName'}}>{{if name name 'World'}}!</b>
       </h1>
    </template>

    <style>
       .header {
           /* For example ... */
           background: #ccc;
       }
    </style>

    <script>
       // Script automatically appends Component import to generated .js file, other imports are up to you to add here
       export default Component.extend({
           tagName: '',
           actions: {
               randomName() {
                   this.set('name', "Person # " + (Math.random() * 1024).toFixed(0));
               }
           },
       });
    </script>

Posts: 1

Participants: 1

Read full topic

ESA - Can I use index route as login route

$
0
0

@belgoros wrote:

When using Ember Simple Auth add-on, can I use index route to override its login route to be able to redirect to another external login page ? Meaning that, I defined application.js routes as follows:

import { inject as service } from '@ember/service';
import Route from '@ember/routing/route';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Route.extend(ApplicationRouteMixin, {
  currentUser: service('current-user'),
  authenticationRoute: 'index',
  routeAfterAuthentication: 'dashboard',

  beforeModel() {
    return this._loadCurrentUser();
  },

  sessionAuthenticated() {
    this._super(...arguments);
    this._loadCurrentUser();
  },

  _loadCurrentUser() {
    return this.get('currentUser').loadCurrentUser().catch(() => this.get('session').invalidate());
  }
});

And the index.js route like this:

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import config from '../config/environment';
import isFastBoot from 'ember-simple-auth/utils/is-fastboot';

export default Route.extend({
  session: service('session'),
   _isFastBoot: isFastBoot(),

  beforeModel: function() {
    if (this.get('session.isAuthenticated')) {
      this.transitionTo('dashboard');
    } else {
      if (!this.get('_isFastBoot')) {
        let oauthUrl = config.oauthUrl;
        let clientId = config.clientID;
        let redirectURI = `${window.location.origin}/callback`;
        let responseType = `token`;
        let scope = `profile%20openid`;
        window.location.replace(oauthUrl
                              + `?client_id=${clientId}`
                              + `&redirect_uri=${redirectURI}`
                              + `&response_type=${responseType}`
                              + `&scope=${scope}`
        );
      }
    }
  }
});

But it does not work.

Posts: 1

Participants: 1

Read full topic

Host App to Engine's Route Transition with QueryParam of type object is not working properly

$
0
0

@kishoreyuvan wrote:

In my host app repository, I have an in Repo lazy loading engine.

When I proceed transition from my host app to engine’s route with Query param of type object for the very first time, It shows the error like

SyntaxError: Unexpected token o in JSON at position 1

And if i do the same again, its working fine.

Actually, I found that router._queryParamsFor(handlerInfos) method in “router.js” returns the empty objects(“map” and “qps”) for the first time, the host app tries to transition to engine’s route.

For the next time, it returns the value for the objects(“map” and “qps”), this is happening because the engine’s instance is already created by the previous transition.

Also, if _queryParamsFor method returns an empty object. Since there is no type check for an object in _serializeQueryParam. It will return the string as “[object object]”.

_serializeQueryParam(value, type) {
   if (value === null || value === undefined) {
     return value;
   } else if (type === 'array') {
     return JSON.stringify(value);
   }

   return `${value}`;
 }

How can I proceed the transition to an engine route with object type QP?

Posts: 1

Participants: 1

Read full topic

Websocket Implementation without Node.js running Ember?

$
0
0

@Paracoder wrote:

Hello all!

I’ve been pouring over frameworks for the past week - research, test, run into a problem, find out it requires a billion dependencies and/or don’t fit the build structure we are needing…

As such, I’m hoping that I can get some clarification regarding the capabilities of this framework in this setting…

We have 3 parts to our environment:

  1. UI hosted (anywhere - not embedded)
  2. Node.JS Server as controller
  3. Java Server as the backend computational/database access point

We have our reasons for requiring the separation between UI and the Java Server and or UI and the database… please do not reply with “well you should just drop the Java” or “drop the Node.JS”… this is being built in the context of financial institutions and therefore requires a greater level of processing and separation.

What I did:

Created a ‘vanilla’ JS/jQuery UI which can request dialogs/data from Node.JS - which authenticates the user, requests the data, and then generates “on the fly” a new (div) window for the user.

The problem with this is rather obvious: while it works for now, any changes in either code can complicate things - and we’ll be hiring developers who need to “pick it up and run with it” once the infrastructure is complete.

As such, I’m looking for a way to do this:

User Requests Info -> UI -> send request over WebSockets -> Node.JS takes request, authenticates, and replies with a dataset and name of the dialog to make -> UI generates dialog with attached data, and passes it on to the user once completed.

As this is meant to be a SPA, and we’re avoiding routing as the idea is to load a new div in the same ‘index.html’, I had looked into Vue.js but ran into serious issues with the WebSocket implementations as the compiling required complicates data retrieval over WebSockets, and Socket.IO … while functional, is not enough of a ‘standard’ to be used in this way. The Java server is also using (pure) WebSockets, so we don’t want to have to do some “loop” when they could all “speak the same language”.

Ideally, we do not want Node.js compiling or spitting out any html or views within it - as in the future a mobile app or other entry point may be added, we need generic ‘envelopes’ to be sent across the wire, allowing the UI to handle their output.

I.e. :

envelope = [ header: “infoRequest”, body: { // array of info } ]

Based on the header, it will then pass off the body to the appropriate function for loading.

If this can be done within Ember.js using websockets as communication, without routes and Node to do the generation… please point me in the right direction!!

Thank you for your time, look forward to the feedback. :slight_smile:

Posts: 1

Participants: 1

Read full topic

Generate route hangs

$
0
0

@453 wrote:

Hello, I am new to ember, so probably doing something dumb, but the ember cli seems to hang when I try to generate a route. I put the details below, and am also curious how I would go about trouble shooting issues like this with the ember cli. For example are there log files etc.? I’m on Windows and not seeing any clues in the event viewer etc.

Thank you!

When try: ember generate route application It replies with: installing route ?Overwrite app\templates\application.hbs?

I enter “n” then see “No, skip” and hit enter

Then the ember cli just hangs - no out put or error messages. And the file is not generated. Need to close the terminal to stop it.

Output from ember version --verbose && npm --version && yarn --version: ember-cli: 3.3.0 http_parser: 2.8.0 node: 10.9.0 v8: 6.8.275.24-node.14 uv: 1.22.0 zlib: 1.2.11 ares: 1.14.0 modules: 64 nghttp2: 1.32.0 napi: 3 openssl: 1.1.0i icu: 62.1 unicode: 11.0 cldr: 33.1 tz: 2018e os: win32 x64 6.4.0 1.9.4

Posts: 1

Participants: 1

Read full topic

Unknown Global Errors when upgrading Ember

$
0
0

@Rocker_Coder wrote:

when upgrading Ember 2.11 to 2.18 I got alot of Unknown Global errors:

  • Ember.Inflector

Unknown Global Global: Ember.Inflector Location: app\routes\base-mt.js at line 17

 i18n: Ember.inject.service(),
searchFilter: Ember.inject.service('search-filter'),
inflector: new Ember.Inflector(Ember.Inflector.defaultRules),
init: function () {
    this._super();
  • Ember.testing

Unknown Global Global: Ember.testing Location: app\routes\base.js at line 30

    //Don't attempt route reloading if testing
    if(!Ember.testing) {
        this.cleanMemory(routeName);
    }
  • Ember.MODEL_FACTORY_INJECTIONS

Unknown Global Global: Ember.MODEL_FACTORY_INJECTIONS Location: app\app.js at line 10

var ComposerOverrides = window.ComposerOverrides || {};

Ember.MODEL_FACTORY_INJECTIONS = true;

Ember.TextField.reopen({

  • Ember.production

Unknown Global Global: Ember.production Location: app\router.js at line 1937

 });

if(!Ember.production) {
  • Ember.onerror

Unknown Global Global: Ember.onerror Location: app\application\route.js at line 48

     let route = this;
    if(Ember.production) {
        Ember.onerror = function (error) {
            route.router.send('error', error);
        };
  • Ember.Logger

Unknown Global Global: Ember.Logger Location: app\application\route.js at line 167

         if (error  error.message){
            if(!Ember.production) {
                Ember.Logger.error(error.message);
            }
            let errorModel = Ember.Object.create();
  • Ember.Handlebars

Unknown Global Global: Ember.Handlebars Location: app\helpers\add-new-line.js at line 5

export function addNewLine(value) { var breakTag = ‘
’; let str = Ember.Handlebars.Utils.escapeExpression(value);

  • Ember.String

Unknown Global Global: Ember.String Location: app\services\jsonschema-validation.js at line 14

   // supports, will do for the moment.
    if (!model.includes('-w-')) {
        model = Ember.String.pluralize(model);

Posts: 1

Participants: 1

Read full topic

Action naming conventions, what's your preference?

$
0
0

@kjf wrote:

I’m curious to find out what naming conventions people are using for their actions.

Our app is a mix of camel-case eg:selectImage and kebab-case eg:on-saveand we’re trying to settle on one convention that works. I’ve seen both approaches used in popular add-ons and core ember seems to prefer kebab-case judging by the conventions used in on the input component actions however there doesn’t seem to be any clear indicator as to what’s preferred in the community.

One thing I like in the react world is the convention of onClick={handleClick} for event bindings, where the left side of the binding is onSomething and the right hand side is handleSomething. That seems to work great for react however handleClick doesn’t feel very ember like to me.

I’m very curious to get other peoples take on things.

Posts: 2

Participants: 2

Read full topic


'router.send' method using Router Service

CMS with Ember nice URL slugs and link to helper

$
0
0

@BenediktD wrote:

Hi,

I’m creating a small CMS with a Drupal backend (https://www.contentacms.org/) for Ember. In the backend I have a field to define a path for each page. I’m having trouble how to architect the routing in a bice way. I would like to avoid using page ID and just use the path defined in the backend.

this is a property I can access through my api as one string /foo/bar/baz.

What I’m having trouble is defining my router so I can use the path defined in the api. It works when the slug is simply /foo or /bar. But what do I do if the slug is /foo/bar or just `/´ or any other length.

This is what my router looks like currently.

Router.map(function() {

       this.route('page', { path: '/:path });

}

I’m also having trouble with the menu. How can I define a LinkTo helper that would work for any url length. {{#link-to 'page' item.alias}} only works for urls in the first level.

Also I’m wondering how I would approach converting internal links that are used inside the body field with link-to helpers. I’m also having the same issue in the menu.

Posts: 1

Participants: 1

Read full topic

Will Ember.Logger be replaced with window.console in Ember 3.4 LTS?

How to stub a computed property

$
0
0

@Willibaur wrote:

Hi all, I’m trying to stub the following within a rendering component test

  breadcrumb: computed('router._router.currentPath', function() {
    const routeName = this.get('router._router.currentPath').replace('index.index', 'index');
    const { breadCrumb } = getOwner(this).lookup(`route:${routeName}`);
  }),

So far I have managed to do it for routeName but I don’t understand how to stub breadCrumb

This is what I have so far:

  test('IS mobile View', async function (assert) {
    setMobileViewStatus(this, true);

    const transitionTo = path => assert.equal(path, 'foo', `transition to correct path \`${path}\``);
    const router = { _router: { currentPath: 'foo.index' }, transitionTo };

    this.setProperties({ router });

    await render(hbs`{{sp-bootstrap/mobile/header router=router}}`);
    const hasMobileViewClass = find('.nav-masterhead-mobile');

    assert.ok(hasMobileViewClass, 'HEADER is rendered on mobile' );
  });

Is there a way to stub the whole computed property and make it return whatever I want?

Thanks for your help

Posts: 2

Participants: 2

Read full topic

Deploying individual Engines

$
0
0

@Josh_Bailey wrote:

Is it possible to build & deploy Engines separately from the host application? If so, how? If not, what work would need to be done to allow this?

I wanted to post here to hopefully gather potential solutions/resources, any possible work done in user space, possible workarounds, etc.

We have a basic setup with one consuming app (the dashboard) and a growing number (5 ATM) of Engines that represent the various lines of businesses within our app. A recent concern among my team has come up with regards to having more control of the build and deploying the individual parts of our app. Sadly, this has lead to discussions on considering other, lighter-weight frameworks that allow the use of bundlers (a la React + Webpack).

Some very high-level thoughts I had:

  • It seems all the Engine asset info is in [app-name]/config/asset-manifest, this could be bundled as a separate JSON file that Engines could update, deploy along with its assets, and then allow the host app to consume independently and always reference the newly deployed engine assets
  • Possible issues if new routes are added to the Engine, would the existing mount in the host app’s route map pick these up
  • Will the new Packager ember-cli api help/solve this?

I’m sure I’m missing a lot of nuances I’m unaware of…

Thanks in advance for any feedback, direction, etc.

Posts: 1

Participants: 1

Read full topic

Upgrading to 3.4.2 produced dozens of new errors and warnings

$
0
0

@larryh wrote:

Hi,

I just upgraded from 3.3 to 3.4.2 and for the first time saw 5 warnings and dozens of errors when I fired up the server.

The warnings are of the form: node-modules are missing dependency fsevents. This happens to two of them: chokidar and sane

The errors come in 3 flavors:

  1. You must use double quotes in templates
  2. Incorrect indentation
  3. Unexpected partial usage

Regarding the warnings: Since they happen not-in-my-code should I just ignore them and assume that ultimately they will be fixed?

Regarding the errors: Like I said, there are a LOT of these suckers. It’s not like my templates contain crappy code (but then again, we all say that, right :wink: )

  1. I just happen to always use single quotes instead of double ones.
  2. I’m a big believer in visual clarity, so my indentations are (to me) very readable.
  3. My partials are simple HTML code. (I have a Rails background and have always thought that partials were a great idea.) I’ve heard that they might be deprecated, but didn’t worry too much about it because I wasn’t “pushing the envelope” with them.

So for (1) and (2), do you think it’s worth spending a lot of time on truly minor fixes, or is there some kind of ESLint rule that I can use to have these ignored? And even if there is such an exclusionary rule, is there a compelling reason to take the hit and slog through all of these changes?

And for (3), have partials officially been considered bad? If so, should I just replace them with HTML-only components?

Thanks,

Larry

Posts: 4

Participants: 2

Read full topic

How to make redirect from back-end side?


How to exclude a route and related files while ember build

$
0
0

@SarathSantoshDamaraj wrote:

Say, I have a repo with in-app add-ons and I want to create a route (say dev-docs) which will have docs/style guides on how to use those add-ons. So, while building my app, I want that route (dev-docs) and related *.css, *.js and *.hbs files to be excluded from /dist. I don’t want to host dev-docs separately as it becomes complex to maintain as the number of add-ons grow.

Posts: 1

Participants: 1

Read full topic

Encountered "1" in payload, but no model was found for model name "1" (resolved model name using (unknown).modelNameFromPayloadKey("1"))

$
0
0

@Raphael_FOSSE wrote:

Hi,

I’m currently working on a todoApp using Rails API as backend and EmbersJs as front. I want everything to be displayed on the rootURL.

I got this error from my firefox console : Encountered “1” in payload, but no model was found for model name “1” (resolved model name using (unknown).modelNameFromPayloadKey(“1”)).

I dont understand where that could come from.

here’s my app/models/todo.js : import DS from ‘ember-data’;

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

my app/routes/application.js:

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

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

And my app/templates/application.hbs :

<h1>Test micro</h1>

<ul>
  {{#each model as |todo|}}
    <li>{{todo.title}} Fait ? :{{todo.isCompleted}}</li>
  {{/each}}
</ul>
{{outlet}}

my rails-api/serializers/todo_serializer.rb :

class TodoSerializer < ActiveModel::Serializer
  attributes :id, :title, :isCompleted
end

my `rails-api/controllers/todos_controller.rb:

class TodosController < ApplicationController
  def index
    render json: Todo.all
  end
end

and my rails-api/models/todo

class Todo < ActiveRecord::Base
end

As i’m new on Ember, maybe am i looking at the wrong place, but if someone have an idea, that would be awesome ! If you need any further informations, just let me know.

Posts: 1

Participants: 1

Read full topic

Ember mirage: 'cannot read property 'get' of undefined'?

$
0
0

@GregWeb wrote:

I have an existing app and tried to get mirage working with it.

export default function () {
this.namespace = '/api/v0';   
  this.timing = 2000;  
  this.get('/accounts', function () {
    console.log("yoooooooooo");
    return{
      users: [
        { id: '1', email: 'joe@myapp.io' },
        { id: '2', email: 'mark@myapp.io' },
      ]
    };
  });

  this.post('/api/login', function(req, res) {
    res.send({
      id: '1',
      token: 'token',
      email: req.body.email,
      isAdmin: true
    })
  }

In Chrome inspector the console log is outputted, but I get errors:

What is this “raven” error? and what is the undefined error trying to tell me?

Posts: 1

Participants: 1

Read full topic

Passing Controllers between ember engines

$
0
0

@wojo wrote:

I try adding a controller as an ember engine and I get this error: “Assertion Failed: Dependencies of category ‘controllers’ can not be shared with engines.”

I have a high level app that handles loading my most important data. I’d like my lower level engines to reference that app.

Posts: 1

Participants: 1

Read full topic

Examples of running non-fastboot ember tests through heroku CI?

$
0
0

@mattmcmanus wrote:

Hey friends, This whole circleci 2 rollout has left a terrible taste in my mouth. I’m also interested in heroku CI’s on demand test runs. Has anyone setup their ember apps to use it? How’s it going? Did you run into any technical issues or billing surprises?

Posts: 2

Participants: 2

Read full topic

Viewing all 4748 articles
Browse latest View live




Latest Images