vendredi 30 août 2019

how can i call a function inside ember octane template without event?

I have a function called calculatePercentage which take a value and return percentage if i want to call this function inside every li such as

<li></li> 

without any user event how can i do that in ember octane app ?

export const calPrecOfTwoNums = (num: number, min: number, max: number) => {
    let precentageResult = Math.round((((num - min) * 100) / (max - min)));
    if(precentageResult < 0) {
        precentageResult = 0;
    } else if(precentageResult > 100) {
        precentageResult = 100;
    }
    return precentageResult;
}




Why some properties don't show in hbs?

I've made a model with some properties:

name: DS.attr('string'),
avatar: DS.attr('string', {defaultValue: 'https://dummyimage.com/100x100/fff/000'}),
yearStart: DS.attr('number'),
experience: computed('yearStart', function() {
    return '56';
}),

And a template where I'm trying to get those properties to a browser:

<ul>
    
        <li>
            <img src= alt=>
            <a href="#"></a>
            <br>
            Начал в  г.
             лет опыта
            <br>
            
        </li>
    
</ul>

this.model is filled with router by this.store.findAll('photographer');. The data is coming from mirage-cli:

    return {
        data: [
            {
                type: 'photographer',
                id: 1,
                attributes: {
                    name: 'Василий Пупкович Иванов',
                    'year-start': 2000,
                }
            }
        ]
    };

With Ember Inspector I see the photographer has property yearStart filled with value of 2000, but it is not shown in browser (and experience property too).

What am I doing wrong?




jeudi 29 août 2019

Retrieve model's property value using a dynamic variable

I want to retrieve a property of a model which has been set dynamically based upon the user which has logged in to the system, in my hbs file.

Suppose fromReports is a property I have set dynamically in the model
,it could be model.fromInstruments for another user
Given, model.fromReports=false or model.fromInstruments =false
and I have var x= fromReports or var x= fromInstruments
I want to get value of model.x in my hbs 

I should get the value as false as both model.fromReports and model.fromInstruments is false




Why is ember changing the name of my model on the first save() attempt but not subsequent save() attempts?

I have a button that is linked to an action to update then save a model:

// component.js
resolveInvestigation(itemID) {
    let item = this.get('store').peekRecord('customers-investigations-item', itemID)

    set(item, 'status_id', 1)

    item.save()

}
// template.hbs

<button >

The button is part of a bootstrap 'card' style component so there are a few instances of it on the page.

If I click the button on card A I get a console error as follows:

Error: No model was found for 'customers-investigation-item'

I have no idea why it has decided to drop the s from 'investigations' - it doesn't even make the PATCH call. If I then click the button on Card B, the model saves correctly. If I reload the page and click Card B first, I get the error, then if I click Card A, it saves correctly.

I'm at a bit of a loss. I thought it might have been some weirdness with native class syntax or the @action decorator but I reverted to a classic component with no improvement. As an example, I am also saving this model in another part of the app with no issues as follows:

      let items = this.store.peekAll('customers-investigations-item').filter((item) => {
        if (item.isNew) {
          return true
        }
      })
      items.forEach(function (item) {
        if (item.isNew) {
          item.set('customer_id', response.id)
          item.save()
        }
      })

I first thought that it was some strrange plurilize/singularize behaviour occuring on save() but that wouldn't explain why subsequent saves after the initial attempt are fine, or how the model saves in other locations of the application.




mercredi 28 août 2019

How can i submit video like this website? [on hold]

I know a website, i want to submit videos same like that website. can you please help me with that.

http://watchwrestling24.net/watch-wwe-205-live-8-27-2019/

here is the website link only link worth with this website if you close the Watchwrestling main website link will redirect to another one

https://education-load.com/watch/player.php?id=TWpBNU1qST0=

this page will redirect you to another page 404 but work's with http://watchwrestling24.net/watch-wwe-205-live-8-27-2019/

this is first link of page

only video link's worth in next tab of website




Tabulator "Rownum" formatter issue

Upon adding a new row after deleting a row in tabulator, rownum formatter doesn't show the latest serial number. Shows the serial number based on number of rows present instead of considering the already existing serial number.




Como bloquear elementos alaranjados de uma página Web?

Gostaria de saber como faz para bloquear elementos alaranjados no Google Chrome com o aplicativo(plugin) Ublock Origin. Alguém pode me ajudar como faz para bloquear esses dois elementos?

Website: hornet.com

Código: <textarea rows="1" autocomplete="off" placeholder="Escreve algo aqui..." id="ember129" class="ember-text-area active-conversation__new-message js-active-conversation-message-input ember-view" readonly="" disabled=""> </textarea>

Elementos para bloquear: readonly disabled

hornet.com###body > .readonly hornet.com###body > .disabled hornet.com##.readonly hornet.com##.disabled




Ember - Component property is not getting updated in template hbs

I have a component property in my component.js based on which i will show/hide some data in template.hbs

Case1: By default the componentProperty (canShow) is true, but based on some change in data it will be set false in another computed property.

        dataChanged: computed( 'data', 'canShow', function () {
            if(it is true) { 
                this.set('canShow', false);
             }
        });

Expected: Canshow should be false, so the data in template should be hidden Result: It is getting updated as false, But in template the data is still showing

Case2: I have tried this with getter and setter in computed.

    canShowTemplateData: computed('canShow', {
       get() {
          return this.get('canShow');
        },
        set(key, value) {
          return value;
        }
    });

Even in this case, set is working fine. But the value is not at all updated in template using get() function. Also pls clarify while using set(), which value should be updated either canShow or canShowTemplateData?

Am I missing something? Or is there any other way to handle this?




lundi 26 août 2019

$ ember serve node_modules appears empty, you may need to run `npm install`

$ ember serve node_modules appears empty, you may need to run npm install

tried changing the node,ember and cordova versions

$ npm install -g node-modules

$ npm install -g node-modules npm WARN deprecated node-uuid@1.4.8: Use uuid module instead npm WARN deprecated hawk@1.0.0: This module moved to @hapi/hawk. Please make sure to switch over as this distribution is no longer supported and may contain bugs and critical security issues. npm WARN deprecated sntp@0.2.4: This module moved to @hapi/sntp. Please make sure to switch over as this distribution is no longer supported and may contain bugs and critical security issues. npm WARN deprecated cryptiles@0.2.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial). npm WARN deprecated hoek@0.9.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial). npm WARN deprecated boom@0.4.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial). npm WARN deprecated object-keys@0.2.0: Please update to the latest object-keys C:\Users\vinod raj\AppData\Roaming\npm\node-modules -> C:\Users\vinod raj\AppData\Roaming\npm\node_modules\node-modules\app.js C:\Users\vinod raj\AppData\Roaming\npm `-- node-modules@1.0.1




dimanche 25 août 2019

Change an Ember model's value before saving to server

I've got an Ember Model, with a field which I want to display and work with, but before I save or retrieve it from the server, I want to multiply/divide it by 1000.

This means the UI should always work with a smaller value, but save a larger value to the server. Likewise, it should retrieve a larger value from the server, but make it smaller before allowing it to be used by the controllers, routes, etc.

import DS from 'ember-data';

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

Essentially, I want my application to show these fields as:

/* my webpage */
Please enter name: "foo"
Please enter value: 5

But when I send the request, it should send them as:

{
    "myModel": {
        "name": "foo",
        "value": 5000
    }
}

It should also receive them in this format, but then deserialise the value by dividing by 1000.

Please note that multiplying/dividing by 1000 is an example - I may want to append, prepend, add, subtract, etc.


I tried doing this in a less elegant way:

// Controller.js
actions: {
    save: function() {
        this.set('model.value', this.get('model.value') * 1000);
        this.get('model').save().then(
            /* stuff */
        );
        this.set('model.value', this.get('model.value') / 1000);
    }
}

But I'm not happy with this, and it results in duplicated code that is hard to maintain, and error-prone.

I have a RESTSerializer, but I don't know how to use it to manipulate fields, and couldn't find anything in the documentation. Maybe I need to use a different serializer? Mine is basically empty so far.

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    primaryKey: 'name',
});




How to get INSPINIA css animations working in Ember

This posting is an extension of a post that I made here: How do I install bootstrap 4 template to Ember web project?

How do I get the INSPINIA css animations working in Ember?

I am attempting to get the collapse-able sidebar navigation menu working (see the INSPINIA link here). Currently, I do not see the arrow and the menu is displayed only in expanded form in the <ul class="nav nav-second-level">...</ul> block of code.

In looking at the sample projects and View Source page, there appear to be a lot of add-ons that INSPINIA uses. Do I need to install all of them? Or, do I just need jQuery?

Here is the code for my handlebar file in question.

<nav class="navbar-default navbar-static-side" role="navigation">
    <div class="sidebar-collapse">
        <ul class="nav metismenu" id="side-menu">
            
                <li class="active"><a href="#"><i class="fa fa-th-large"></i> <span class="nav-label">Client</span> <span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li><a href="#">Update Information</a></li>
                        <li>Change Password</li>
                        <li><a href="#" onclick=>Logout</a></li>
                    </ul>
                </li>
            
                <li>Login</li>
                <li>Register</li>
            

            <li>About</li>
            <li>Contact Us</li>
        </ul>
    </div>
</nav>




samedi 24 août 2019

sublime text 3: it doesn't show lint error red line?

i use sublime text-3 for a ember workflow and i want sublime text show me a red error line during my coding if for example i use double quotes in typescript file, forget add a spaces or use a incorrect indentations? for Example in this

const RATINGS = {
    BAD: 'BAD',
    MEDIUM:'MEDIUM',
    GOOD:"GOOD",
};

this must show a red line in second line and third line, so if there is a plugins for that ?




vendredi 23 août 2019

How to migrate from ember-i18n to ember-intl in ember verision2.14

I am working on a ember project version 2.14, we are migrating from ember-i18n to ember-intl, currently the project has translation files with .coffee format with some import in it of other translation file with .coffee format from other shared folder.

Not sure how to migrate




How to reload a model with additional query params?

I have model which has_many trains. After clicking some button I want to reload these trains, but I want each reloading request to be sent with additional query parameters.

Now I have something like this:

this.get('model.trains').forEach(function(train) {train.reload()});

which sends trains/:id requests, but would like it to send something like trains/:id?class=1

How can I do this?




How can I get a HTML Page from Spring using Ember. How to request a html page?

I have a login.html page in Spring. I have a controller to serve this page at port 8080. How can I get this complete page using ember?

This is my controller:

@Controller
public class LoginController {

    LoginService loginService;

    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    @RequestMapping("/login")
    public String showJoke(Model model){

        model.addAttribute("date",loginService.getDate());

        return "login";
    }
}

I didn't write any code on ember yet because I don't know where to write them( on controller or model or component)




jeudi 22 août 2019

relative bar percentage calculation

i want to draw a bar percentages calculations for a 3d object with the following condition 1- i have 3 background bar prefect good and bad all have same width 2- percentage from 0 to 60% must have color of green indicate for a good and must end in the prefect bar and from 60% to 85% orange color and end on the second bar and from 85% to 100% red and end on the bad color like in this picture
BarsPrecentageClaculation the problem is how to adjust this thresholds as in this photo whereas the 3 columns have same width for example if the first bar have percentage 55% it will have a prefect indicator whereas it will be in medium column in other word how to make bar from 0-60%->green->end on first column and from 60-85%->orange->end on second column and begin with third column ect..

const percentageCal = (num: number, min: number, max: number): number => {
    return Math.round((((num - min) * 100) / (max - min)));
}

const setBarsColor = (percentage: number): string => {
    let colorIndication: string;
    if(percentage >= 0 && percentage <= 60) {
        colorIndication = COLOR_INDICATORS.good;
    } else if(percentage > 60 && percentage <= 85) {
        colorIndication = COLOR_INDICATORS.medium;
    } else if(percentage > 85 && percentage <= 100) {
        colorIndication = COLOR_INDICATORS.bad;
    }
    return colorIndication;
}

i need a way to adjust color according to UX




Check database connection from the browser using Emberjs (or javascript)

I'd like to check a (random) database connection directly from my client-side app without running it through a server.

The reason for this, is that I don't want the database credentials to ever go through my server.

Any idea if and how this is possible?

(I'm using Emberjs, so ideally I'd like to use Ember to do it)




Handlebars conditional style attribute

I am using ember 1.8.1

The controller has a property isDisplay

In handlebars, I implement like this, it works but code is too long


    <div class="form-group">
    </div>

    <div class="form-group" style="display:none;">
    </div>


I tried to using conditional, like this but it doesn't work

<div class="form-group" >
</div>




mercredi 21 août 2019

How to test serializer when applying on the transformer in Emberjs

The problem is that I can't even run the test when I have a transform applying on the serializer. The errors show like this:

TypeError: typeClass.eachTransformedAttribute is not a function
    at Class.applyTransforms (http://localhost:7357/assets/vendor.js:116271:17)
    at Class.normalize (http://localhost:7357/assets/vendor.js:88027:12)
    at Context.<anonymous> (http://localhost:7357/assets/tests.js:854:41)
    at callFn (http://localhost:7357/assets/test-support.js:17929:21)
    at Test.Runnable.run (http://localhost:7357/assets/test-support.js:17922:7)
    at Runner.runTest (http://localhost:7357/assets/test-support.js:18392:10)
    at http://localhost:7357/assets/test-support.js:18498:12
    at next (http://localhost:7357/assets/test-support.js:18312:14)
    at http://localhost:7357/assets/test-support.js:18322:7
    at next (http://localhost:7357/assets/test-support.js:18254:14)


The version list:

    "ember-cli": "~3.11.0",
    "ember-mocha": "^0.16.0",
    "ember-cli-chai": "^0.5.0",
    "ember-cli-mirage": "^1.1.0",

unit/serializers/posts-test.js

import { expect } from "chai";
import { describe, it } from "mocha";
import { setupTest } from "ember-mocha";
import setupMirage from "ember-cli-mirage/test-support/setup-mirage";

describe("Unit | Serializer | Post", function() {
    let hooks = setupTest();
    setupMirage(hooks);

    it("serializers test", function(){
      let store = this.owner.lookup("service:store");

      let record = store.createRecord("post", {});

      let serializer = store.serializerFor("post");

      let input = {
         id: 888,
         title: "Good Day",
         content: "That's a good day."
      }

      let expectResult = {
         id: 888,
         data: {
           title: "Good Day",
           content: "That's a good day."
         }  
      }

      let normalize = serializer.normalize(record, input);

      expect(normalize).to.be.ok;

      expect(normalize).to.be.deepEqual(expectResult);
    });

app/serializers/post.js


import DS from "ember-data";

export default DS.RESTSerializer.extend({

   normalize(model, hash){
      const res = {
        id: hash.id,
        data: {
          title: hash.title,
          content: hash.content 
        }
      }

   this.applyTransforms(model, res.data); // I think the error start here

   return { data: res };   

   }

});


app/transforms/title.js

import DS from "ember-data";
import { A } from "@ember/array";
let Title = object.create({});

export default DS.Transform.extend({
    deserialize(serialized) {
        return Title.create(serialized);
    },

    serialize(deserialized) {
        return deserialized;
    }
});


app/transforms/content.js

import DS from "ember-data";
import { A } from "@ember/array";
let Content = object.create({});

export default DS.Transform.extend({
    deserialize(serialized) {
        return Content.create(serialized);
    },

    serialize(deserialized) {
        return deserialized;
    }
});



I can't even pass this serializer test, and I spent 5 days researching the easy approach to figure it out. unfortunately, I stuck on this question still.




Serialize has many only IDs when existing, but empty array when nil

Ember noob here, I've looked through docs on serialization and stack overflow posts and I either cannot find what I'm looking for or do not understand enough to know its what I'm looking for.

Currently I have an object called recipe, and recipe can have many recipes called linked recipes. When linked recipes exist, the serialization passes only the ID's into the requests to my back end, as intended. However when there are no linked recipes, nothing is serialized because there are no IDs. I would like an empty array to be passed back but it seems my serialization methods are preventing this.

    linkedRecipes: {
      serializer: 'ids',
      deserialize: 'ids'
    }

serializeHasMany: function(snapshot, json, relationship) {
  if(relationship.key == "linkedRecipes") {
    var k = "linked_recipe_ids";
    var records = snapshot.hasMany('linkedRecipes');
    var parameterValue = [];
    if(records) {
      records.forEach(function(item, index) {
        parameterValue.push(item.get('id'));
      });
    }
    json[k] = parameterValue;
  }
}

If linked recipes exist, my put request looks like linked_recipe_ids: ["1", "3"], the goal outcome is for when linked recipes dont exist, for the request to look like linked_recipe_ids: []

If there's any more code you'd like me to show I'd be happy to do so.




mardi 20 août 2019

Ember hasMany relationship save on create

I'm trying to create an ember data record with a hasMany relationship from a POJO, and it's been remarkably difficult. This is using ember-concurrency (hence the task and yield syntax.

  saveEntry: task(function* (obj){
      let entry = yield this.model.get('entries').createRecord({
        groupId: obj.objectID,
        name: obj.name,
        ...

      }).save();
      obj.owner_ids.forEach((user_id) => {
        this.store.findRecord('user', user_id).then((user) => {
          entry.get('owners').pushObject(user);
          entry.save();
        });
      })
   }).drop();

So the tough bits are the 'obj.owner_ids', which is an array of user_ids. I add each to the array, but then need to save after every pushObject or it doesn't work. And even when it does work, it is throwing a bunch of network errors (probably due to race conditions on the save). There must be a better way, but I haven't found it.




Assertion failed helper when I use custom yields in my application

I'm tryng this solution for my necessity to use two custom yields in same component:

How can I yield multiple pieces of content into an ember.js component template?

This is my code:

// component 

   
    This is a content
  
  
    This is a another content
  


// father-component
<div class="left">
  
</div>
<div class="right">
  
</div>

// foo-content 


In https://ember-twiddle.com/ this works nicelly, but in my localhost this dosn't works and return this error

Assertion Failed: A helper named 'f.right-content' could not be found

Some help?

I work with app exporting the components, and the path js and template separetly




lundi 19 août 2019

Ember reflexive relationship reloaded after removing it

In my app, recipes has a reflexive relationship called linkedRecipes. I have set the inverse to null. If a recipe has 3 linked recipes, and I remove 2 of them, everything works as intended. However whenever I try to delete the last recipe, whether that means deleting 3 of 3 linked recipes, or deleting 1 of 1, the linked recipe(s) will remain there on save, and will be sent in the PUT request for updating a recipe.

I have gone into the Ember inspector and watched the recipes linkedRecipes length become 0 after the removeLinkedRecipe function, but during the saveExistingRecipe function, and in the PUT request, the linked recipes still show as what they were before the removeLinkedRecipe function.

recipe.js:

export default DS.Model.extend({
  linkedRecipes: DS.hasMany('recipe', { async: true, inverse: 'null' }),
});

recipe-viewer.js:

removeLinkedRecipe: function(recipeId) {
  var self = this;
  this.get('model.linkedRecipes').forEach(function(linkedRecipe) {
    if (linkedRecipe.get('id') == recipeId) {
      self.get('model.linkedRecipes').removeObject(linkedRecipe);
    }
  });
}
saveExistingRecipe: function() {
  return $.ajax({
    url: '/api/v1/recipes/' + this.get('model.id'),
      type: 'PUT',
      data: { recipe: this.get('model').serialize() 
    }
  });
},

I'm working on a large application, and I'm not sure what other code would be helpful to show. Let me know if you need to see anything else.




How to get relationship model from relationship of another model

I have some models with relationships, that are fething from firebase through emberfire:

library:

export default Model.extend({
  title: attr('string'),
  address: attr('string'),
  phone: attr('string'),
  books: hasMany('book')
});

book:

export default Model.extend({
  title: attr('string'),
  description: attr('string'),
  author: belongsTo('author'),
  libraries: hasMany('library')
});

author:

export default Model.extend({
  name: attr('string'),
  books: hasMany('book')
});

how can i fetch all the libraries of some author's books?

I already tried to fetch children's model after fetching parent one, but seems like promises return instances of not Model's class, and there is no relations fields i expected :/

 async model() {
    const authors = await this.store.findAll('author')
    const books = await Promise.all(authors.getEach('books'))
    const libraries = await Promise.all(books.getEach('libraries'))
    // libraries variable is undefined, cause books has no 'libraries' property
    return authors
  }




Is it a correct way to implement ember-simple-auth authentication with graphql?

I have a graphql request. The request is working and it returns a token for a particular user. But I am not sure how to utilize that token with ember-simple-auth and its sessions. I've used just this: this.set("session.isAuthenticated", true). Using it, it seems to be that the application don't need to use authenticator at all. I am not sure about this decision and want to ask maybe there is a better way to use ember-simple-auth in this situation (when I get the token through graphql request and don't need to use authenticator). Also I wanted to ask whether I can save the token this way: this.set("sssion.token", token), or there's an "idiomatic" (built in) solution?

I've tried to use authenticator in a different ways, but it wasn't working. As I understand it is supposed to send POST-request on backend, but since there already is a graphql request, probably it means the application don't need authenticator, only session service is necessary. Are there some draw-backs in this decision?

My login.js file in controllers folder looks like this:

    actions: {
        authenticate() {
            let username = this.get('email');
            let password = this.get('password');
            let hash = {username: username, password: password };

            let controller = this;
            this.get('apollo').mutate({mutation: Mutation.TOKEN_AUTH, variables: hash})
            .then(function(result) {
                controller.set('session.isAuthenticated', true);
                console.log('session.isAuthenticated: ', controller.get('session.isAuthenticated'));
            })
            .catch(function(reason) {
                console.log('Error: ', reason);
            })

I've got "func is not defined" error in browser console, but not sure whether it's related to this problem.




samedi 17 août 2019

Port 4200 (or any other port I I TRY) is already in use

Ports I tried 8080, 4200, 4201, 4202 ... I used the following command to see if the port is being used and it is not being used

get-nettcpconnection | where LocalPort -eq "4200" | select local*,remote*,state,@{Name="Process";Expression={(Get-Process -Id $_.OwningProcess).ProcessName}}

I even used netstat -q to include bound nonlistening ports

I tried hard coding it in .ember-cli

I tried with firewall turned off

What works is ember serve --port 0 BUT I am getting some huge ports like 26000+. Why can I not use 4200 when it is not being used?




Ember serve: every port is in use

When I specify no port or set the port explicitly, I always see:

ember serve --port 4207
Port 4207 is already in use.

It doesn't seem to matter which port I pick.

When I start with port 0 (let the cli pick an available port) it starts on on something around 30000~40000.

I am on a Mac. I just upgraded my ember-cli to 3.12.0

What is wrong here?




jeudi 15 août 2019

EmberJS - Assertion Failed: computed expects a function or an object as last argument

Trying to use ember-models-table 3.x but facing an issue with "Assertion Failed: computed expects a function or an object as last argument."

ember-cli: 3.9.0

node: 10.16.1

Create a brand new ember project and updated the files below,

routes/test.js

import Route from '@ember/routing/route';
import {A} from '@ember/array';

export default Route.extend({
  setupController(controller) {
    controller.set('columns', A([
      { propertyName: 'index' },
      { propertyName: 'firstName' },
      { propertyName: 'lastName' },
      { propertyName: 'age' },
      { propertyName: 'city' }
    ]));
    controller.set('data', A({
      data: [
        { id: 1, type: 'movies', attributes: { name: 'Interstellar' } },
        { id: 2, type: 'movies', attributes: { name: 'Inception' } },
        { id: 3, type: 'movies', attributes: { name: 'Dunkirk' } },
      ]
    }));
  }
});

templates/test.hbs

<ModelsTable @data= @columns= />

router.js

import EmberRouter from '@ember/routing/router';
import config from './config/environment';

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

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

export default Router;

Error

index.js:163 Uncaught Error: Assertion Failed: computed expects a function or an object as last argument.
    at assert (index.js:163)
    at new ComputedProperty (metal.js:2757)
    at computed (metal.js:3220)
    at Module.callback (models-table.js:192)
    at Module.exports (loader.js:106)
    at Module._reify (loader.js:143)
    at Module.reify (loader.js:130)
    at Module.exports (loader.js:104)
    at requireModule (loader.js:27)
    at Class._extractDefaultExport (index.js:426)




How do I make my response upto the required standard

So, I have a backend rails application running which is responding for a particular request as follows

{"id": 68,"name": "name","email": "email"}

But in ember, I'm getting this error

Error: Assertion Failed: normalizeResponse must return a valid JSON API document:
* One or more of the following keys must be present: "data", "errors", "meta".
at Object.assert (index.js:163)
at normalizeResponseHelper (-private.js:7428)
at -private.js:13291
at Backburner._run (backburner.js:1010)
at Backburner._join (backburner.js:986)
at Backburner.join (backburner.js:757)
at -private.js:13287
at tryCatcher (rsvp.js:335)
at invokeCallback (rsvp.js:506)
at publish (rsvp.js:492)

I tried wrapping everything under a 'data' array, then I got this error

Error: Assertion Failed: normalizeResponse must return a valid JSON API document:
* Top level of a JSON API document must be an object
at Object.assert (index.js:163)
at normalizeResponseHelper (-private.js:7428)
at -private.js:13291
at Backburner._run (backburner.js:1010)
at Backburner._join (backburner.js:986)
at Backburner.join (backburner.js:757)
at -private.js:13287
at tryCatcher (rsvp.js:335)
at invokeCallback (rsvp.js:506)
at publish (rsvp.js:492)

How do I normalize it all and where, backend or frontend?

update: I made a hash response = {:data=>@user}, and then returned response.to_json I got this

Error: Assertion Failed: Encountered a resource object with an undefined type (resolved resource using (unknown))
at Object.assert (index.js:163)
at Class._normalizeResourceHelper (json-api.js:183)
at Class._normalizeDocumentHelper (json-api.js:133)
at Class._normalizeResponse (json-api.js:228)
at Class.normalizeSingleResponse (json.js:407)
at Class.normalizeSaveResponse (json.js:393)
at Class.normalizeCreateRecordResponse (json.js:351)
at Class.normalizeResponse (json.js:232)
at normalizeResponseHelper (-private.js:7421)
at -private.js:13291




Upgrading an Ember Project. What do I do about an ArrayProxy extending the deprecated SortableMixin?

I am attempting to upgrade an old (1.10) Ember project to the latest LTS release (3.8).

One of the things I am struggling with is this line, as Ember.SortableMixin has been deprecated.

ArrayProxy.extend(Ember.SortableMixin).create({ content: [] })

I have heard that we can use computed.sort to replace most occurrences, but what am I to do about this case, where the ArrayProxy is extending the Mixin?

I haven't been able to find much advice about this case online.

Thanks.




How to get Clicked Button on Ember Controller

I can't get the clicked button on ember controller

I used deleteStudent : function(event) {} but event is undefined. I also tried deleteStudent : function() { console.log(this);} but 'this' refers to something else;

//HTML

<ul>
    
    <li id=>  <button >x</button></li>
    
</ul>

//Ember controller

actions: {
            deleteStudent : function() {
            console.log(); // I want to get button here
          }




mercredi 14 août 2019

Adding meta data in ember-cli-mirage route handler

I need to return meta in my ember-cli-mirage route handler data along with the serialised objects in my tests

server.createList('things', 42);

this.get('/things', function(schema, request) {
  return this.serialize(this.schema.things.all());
});

I'd like the route handler to output:

{ data: ..., meta: { 'record-count': 42 } }

Is there a way to set up Mirage to do this or do I need to explicitly set that data on every request?




How do I trigger a function in an Ember component from the test component?

In the unit test ComponentA-test I would like to trigger the function load() in ComponentA, but I have problems doing so.

Before the assert.equal in the below code example I would like to add something simular to this.load() that I would have written in the component to trigger it. But I can't seem to find the right syntax for doing so.

    test('should render some information', async function (assert)) {
       await render(hbs``);

       assert.euqal(".info").text().trim(), "info text");
    }




Unable to polyfill Object.fromEntries in Ember

I have a simple Ember app and I need to polyfill Object.fromEntries in a component.

For reference, I use Safari 12.1.1 that supports fromEntries natively and Safari 11.1.1 that does not.

AFAIK, all I should need is a proper ember-cli-build.js config.

I would appreciate it if someone could tell me why the following tweaks do not properly polyfill the function:

const app = new EmberApp(defaults, {

  'ember-cli-babel': {
    // supposedly should inject core-js/stable into app
    // @see https://github.com/babel/ember-cli-babel#polyfill
    includePolyfill: true,
  },

  babel: {
    // should replace injected core-js/stable with imports
    // that are not natively supported by config/targets.js
    // @see https://babeljs.io/docs/en/babel-preset-env#usebuiltins-entry
    useBuiltIns: 'entry',

    // explicitly use corejs v3 per babel-preset-env docs
    corejs: 3,

    // force inclusion of fromEntries regardless of config/targets.js
    include: [
      'es.object.from-entries',
    ],
  },

  //...
});

I can see it's there: https://github.com/babel/babel/blob/v7.5.5/packages/babel-preset-env/src/polyfills/corejs3/built-in-definitions.js#L265


Package versions:

  • ember-source@3.7.2
  • ember-cli@3.5.0
  • ember-cli-babel@7.5.0
  • @babel/core@7.5.5
  • core-js@3.2.1



Why am i getting assertion error of FirebaseAppService

Version info

DEBUG: -------------------------------
DEBUG: Ember      :  3.4.4
DEBUG: Ember Data : 3.11.0
DEBUG: EmberFire  : 3.0.0-rc.3
DEBUG: -------------------------------

Steps to reproduce Try to save record on my firebase storage in controller:

import Controller from '@ember/controller';
import { computed } from '@ember/object';
import v4 from 'npm:uuid/v4'

export default Controller.extend({
  emailFromValue: '',
  header: 'Coming soon',
  alertMessage: '',
  showAlert: false,
  isDisabled: computed('emailFromValue', function() {
    return !this.emailFromValue.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/);
  }),
  actions: {
    changeEmailValue({ target: { value } }) {
      this.set('emailFromValue', value);
    },
    requestInvitation(e){
      e.preventDefault();
      this.store.createRecord('invitation', { id:v4(), email: this.emailFromValue}).save()

      this.set('alertMessage',`Thank you! We saved your email address: ${this.emailFromValue}`)
      this.set('showAlert', true)
    }
  }
});

config of firebase in environment:

firebase: {
      apiKey: "AIzaSyAhO6f8wKS-...",
      authDomain: "...9e.firebaseapp.com",
      databaseURL: "...39e.firebaseio.com",
      projectId: "...39e",
      storageBucket: "",
      messagingSenderId: "...45128",
      appId: "...94d4964176"
    },

Expected behavior Successful save the data

Actual behavior after calling save method of record i've got an error:

index.js:163 Uncaught Error: Assertion Failed: You must call `this._super(...arguments);` when overriding `init` on a framework object. Please update <libraries-app@service:firebase-app::ember204> to call `this._super(...arguments);` from `init`.
    at assert (index.js:163)
    at FirebaseAppService.__ASSERT_INIT_WAS_CALLED__ember1565768194366642062813808__ (object.js:88)
    at sendEvent (metal.js:462)
    at initialize (core_object.js:107)
    at Function.create (core_object.js:692)
    at FactoryManager.create (container.js:549)
    at instantiateFactory (container.js:359)
    at lookup (container.js:287)
    at Container.lookup (container.js:131)
    at Class.lookup (container_proxy.js:78)

How have i already tried to solve it:

  • Installed different versions of emberfire and ember-cli, but had another issues
  • Searched error in google and github issues, but haven't got any result



lundi 12 août 2019

Why won't my tracked array update in Ember Octane?

I'm trying out Octane, and for some reason, if I show an array in a template and I add a new object to it, the UI doesn't update. What am I doing wrong?

Here is my template:

<label for="new-field-name">Field Name</label>
<Input id="new-field-name" @value= type="text" />
<button >Add field</button>


    <p></p>


And the component:

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ConfigControlsComponent extends Component {
    @tracked fields = []
    @tracked newFieldName = ''

    @action addField() {
        this.fields.push({
            name: this.newFieldName
        })
        console.log(this.fields)
    }
}

The console.log shows the array with the new object added to it, and the fields array is tracked, but nothing changes when I click the button.




First ember build is very slow and gives a Error

If I start the Puma server with bin/rails server and then call my page via localhost:3000, I get a build error. After that, ember starts to build my app and after that I can call the page normally. But why does he show me an error first and doesn't build the page properly and shows it afterwards? Does anyone know which configuration I have to set how/where for this to work?

My Build Time (on first request):

Build successful (24232ms)

Slowest Nodes (totalTime => 5% )              | Total (avg)         
----------------------------------------------+---------------------
Bundler (1)                                   | 5151ms              
Babel: frontend (2)                           | 3411ms (1705 ms)    
Package /assets/vendor.js (1)                 | 1450ms              
broccoli-persistent-filter:TemplateCom... (7) | 1449ms (207 ms)     
Babel: @ember-data/store (2)                  | 1404ms (702 ms)     
SassCompiler (1)                              | 1308ms              
Babel: ember-test-helpers (2)                 | 1266ms (633 ms)

Output from ember version --verbose && npm --version && yarn --version:

ember-cli: 3.11.0
http_parser: 2.8.0
node: 8.16.0
v8: 6.2.414.77
uv: 1.23.2
zlib: 1.2.11
ares: 1.10.1-DEV
modules: 57
nghttp2: 1.33.0
napi: 4
openssl: 1.0.2r
icu: 64.2
unicode: 12.1
cldr: 35.1
tz: 2019a
os: darwin x64
6.4.1
1.1.0

My package.json:

{
    "name": "frontend",
    "version": "0.0.0",
    "description": "",
    "license": "MIT",
    "author": "",
    "directories": {
        "doc": "doc",
        "test": "tests"
    },
    "repository": "",
    "scripts": {
        "build": "ember build",
        "start": "ember server",
        "test": "ember test"
    },
    "dependencies": {
        "ember-cli-babel": "^7.8.0",
        "ember-cli-htmlbars": "^3.1.0",
        "ember-cli-shims": "^1.2.0",
        "ember-concurrency": "^1.0.0",
        "ember-data": "3.12.0",
        "ember-file-upload": "^2.4.4",
        "ember-js-pdf": "^0.4.2",
        "ember-responsive": "^3.0.5",
        "ember-source": "3.12.0",
        "ember-wormhole": "^0.5.2",
        "fabulous-table": "^1.0.5",
        "jquery-confirm": "^3.3.2",
        "node-sass": "^4.7.2",
        "print-js": "^1.0.61"
    },
    "devDependencies": {
        "broccoli-asset-rev": "^3.0.0",
        "ember-ajax": "^5.0.0",
        "ember-array-helper": "^5.0.0",
        "ember-cable": "0.8.1",
        "ember-cli": "^3.11.0",
        "ember-cli-app-version": "^3.1.3",
        "ember-cli-dependency-checker": "^3.2.0",
        "ember-cli-head": "0.4.1",
        "ember-cli-htmlbars-inline-precompile": "^2.1.0",
        "ember-cli-ifa": "^0.7.0",
        "ember-cli-mirage": "^1.1.0",
        "ember-cli-moment-shim": "^3.5.0",
        "ember-cli-qunit": "^4.3.0",
        "ember-cli-rails-addon": "0.10.0",
        "ember-cli-sass": "^10.0.1",
        "ember-cli-spinner": "0.0.9",
        "ember-cli-sri": "^2.1.0",
        "ember-cli-test-loader": "^2.2.0",
        "ember-cli-uglify": "^3.0.0",
        "ember-cookies": "^0.4.0",
        "ember-custom-actions": "3.2.0",
        "ember-export-application-global": "^2.0.0",
        "ember-highcharts": "0.5.4",
        "ember-i18n": "^5.1.0",
        "ember-ionicons": "^0.1.1",
        "ember-load-initializers": "^2.0.0",
        "ember-moment": "^7.5.0",
        "ember-resolver": "^5.2.1",
        "highcharts": "^6.2.0",
        "loader.js": "^4.6.0"
    },
    "engines": {
        "node": ">= 8.9.1 < 9"
    },
    "private": true
}

My Error in Server Console:

Completed 500 Internal Server Error in 2822ms (ActiveRecord: 26.7ms)


Not notifying due to an invalid api_key

EmberCli::BuildError - :frontend has failed to build: - Building
:
  app/views/ember_cli/ember/index.html.erb:8:in `_app_views_ember_cli_ember_index_html_erb__3097041922955580926_70136581441240'

My index.html.erb looks like:

<script type="application/javascript">
  window.I18n = {
    locale: '<%= I18n.locale %>',
    defaultLocale: 'de'
  };
</script>

<%= render_ember_app params[:ember_app] do |head| %>
    <% head.append do %>
        <%= csrf_meta_tags %>
    <% end %>
<% end %>




vendredi 9 août 2019

How do I define an input using Angle Brackets?

I know how to make an input in Ember using curly braces:



How do I do this using Angle Brackets component syntax?




checksum of a file in javascript

I have a use case where if a user uploads a file and then before it gets uploaded, I want to calculate a checksum on that file within the browser. I found couple of libraries but for files more than 3 GB, the calculation time is too much so was wondering is there any way this can be achieved in JS. I am using Ember as my front end framework.

Referred below article:

https://medium.com/@0xVaccaro/hashing-big-file-with-filereader-js-e0a5c898fc98




How to convert javascript with define statements and module exports back to pure javascript?

Hi, I am trying to view a web page offline in a localhost environment. The site seems to be an https://emberjs.com/ based app that uses a bunch of define and export statements to organize the app functionality.

The thing is, I don't really need any of the app overhead since I already have the entire page downloaded (there are no links to other pages - all content is on one page) and therefore I just require the browser interaction. That is also to say I don't require ember on my local system. The reason I am using localhost is because some of the large assets are on a cloud storage site and the mechanism to retrieve those particular assets does not work with file:// protocol.

The web app seems rather complex and is way beyond my abilities to decipher and reverse engineer. I just know that for my goals, simply having the user interaction portions of the app (like playing audio file, video file, clicking through slideshows, etc) will suffice. I don't require any AJAX sort of interaction. Basically I just need the page to work similar to Chrome or Firefox Offline viewing.

So after downloading all the assets and replacing all remote links with local links, I saw that all the javascript is handled through two massive files: vendor.js and app.js.

Vendor.js is where various vendor components reside, like jquery. App.js is where the app is loaded and where all page interaction is scripted. If viewing the remote file in Chrome, it is able to build an entire source directory structure where I see all individual assets, but they are all mixed in to the massive vendor.js and app.js.

If I comment out the app.js include in the page's HTML, then there is no user interaction. I see all audio and video components but no reaction to me pressing play buttons (which all depend on audio/video js modules). If I include app.js then the page acts like it is loading for the first time and all the downloaded assets are basically wiped from the browser. That is, when I load the page as localhost/thepage.html I first see the fully downloaded page but then it refreshes and goes into the app initialization mode which amounts to blank page showing that it is trying to load the app, which in my case is not needed since I already downloaded the page after the app loaded...

That is where I am stuck. I can't figure out how to disintegrate the app overhead from the app's interaction code.

Looking in Chrome developer under sources, here is what a typical page interaction module looks like:

define('theapp/mixins/av-players', ['exports', 'ember'], function (exports, _ember) {
  exports['default'] = _ember['default'].Mixin.create({
    startAV: function startAV() {
      var mainPanel = $('.main-panel'),
          video = $('.video-player').get(0),
          video_player = $('.video-player .player').get(0),
          audio = $('.audio-player .player').get(0),
          seek = $('.audio-player .audio-controls #player-seek'),
          volume = $('.audio-player #player-vol'),
          timeCode = $('.audio-player .audio-timecode'),
          controls = $('.audio-controls > i, .audio-controls > label').not('.fa-retweet'),
          repeatBtn = $('.audio-controls > .fa-retweet'),
          player = $('.audio-player'),
          title = $('.header .current-course-topic'),
          lesson = $('.audio-player .topic-title');

      if ($.isMobile) {
        $('.video-player .fa-chevron-circle-right').addClass('ipad-control');
      }

      $(document).on('click', '.track-handle', $.proxy(this.playAudioFromOb, { lesson: lesson, video: video, video_player: video_player, audio: audio, controls: controls, player: player })).on('click', '.audio-asset', $.proxy(this.playAudioFromOb, { lesson: lesson, video: video, video_player: video_player, audio: audio, controls: controls, player: player })).on('click', '.video-asset', $.proxy(this.playVideoFromOb, { audio: audio, player: player, video: video, video_player: video_player })).on('click', '.video-player .fa-chevron-circle-right', $.proxy(this.minmaxVideoPlayer, { video: video, video_player: video_player, mainPanel: mainPanel })).on('click', '.video-player .fa-play-circle', $.proxy(this.videoPlayAction, { video_player: video_player })).on('click', '.video-player .fa-pause', $.proxy(this.videoPauseAction, { video_player: video_player })).on('click', '.video-player .fa-times-circle', $.proxy(this.closeVideoPlayer, { video: video, video_player: video_player }));

Plus a whole bunch of other code, but you get the point: these interaction modules are what I need to strip from the app.js and just reduce everything down to these modules.

I am not sure if I really need these define constructs, which is why I was thinking that if I could find the needed modules in Chrome's sources view, I could just create another app.js with just the needed module code, no exports, or any other unnecessary complications, but at same time I really just want to see what you all recommend in terms of procedure.

So in summary, I am expecting to view my downloaded page and to interact with various modules on the page such as audio and video players. What I am getting instead is a page that thinks the app has to load from scratch and is therefore ignoring everything that is already on the page...




jeudi 8 août 2019

How to over ride a function of component in integration test in ember Qunit testing

I'm writing my first question here sorry for any ambiguity.

I write an integration test for 'update-pw' component which simple render 'update-pw' and then fill input field with fillIn and then click save button which trigger the action 'in update-pw.js'. I only pass email(for whom we want to change password) and new password. savePW() function further has a function call 'self.store.updateSingleUserPw(email, newPw)' which is written in service -> 'store.js'. updateSingleUserPw(email, newPw)<-- this return a promise after server process on api call. On basis of fulfillment or rejection of promise I show a modal. I just want to make that promise fulfill or rejected in my test instead of server response for promise.

integration/component/update-pw-test.js

import { module, test } from 'qunit';
import EmberObject from '@ember/object';
import { setupRenderingTest } from 'ember-qunit';
import { render, fillIn, click } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import Service from '@ember/service';

module('Integration | Component | update-pw', function(hooks) {
  setupRenderingTest(hooks);
  const store = Service.extend({
    savePW() {
self.store.updateSingleUserPw(email, newPw, function() {

        console.log('this is function overriding', email, newPw);

        return true;

      })
        .then(function() {
          // Reset controller fields
          self.set('password', '');
          self.set('updateModal', false);
          swal({
            title: 'Das hat geklappt',
            type: 'success'
          });
        }, function() {
          self.set('updateModal', false);
          swal({
            title: 'problems with setting new pw.',
            type: 'error'
          });
        })
        .finally(function() {
          self.set('changingPassword', false);
        });

    }
  });
  test('it renders', async function(assert) {

    this.application.register('service:store', store);
    this.application.inject.service('store', { as: 'store' });
    assert.expect(2);
    this.set('updateModal', true);
    this.set('testing', true);
    let currentUpdateAdmin = EmberObject.create({
      username: 'steinauer',
      email: 'lala@test.at'
    });
    this.set('currentUpdateAdmin', currentUpdateAdmin);
await render(hbs``);

    assert.equal(this.element.querySelector('h4').textContent.trim(), 'set new PW for steinauer');
    await fillIn('#password', 'test123456');
    await click('.save-button');
    // Template block usage:
    await render(hbs`
      
        template block text
      
    `);

    // assert.equal(this.element.textContent.trim(), 'what is this');
  });
});

components/update-pw.js

import Component from '@ember/component';

export default Component.extend({
  changingPassword: false,

  actions: {
    savePW() {
      let self = this;
      if (!self.get('currentUpdateAdmin.email'))
        return;

      let newPw = self.get('password');
      let email = self.get('currentUpdateAdmin.email');
      self.set('changingPassword', true);

      if (!email)
        return;

      self.store.updateSingleUserPw(email, newPw)
        .then(function() {
          // Reset controller fields
          self.set('password', '');
          self.set('updateModal', false);
          swal({
            title: 'Das hat geklappt',
            type: 'success'
          });
        }, function() {
          self.set('updateModal', false);
          swal({
            title: 'problems with setting new pw',
            type: 'error'
          });
        })
        .finally(function() {
          self.set('changingPassword', false);
        });

    }
  }
});


function in Service/store.js

updateSingleUserPw(email, newPw) {
    let headers = this.get('headers');

    return new Promise(function(resolve, reject) {
      $.ajax({
        type: 'POST',
        url: ENV.api + '/accounts/updateSingleUserPw',
        data: {
          email: email,
          pwNew: newPw
        },
        headers,
        dataType: 'json'
      }).then(function(success) {
        if (success) {
          resolve(newPw);
        } else {
          reject('password change failed');
        }
      }, function(xhr, status, error) {
        reject(error);
      });
    });
  }

Before trying to override function I got only rejected promise modal but after the try of overriding the function i'm getting: Promise rejected during "it renders": Cannot read property 'register' of undefined.




mercredi 7 août 2019

Best way to utilize a serializer in Ember.js to support a different payload key?

When running the following line of code:

this.get('store').query('domain-message', 
{
    domainId: user.defaultDomain.id
});

>>/api/domain-messages?domainId=1

this error is returned:

The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use store.queryRecord to query for a single record. Error: Assertion Failed: The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use store.queryRecord to query for a single record.

I have a model in app/pods/domain-message/model.js that looks like so:

import DS from 'ember-data';
import attr from 'ember-data/attr';

export default DS.Model.extend({
    campaignId: attr('number'),
    orgId: attr('number'),
    orgName: attr('string'),
    userId: attr('number'),
    memberId: attr('number'),
    messageSubject: attr('string'),
    messageBody: attr('string'),
    attachmentLink: attr('string'),
    //sentTimestamp: attr('date'),
    //receivedTimestamp: attr('date'),
    //archivedTimestamp: attr('date'),
    messageSeen: attr('boolean'),
    messageRead: attr('boolean'),
    parentMessageId: attr('number'),
    actionCount: attr('number'),
    completedActionCount: attr('number'),
    //actionStatusUpdatedTimestamp: attr('date'),
});

When inspecting the network for this query, the payload data is as follows:

{"messages":[{"id":1,"campaignId":1,"orgId":1,"orgName":"TestOrg","userId":120,"memberId":"12345","messageSubject":"Test Message","messageBody":"test test test","attachmentLink":"https://google.com","sentTimestamp":null,"receivedTimestamp":"2019-08-07T17:01:39Z","archivedTimestamp":null,"messageSeen":false,"messageRead":false,"parentMessageId":0,"actionCount":0,"completedActionCount":0,"actionStatusUpdatedTimestamp":"2019-08-07T17:01:39Z"},{"id":2,"campaignId":1,"orgId":1,"orgName":"TestOrg2","userId":120,"memberId":"12349","messageSubject":"Hello","messageBody":"How are you?","attachmentLink":"https://google.com","sentTimestamp":null,"receivedTimestamp":"2019-08-07T17:07:39Z","archivedTimestamp":null,"messageSeen":false,"messageRead":false,"parentMessageId":0,"actionCount":0,"completedActionCount":0,"actionStatusUpdatedTimestamp":"2019-08-07T17:07:39Z"}],"meta":{"count":2,"total":2,"offset":null,"limit":null}}

Notice how the payloadKey is "members", this may be causing the issue since it may have to be the same as the models name. Is there anyway to modify this payloadKey and change it so that the model above supports it?

I am not using a serializer, but I do know that it may be required to do so to make this work. Can anyone suggest the best route to suppress this error? When generating a serializer, it will be located in app/pods/domain-message/serializer.js.

Thanks in advanced.




if id is invalid, go to another ember route

I have an ember project, the main concep is there is a list of books on the route /books, but you can pass in a book id in /books/1 and it would view that book only. Here is the router i made...

Router.map(function()
{
    this.route('books', {path: '/'});
    this.route('books', {path: '/*path'});
    this.route('books', {path: 'books/:book_id'});
});

So my default path will always be /books except if the user passes in an id

On my books route, I have the following functions

setupController(controller, model)
{
    this._super(controller);
    controller.loadBook(model.book_id);
},

model(params)
{
    return params;
}

So the model function returns the id and the setupController function will run on init and call the loadBook function in the controller passing in the id

In my controller I have my loadBook function

routerService: service('router'),

loadBook(book)
{
    const validBook = (book === 1);
    if (!validBook)
    {
        console.log('transitioning');
        this.get('routerService').transitionTo('books');
    }
}

So this works, if I go to /books/1, Its a valid book. But if I go to books/2, It will go in that function and transition to /books but the url is still books/2.

Is there any way to actually transition to /books so the url says that, thanks




Unexpected token error when migrating to native classes for components

I upgraded to Ember 3.11 and I want to start using native classes for my components. When I change a component class to something similar like:

    export default class MyClassName extends BaseComponent {

        myFieldName;

I get a build error "Parsing error: Unexpected token ;" because of the class field.

Ideas how to make sure ember-cli doesn't complain about the new syntax are more than welcome.

Thanks




mardi 6 août 2019

Disabled on buttons does not seem to take effect

I just started learning ember today. (Trying to do yoember.com) tutorial. Please excuse my newbie questions.

I'm experiencing some issues and I am not sure what I am doing wrong.

Issue:

  • Disabled does not work (it always enables the button)

What I am doing:

  • I have a contact page which has email, message and submit button.
  • I want to disable the button initially (When there is no email, message)

This is what I've done so far:

contact.hbs:

<h1>Contact Page</h1>
<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="text">Text</label>
    <textarea type="textarea" class="form-control" id="text" placeholder="Text" rows="4" cols="50" value=></textarea>
  </div>
  <button disabled=  type="submit" class="btn btn-primary">Submit</button>
</form>

Contact.js

import Route from '@ember/routing/route';
import { match, not } from '@ember/object/computed';

export default Route.extend({
    emailAddress: '',
    message: '',
    isValid: match('emailAddress', /^.+@.+\..+$/),
    isDisabled: not('isValid'),

    actions: {
        submitButton () {
            alert(`Saving of the following email address is in progress:`);
        }
      }
});

Questions:

1) What am I doing wrong? Why is the button always enabled?

2) What is the difference when I do value=emailAddress vs value=




Is it possible to run ember fastboot only for search crowlers

Ember fastboot works fine. But is it possible to have both static files for browser-clients and fastboot server for search engines crawlers?




Adding Ember.js frontend app to Node.js backend app

I have a running ember.js frontend app. Also have a node.js backend app which can do basic CRUD operations from MongoDB. Using Postman I can see that my node.js app is returning JSON data properly.

I want my frontend to use the backend to do CRUD operations on MongoDB. I am new to ember.js so I want a guideline where I can understand to use the JSON data from the node.js app and use with ember.js frontend.

My ember.js app already is using a mock server. It has a "dist" folder inside.

My adapter/application.js file in ember.js frontend:

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  namespace: 'api' 
});

I want to use my localhost:3000 node server here. Do not know where to add it.




lundi 5 août 2019

My Application is not responding to the request given by front end and throwing a CORS exception

I have created a web service using dropwizard application.

  1. Through this I am able to create resources package wherein I have created entity for indexing the document, search request, getting doc by id.

  2. By hitting the api in postman I get the desired result.

  3. For developing the web application I built the front end using ember.js.

  4. But when I send request to my application I am getting CORS policy exception.

    • When I am sending request through postman to http://localhost:9090 (9090 is the port number of my ApplicationConnector) then it is respnding to the request.
    • Now when I send request from origin http://localhost:4200 (4200is the default port number for ember.js) to http://localhost:9090 it is giving error :

Access to XMLHttpRequest at http://localhost:9090/{indexName}/{id} >from origin http://localhost:4200 has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
No 'Access->Control-Allow-Origin' header is present on the requested resource.

So can someone please explain how to resolve this issue and if there is any other way apart from enabling CORS in Dropwizard ?




From the Tabulator focus is not moving to the table footer editable fields

  1. I am using tabulator api to display table data.
  2. I am using "tab" key to navigate on the cells.
  3. When it is last row and last cell, focus should move to the table footer which is having paging selectable field(attached the screenshot.)

enter image description here

  1. To know the which is the last row and last cell I am getting selected rowid.
  2. To know which is the last cell on the last row getting the cell value form cellEdited fucntion.

Code to execute on the tab function:

if(e.keyCode === 9){
                console.log("tabbing function called");                
                    var selectedRows = [];                
                    var selectedRowId = 0;
                    selectedRows = self.get('table').getSelectedRows();
                    if (selectedRows.length > 0) {
                        selectedRowId = selectedRows[0]._row.data.id;
                    }                    
                    if (self.get("rowIdMax") === selectedRowId && self.get("activeCell") === self.get('table').getColumns()[3].getField()) {                    
                        var pageSizeElement = document.getElementsByClassName("tabulator-page-size")[0];
                        pageSizeElement.focus();
                    }

When I click on the tab key from the last and last cell(image : 2222), the cursor should move to the "Page Size" editable field.

Thank you in advance.




I need recomendations about emberjs nature

I'm working with emberjs during some time and now I want to redefine my understanding of ember's nature.

Question 1. Am I right that the route's model() hook is the best place to write asynchronous code (to get all needed data)? Should I try to place all my network requests (or at least most of them) inside routes' models?

Question 2. The component hooks have synchronous nature. Does that mean it's a bad desition to write async code inside hooks?

Say, I have async init() hook where some data is calculated and didRender() hook where I expect to use that data. When ember calls init() it returns Promise, so it's moved from a stack to a special queue and ember doesn't wait until event loop returns that code back to a stack. So ember runs next hooks, and when didRender() is being executed the init() hook may not be fulfilled and the expected data may not exist. Is it right?

Question 3. Services hooks should also be synchronous. Because when a service is injected inside a component and is used ember also doesn't wait until the async hook is fulfilled.

Say, I have a shopping cart service with products property. The products ids are stored in localstorage and I want to get those products from a server to set them into products property.

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

export default Service.extend({
    store: service(),

    init(...args) {
        this._super(args);
        this.set('products', A());
    },

    async loadProducts() {
        const cartProducts = A();
        const savedCartProducts = localStorage.getItem('cartProducts');
        if (savedCartProducts) {
            const parsedSavedCartProducts = JSON.parse(savedCartProducts);
            const ids = Object.keys(parsedSavedCartProducts);
            if (ids.length > 0) {
                const products = await this.store.query('product', {id: Object.keys(parsedSavedCartProducts)});
                products.forEach(p => {
                    p.set('cartQuantity', Number(parsedSavedCartProducts[p.id].qty));
                    cartProducts.pushObject(p);
                });
            }
        }
        this.products.pushObjects(cartProducts);
    },
  ...
});


If I call loadProducts() from service's init() I can't use this.cart.products in controllers/application.js, for example. Because service is ready, but async init() is still executed. So, should I call it in routes/application.js model() hook?

Question 4. If there is some general component that doesn't refer to any route, but this component needs some data from a server. Where should I make async requests? Or computed properties and observers are the only solutions?

Thanks a lot.




dimanche 4 août 2019

Texts in handlebar file not updating after change

I'm creating a CRUD application using Ember.js as frontend, Node.js as backend and MongoDB as database. I'm new in Emberjs. After changing an HTML tag in my handlebar file, the browser is not showing the changes.

I have edited the "quote.hbs" file. Updated h1 html tag "Quotes!" to "Quotations". Then I have restarted the servers using these commands:

To start the node server:

node server

To start the ember server and bind to node:

ember serve --proxy=http://localhost:8081 --live-reload false

My handlebar template file is given below:


<div class="container">  
    <div class="row">
        <div class="col-md-4">
            <h1>Quotes!</h1>
            
                
                    Book: 
                <br/>
                    Author: <br/><br/>
            

        </div>
        
            
    </div>
</div>

The servers are running without any errors and texts are also being displayed. I expected that the web page will show updated texts in h1 tag. But it is showing the texts before it was updated.




samedi 3 août 2019

Google window.gapi.client.init not resolving nor rejecting promise

I'm trying to set up an Ember project in a Chrome extension. The project works perfectly fine in the browser with my Web Application OAuth 2.0 client ID. However when I use my Chrome App OAuth 2.0 client ID and load my Ember app into Chrome, the window.gapi.client.init call never resolves nor rejects. Neither client.init... then... is logged nor error! is logged (see code). Any ideas why this call would hang in a Chrome extension but be ok in the browser?

My code:

window.gapi.load('client:auth2', () => this.initClient());

which calls:

  initClient() {
    console.log('initClient');
    window.gapi.client.init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      discoveryDocs: DISCOVERY_DOCS,
      scope: SCOPES
    }).then(() => {
      console.log('client.init... then...')
      // Listen for sign-in state changes.
      window.gapi.auth2.getAuthInstance().isSignedIn.listen((isSignedIn) => this.updateSigninStatus(isSignedIn));

      // Handle the initial sign-in state.
      this.updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      this.authorizeButton.onclick = this.handleAuthClick;
      this.signoutButton.onclick = this.handleSignoutClick;
    }, (error) => {
      // debugger
      console.log('error!');
      console.log(error);
      this.appendPre(JSON.stringify(error, null, 2));
    });

My manifest.json:

  "description": "Build an Ember Chrome Extension!",
  "permissions": ["identity", "storage", "activeTab", "geolocation"],
  "oauth2": {
    "client_id": "my-chrome-app-client-id.apps.googleusercontent.com",
    "scopes": [
      "https://www.googleapis.com/auth/calendar.readonly",
      "https://www.googleapis.com/auth/calendar.events.readonly"
    ]
  }
  ...

Only initClient is logged to the dev console, nothing else. I tried looking at this but it didn't help.




vendredi 2 août 2019

Ember.js: How can I test Express server mock?

I have a simple express server running in my Ember app for development purpose. I created it with the command ember g http-mock.

So in my app I have this directory:

my-app
  server
    mocks
      posts.js

How can I make a unit test that runs posts.js mock?.




How to access validation on model that belongs to current model?

I have Models as follows: "recommendedProduct" belongsTo "recommendation" belongsTo "recommendedAdjustment" belongsTo "report". I am trying to access the validation on recommendedProduct in report template with ember-cp-validations but I'm not getting anything on screen?

Tried all sorts of variations of: model.recommendedAdjustment.recommendation.recommendedProduct.recommendedProductSuppliers No one is helping on Discord. Docs don't have enough information to solve the issue

  
   <div class="col-sm-4">Sole supplier required</div>
    
  
  
   <div class="col-sm-4">Sole supplier not required</div>
    
  

I expect one div to show depending on if the recommendedProductSuppliers validation in the recommendedProduct Model is valid or not.




Ember.js moment.js update or use alternative?

We have been using moment for the past few year in our software via ember-moment. After some time with production version frozen we are now updating. First step was to move up to 2.16 when we got the perception that we should not use shim any more, and so we don't know how to do regarding the moment dependency.