dimanche 30 septembre 2018

How to update variables that are inside a helper body in an Ember template

Imagine a property myNumber in a controller that has a different random number every second. With this template you will see this change every second:

<h4>Random number</h4>
<p></p>

However, when the number is only referenced inside a helper (e.g. #if or #each, the number is not updated anymore. This will only show the initial value:

<h4>Random number</h4>

    <p></p>


Interestingly, when you add the reference to the property back to the root of the document, the previously static numbers will now also update:

<h4>Random number</h4>
 -- Without this reference, references below won't update.

    <p></p>


How can I have myNumber inside the helpers update, without showing the number in the root of my template?

I've tried adding the reference in html comments, but that doesn't work. I assume Ember doesn't draw elements that are not in the DOM:

<h4>Random number</h4>
<!--  -->

    <p></p>


What does work is adding the value to the DOM, but hiding it. However, this is an ugly solution:

<h4>Random number</h4>
<span style="display:none">
    
</span>

    <p></p>





Toggling between true and false

import Component from '@ember/component';

export default Component.extend({
  hello: true ,

  actions:{
      switch: function(hello){
        if(hello = false){
        this.set('hello', true);
      }else {
        if(hello = true){
          this.set('hello', false);
        }  
      }

I'm trying to toggle between the false and true options however this always returns false. I need it so that it switches between the two depending on the its current value.

    }
  }
});




samedi 29 septembre 2018

I would like each route in Emberjs to have its own page, when i have multiple routes they all show the content in the same page

I have a quick question Here, I am new to Ember and it looks really exciting, I would like to have multiple routes in my web application, but when I click on a route it redirects the outlet to ONLY this NEW page "route", I don’t want the old page + content of the new page..

Any Ideas how to do that?

Thanks

Omar Mostafa




Ember API missing template helper functions

I'm a new to Ember and maybe i'm missing something, but since version 3.1 (https://emberjs.com/api/ember/3.1/classes/Ember.Templates.helpers) i can't find documentation for helpers yield and with and some others (3.4: https://emberjs.com/api/ember/3.4/classes/Ember.Templates.helpers). I read a changelog and could't finde any changes.




vendredi 28 septembre 2018

API call as json in Emberjs

I need to make a email search API endpoint and make reports with the data.

Example: the user search for an email and if that email is in the JSON file it will display the name city and others of the person with that email.

The Json data is coming from a API call.

I am very new in Emberjs, thank you for the help




Ember-body-class initializer leaking memory

I found a memory leak in ember-body-class but don't know how to fix it best. The memory leak is in the ember-body-class initializer, namely in body-class.js line(42) and (58).

export function initialize(instance) {
  ...
  Route.reopen({

    ...

    addClasses: on('activate', function() {
  --> const document = instance.lookup('service:-document');
      const body = document.body;
      ['bodyClasses', 'classNames'].forEach((classes) => {
        this.get(classes).forEach(function(klass) {
          addClass(body, klass);
        });
      });

      ...
    }),

    removeClasses: on('deactivate', function() {
  --->const document = instance.lookup('service:-document');
      const body = document.body;

      ['bodyClasses', 'classNames'].forEach((classes) => {
        this.get(classes).forEach(function(klass) {
          removeClass(body, klass)
        });
      });

      ...

    }),
  });
}

The Problem is, please correct me if I'm wrong, that these lines are referencing the instance in the callback, so that there is a reference from the Route prototype to the instance, which in consequence retains the container. Finally, our unit tests run out of memory.

I already opened an issue at github too. Here's the link (https://github.com/crixx/bodyclassplayground) to my reproduction-repo. Steps to reproduce and trace the error are also in the repo-readme...

Anyone an idea how to fix this? Any help highly appreciated!




EmberJS: do web crawlers wait while I set my canonical link asynchronously?

I am working on an EmberJS application, and I want add a canonical link to the <head> tags,

<link rel="canonical" href="https://www.my-domain.com"/>

When the didTransition method of the Ember.Router runs, surprisingly - at least for me - the window.location.pathname is still that of the departure page, not that of the arrival page. Therefore, the only way I found to populate the canonical link is by using Ember.run.next, which - if I understand correctly - is just a wrapper of setTimeout(, 0).

didTransition: function () {
  this._super(...arguments);

  run.next(() => {
    $('link[rel=canonical]').attr('href', 'https://www.my-domain.com' + window.location.pathname);
  });

  return true;
},

As my main purpose is SEO, I was wondering how web crawlers treat 0-delay setTimeout, and whether or not I am defeating the whole purpose of my task by using setTimeout. Can anyone help?




mercredi 26 septembre 2018

Ember.js - classNameBindings is removing classes added from outside

When Ember recomputes the classes for a component through the classNameBindings attribute, it overwrittes any class added from outside, for example added by jQuery directly to the element.

Refactoring to get the classes added the "Ember way" through the classNameBindings is not an option, since I'm using an external jQuery plugin that adds them, perfect-scrollbar.

I suppose the problem happens because Ember doen't know about the classes added and just ignores them.

Is there a way/workaround for this kind of scenarios?


I put up a twiddle with a minimal working example of the problem here (if there is a way to get a working ember example using the code snippets, let me know and I edit)

One button toggles a class that changes the background color through de classNameBindings attribute, the other button uses jQuery to toggle a class that adds a green border. If the class through jQuery is added and then the ember button is pressed, the jQuery class is lost.




Action after file selected

I'm working in ember (and js in general) for pretty much the first time.

Here's the scenario: there is a "choose file" button. The standard file selection button has been hidden and replaced with a custom button. A user clicks the button, a file selection window appears, the user selects their file, and clicks 'ok'. Because the default button has been hidden, I need to indicate to the user that a file has been selected. I want to display a message indicating this.

In template.hbs I have something like

<button class="outline-only inline-block" id="my_file_button" >
    Choose file
</button>
<input type="file" id="my_file" name="my_file"> <!-- this is set to display: none in css file -->

   File selected


in component.js I've defined as part of actions:

clickButton(button) {
  let self = this;
  jquery('#'+button).click();
  self.set(button+'_button_clicked', true);
}

What this does is cause the "file selected" message to be displayed as soon as the user clicks the "choose file" button, whether they complete the file selection or click 'cancel'. How can I make it so the message does not display until a completed, successful selection has been made?




Ember.js use triggerKeyEvent for default browser behaviour

Is it possible to use the triggerKeyEvent test helper to initiate default browser behaviour?

So far I can only get it to initiate Ember actions linked to the key event, for example if I have a keyup action defined on .my-input.

I've tried with keyup, keydown and keypress.

One example would be trying to tab from one input to the next:

await focus(document.querySelector('.my-input'));
await triggerKeyEvent(document.querySelector('.my-input'), "keyup", 'Tab');

Another would be to check or uncheck a focussed checkbox with the spacebar key:

await focus(document.querySelector('.my-checkbox'));
await triggerKeyEvent(document.querySelector('.my-checkbox'), "keypress", 'Space');



Ember - nested recursive modules

I am working on an click and drop feature --- where on the page the module is used in a recursive way so it has a parent and children.

I have hit an issue where if the user started to select the children - and then selects the parent - I want to deselect the children. Although I am unsure how to store or monitor a change in the parent/child items selected to make global deselection.

So the user has selected the child of bacon3.. if they select the parent - it would need to deselect the children -- but I feel I am currently locked in the scope of the module

enter image description here




mardi 25 septembre 2018

Ember Firebase Authentication

I've successfully connected my app to Firebase and am authorizing users while also adding additional user information to a user-profile model. There's a few things I'd like to do with this data.

First of all, upon signup (username, password), I'm asking the user for some additional information (name, avatar, city, etc). How can I use this data alongside the authed user (i.e. Welcome :name site wide)? Additionally, I'd like this user to only see their own profile and be able to edit their own profile. A bit stumped currently and just looking for next steps...

Thanks!




How to toggle Ember feature flags from the devtools console

I'm using the ember-feature-flags addon to provide some way to toggle new UI features in my ember application.

The docs say that you can toggle these features at runtime:

this.get('features').enable('newHomepage');
this.get('features').disable('newHomepage');

However, this does not work at "runtime" in the devtools console because the this context will refer to the Window object. I do NOT want to rely on the Ember Inspector and the answer to [this existing question] does not work for me: How to access a known Ember component from console (either because the Ember version I'm on does not expose that information or this is a features service, not a component).

I want to be able to do this in native JavaScript, running in the devtools, that can be ported to a simple bookmarklet to give to other folks to toggle the feature flag on and off on their machines.

Ultimately, I think I'm trying to get the Ember application's instance in order to do something similar to what is possible with the Inspector, but instead of doing $E.get('features')..., I would need to do EmberAppInstance.get('features').... I don't know how to get that app instance, though.




ReferenceError: Can't find variable: authenticator Ember js Error

I got an error ReferenceError: Can't find variable: authenticator Ember error in browser console and authenticator is not defined in terminal with this code

import Controller from '@ember/controller';
import { inject } from '@ember/service';
export default Controller.extend({
  session: inject('session'),
   actions: {   
     authenticate: function(){
       var credentials = this.getProperties('username','password');
       authenticator = 'authenticator:jwt';
       this.get('session').authenticate(authenticator,credentials).catch((reason) => {
            this.set('errorMessage', reason.error || reason);
       });
     }
}
});




upload multiple files using ember-file-upload

to upload file in ember js we are using ember-file-upload


in the documentation I can see they have options to select multiple files, it creates a queue and upload photo one by one. so suppose there are 3 files in a queue it sends 3 request. What I am trying to achieve is send multiple files in a single request only.




lundi 24 septembre 2018

Ember Difference between Restadapter vs Jsonapiadapter

Ember uses Restadapter & Jsonapiadapter for the adapters. What are the exact differences between the 2 in terms of data formats for request/response ? Any other things we need to ensure when using any of these 2.




Ember - if lastItem in each

I am trying to show a piece of markup under the very last item in an each in ember -- I tried something like @last - but it came back with an error

<ul>
  
    <li>Hello, ! You're number  in line</li>
  
</ul>




using Visual Studio Code and Visual Studio Community interchangeable for .NET CORE Web API

Please note that I am new to front-end and back-end Web API development.

I am not sure if this is possible, and I suspect it is not, but I am wondering if anyone knows whether or not it is possible to modify a .NET CORE Web API with both Visual Studio Code and Visual Studio Community? I suspect it is not because VS Community creates the project with a solution files whereas VS Code does not.

The reason for doing this is that I like the CLI nature of Visual Studio Code to create .NET CORE Web API's that can be developed in tandem with a EmberJS front-end framework. However, I much prefer Visual Studio Community's debugger and intellisense for more advanced development of the back-end. This is purely a preference and not necessarily a show stopper.




Customizing search box in ember powerselect

I want to add a search icon inside the Ember power-select input tab. I don't see any method so far to customize it. How do i do this?




Ember Fastboot / Ignore NPM Module

I first want to point out I'm crossposting from here:https://github.com/ember-fastboot/ember-cli-fastboot/issues/621 So far the issue hasn't gained any traction to opening to wider community.

I'm trying to make ember-cli-slick fastboot compliant. It uses slick.js from node_modules like so:

included: function(app) {
this._super.included(app);

app.import("node_modules/slick-carousel/slick/slick.js");

I'm attempting to get the treeforvendor working but not having much luck. I'm following the documentation here https://www.ember-fastboot.com/docs/addon-author-guide#third-party-dependencies but I suspect it's targetting bower rather than npm/node_modules.

treeForVendor(defaultTree) {        
    var browserVendorLib = new Funnel('node_modules/slick-carousel/slick/slick.js');    

    browserVendorLib = map(browserVendorLib, (content) => `if (typeof FastBoot === 'undefined') { ${content} }`);

    return new mergeTrees([defaultTree, browserVendorLib]);
  },

This results in the error:

Build Error (broccoli-persistent-filter:Mapper)

ENOTDIR: not a directory, scandir 'projectdir/tmp/broccoli_persistent_filtermapper-input_base_path-FOInixjr.tmp/'

I've also tried

  treeForVendor(defaultTree) {        
    var map = require("broccoli-stew").map;
    var Funnel = require("broccoli-funnel");
    const mergeTrees = require('broccoli-merge-trees');

    let tree=new Funnel('node_modules/slick-carousel/slick/', {
      destDir: 'slick-carousel',
      files: ['slick.js']
    })

    tree = map(tree, (content) => `if (typeof FastBoot === 'undefined') { ${content} }`);


    return new mergeTrees([defaultTree, tree]);
  },

This at least builds.. but then I get back to the Fastboot error

ReferenceError: jQuery is not defined at projectfolder/tmp/broccoli_merge_trees-output_path-8cGO0zCl.tmp/assets/node_modules/slick-carousel/slick/slick.js:25:1

I've created a clean and otherwise empty Ember addon project with just the import and treeforvendor functions to demonstrate the issue https://github.com/MrChriZ/ember-slicker




dimanche 23 septembre 2018

Unexpected token when using ES6 classes in Ember

I am trying to experiment with ember decorators, but can't even get to compile with fields on classes. Classes without fields are fine, but I get this error whenever there is a field:

Build Error (broccoli-persistent-filter:Babel > [Babel: l3utils])
l3utils/utils/misc-utils.js: Unexpected token (70:9)

  68 | 
  69 | class TestField extends EmberObject{
> 70 |   isField=true;
     |          ^
  71 |   qKey=null;
  72 |   _value=null;

If I just comment that out, then I get the same error on the @computed so it just doesn't seem like babel? eslint? is configured to parse the syntax at all. There's a lot of cruft in this project, but I would really like to get it going.

Does anyone have any idea as to where to look for versions or configs that may be wrong? I'm using Ember 3.3. Here are some maybe relevant versions from the package.json:

"devDependencies": {
    "@ember-decorators/babel-transforms": "^2.1.1",
    "babel-eslint": "^8.2.6",
    "broccoli-asset-rev": "^2.7.0",
    "ember-ajax": "^3.0.0",
    "ember-cli": "~3.3.0",
    "ember-cli-babel": "^6.17.2",
    "ember-cli-dependency-checker": "^2.0.0",
    "ember-cli-eslint": "^4.2.1",

I really don't understand what is going on int .eslint.js file. I try not to fool with these things too much in an effort to keep it as vanilla as possible, but it looks odd:

module.exports = {
 root: true,
 parser: 'babel-eslint',
 parserOptions: {
  ecmaVersion: 6,
  sourceType: 'module'
 },
 plugins: [
 'ember'
 ],
 extends: [
  'eslint:recommended',
  'plugin:ember/recommended'
 ],
 env: {
  browser: true
 },
 rules: {
 }, ... and so on

I've tried changing that ecmaVersion to different settings and it doesn't seem to do anything - even if I change it to a nonsensical value. I kind of don't even know where to look since it doesn't produce any configuration errors - just that syntax error.




Ember github repositories

I am currently learning ember framework. So far I have learned some core concepts and I managed to develop some basic ember applications. But I would like to explore open source ember applications for even more understanding. Can you point out some repositories?




samedi 22 septembre 2018

AJAX Issues with 304

I have an AJAX call (try to disregard all of the serialization, that part works 100%) that's throwing a 304. How would I set this up so my data (flightResults) doesn't get overwritten by the empty 304 response body? Code below...apologies for the long snippet, just want to get it all in there..Thanks!

        var app = {};
        app.init = function(){
          app.flightsGeo();
        };
        app.flightsGeo = function(){
          var location = resp.headers.get('Location');
          var sessionKey = location.substring(location.lastIndexOf("/") + 1);
          let updatedURL = `https://skyscanner-skyscanner-flight-search-v1.p.mashape.com/apiservices/pricing/uk2/v1.0/${sessionKey}?sortType=price&sortOrder=asc&pageIndex=0&pageSize=5`
          $.ajax({
            type: "GET",
            url: updatedURL,
            dataType: 'json',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'X-Mashape-Key': 'yOLGSU9nWcmshQAjA5nsXiBvEooWp1v2Q9Jjsncjrhz58ajvZM',
              'X-Mashape-Host': 'skyscanner-skyscanner-flight-search-v1.p.mashape.com',
            },
            success: function(response){

            },
            error: function(error){
              self.set('loading', false);
              self.set('searchError', true);
            }
          }).done(function(response){
            var itineraries = response.Itineraries;
            var agents      = response.Agents;
            var legs        = response.Legs;
            var carriers    = response.Carriers;
            var places      = response.Places;
            $.each(itineraries, function(itineraryKey, itineraryVal){
                var inbound          = app.getObjects( legs, 'Id', itineraryVal.InboundLegId),
                    inDepartureTime = inbound[0].Departure,
                    inArrivalTime   = inbound[0].Arrival,
                    inDepartureDate = inbound[0].Departure,
                    inArrivalDate   = inbound[0].Arrival,
                    inOrigin        = app.getObjects( places, 'Id', inbound[0].DestinationStation),
                    inDestination   = app.getObjects( places, 'Id', inbound[0].OriginStation),
                    inCarriers      = app.getObjects( carriers, 'Id', inbound[0].OperatingCarriers[0]);
                var outbound         = app.getObjects( legs, 'Id', itineraryVal.OutboundLegId),
                    outDepartureTime = outbound[0].Departure,
                    outArrivalTime   = outbound[0].Arrival,
                    outDepartureDate = outbound[0].Departure,
                    outArrivalDate   = outbound[0].Arrival,
                    outOrigin        = app.getObjects( places, 'Id', outbound[0].DestinationStation),
                    outDestination   = app.getObjects( places, 'Id', outbound[0].OriginStation),
                    outCarriers      = app.getObjects( carriers, 'Id', outbound[0].OperatingCarriers[0]);
                var agent     = app.getObjects( agents, 'Id', itineraryVal.PricingOptions[0].Agents[0]);
                var price     = itineraryVal.PricingOptions[0].Price.toFixed(2);
                var permalink = itineraryVal.PricingOptions[0].DeeplinkUrl;
                var time      = itineraryVal.PricingOptions[0].QuoteAgeInMinutes;
                var data = {
                    agent: agent,
                    price: price,
                    time : time,
                    permalink: permalink,
                    inbound: {
                      time: {
                        departure: inDepartureTime,
                        arrival: inArrivalTime
                      },
                      date: {
                        departure: inDepartureDate,
                        arrival: inArrivalDate
                      },
                      station: {
                        origin: inOrigin,
                        destination: inDestination
                      },
                      carriers: inCarriers
                    },
                    outbound: {
                      time: {
                        departure: outDepartureTime,
                        arrival: outArrivalTime
                      },
                      date: {
                        departure: outDepartureDate,
                        arrival: outArrivalDate
                      },
                      station: {
                        origin: outOrigin,
                        destination: outDestination
                      },
                      carriers: outCarriers
                    }
                };
                results.push(data);
            });
            self.set('flightResults', results);
            self.set('loading', false);
            self.set('complete', true);
          }).fail(function(){
              alert("Something went wrong");
          });
      };
      app.getObjects = function(obj, key, val) {
          var objects = [];
          for (var i in obj) {
            if (!obj.hasOwnProperty(i)) continue;
            if (typeof obj[i] == 'object') {
              objects = objects.concat(app.getObjects(obj[i], key, val));
            } else
            if (i == key && obj[i] == val || i == key && val == '') { //
              objects.push(obj);
            } else if (obj[i] == val && key == ''){
              if (objects.lastIndexOf(obj) == -1){
                objects.push(obj);
              }
            }
          }
        return objects;
      };
      var results = [];
      $(document).ready(app.init);
      return app;




Ember.js - Whats the proper way to handle property translations?

I have a model with a gender property, which can be "female" or "male".

What's the best way to handle the translation of that property?

I thought of some ways to tackle this, but not sure if I'm overthinkering this or solving it poorly.

1) Make a helper or tagless component that receives the value, has the translations service injected and translates it. With an aditional flag to capitalize or lower case the output.

2) Just use t helper and concat for the translation key, eg: . This is very straight forward and I will be copy-pasting this everywhere, looks messy.

3) Computed property in the model. I feel like injecting the translations service in my models is wrong (just my impression, if this is the proper way I'm good with it)

4) Computed property in the component that has to show the gender. This is like option 2 but in the component instead of the template, will be copy-pasting this a lot.




Ember js Mocha Testing

enter image description here

I have my div like this in the integration test I need to check that how many elements or length is there with class = "highcharts-grid-line" . or how many children are there with that class in ember mocha test for the div with data-test-id = "bar-chart-body".Please help to to find syntax.

It must be like expect($(.....).to.be.length(x);




vendredi 21 septembre 2018

How to get module option from test command in environment config

When running tests using a command such as ember test --module="Acceptance | example", how could I capture the module option within the environment.js config file?

I'd like to do this so that I can validate the option in the config, then pass a flag into the application instance for testing.




Ember Qunit acceptance test cases failing for application home page

1) I'm using acceptance test cases using Qunit for my home or Landing page.
2) I used all my home page logic in application.js route.
3) I created application-test file. Below are code.

import { test } from 'qunit';
import moduleForAcceptance from 'landingui/tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | application');

test('visiting /', function (assert) {
    visit('/');

    andThen(function () {
        assert.equal(currentURL(), '/');
    });
});

4) When I run my test cases its failing. Below are error which occurred.

Acceptance | application: visiting / (1, 1, 2)Rerun1668 ms
okay@ 1018 ms
Promise rejected after "visiting /": Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.@ 1649 ms
Source:     
Error: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
    at clear (http://localhost:8080/assets/vendor.js:26486:20)
    at RenderResult.destroy (http://localhost:8080/assets/vendor.js:31483:13)
    at RootState.destroy (http://localhost:8080/assets/vendor.js:43036:24)
    at InteractiveRenderer._clearAllRoots (http://localhost:8080/assets/vendor.js:43280:22)
    at InteractiveRenderer.destroy (http://localhost:8080/assets/vendor.js:43177:18)
    at destroyDestroyables (http://localhost:8080/assets/vendor.js:34043:15)
    at Container.destroy (http://localhost:8080/assets/vendor.js:33801:7)
    at Backburner._run (http://localhost:8080/assets/vendor.js:33569:35)
    at Backburner.run (http://localhost:8080/assets/vendor.js:33258:25)
    at run (http://localhost:8080/assets/vendor.js:50002:29)

Please help to fix this issue.




Display only positive values in Ember handlebar

Following the answer for question Check for a value equals to in Ember Handlebar If block helper I run

ember generate component greater-than-zero

In components/greater-than-zero.js I have put:

import Ember from 'ember';

export default Ember.Component.extend({
    isGreaterThanZero: function() {
      return this.get('param') > 0;
    }.property('param')
});

and in templates/components/greater-than-zero.hbs:


  


I am trying to use as:


    


The problem is that nothing is displayed. If I leave only in templates/components/greater-than-zero.hbs, then all myvarss are displayed. So I think the handlebar is recognized and the problem is with the isGreaterThanZero function. Here if add console.log(this.get('param')); before the return statement, it prints undefined to the console.

I am new to Ember, so maybe I miss some elementary thing.




Overwhelmed by repeated filenames for routes, controllers. templates, etc in JavaScript

I'm starting to work seriously with Ember, but I think I would have the same problem in other structured frameworks.

When multiple files are opened in my editor, I waste a lot of time figuring out which file I must edit. The same filenames are repeated over and over. For example, I have index.js or edit.js almost in every route, subroute, controller, nested controller, for all the modules!

In my editor, the open files I see are:

 - index.js
 - edit.js
 - index.js
 - edit.js
 - index.js
 - edit.js
 - index.js
 - edit.js

Because the diacritic part of the name is in its path, not shown in the IDE

 - routes/clients/index.js
 - routes/clients/edit.js
 - routes/contacts/index.js
 - routes/contacts/edit.js
 - controllers/clients/index.js
 - controllers/clients/edit.js
 - controllers/contacts/index.js
 - controllers/contacts/edit.js

I usually work with Coda and BBEdit, for Mac. Fortunately, I use Perl for my backend, so the Perl filetype shows a different color and icon in the IDEs. I wonder how node.js developers can live. :-D

I also tried Sublime, Brakets, Atom, etc, Some of them put the open filenames on upper tabs, other put them in the margin, but I have no clue of what is open.

At least, BBEdit puts a mark in the main filetree to show if a file is open.

enter image description here

Maybe I should rename everything like client_controller_index.js, but it is long and complicates reusing things. Ember is very opinionated, the same than CLI automation and even dashes have a meaning.

Currently I am using the naming criteria learned in tutorials. Is it is not a good practice when things grow up?

Any recomendation on filenaming, structures or IDEs?

Thank you in advance.




jeudi 20 septembre 2018

Click events on Ember

I'm discovering EmberJS and started to migrate an existing website to this framework. I was having an issue with a Bootstrap-based dropdown. This issue actually helped me understand Ember's concepts a bit better but I still have some questions.

I used the ember-bootstrap module to generate this dropdown (among other things) and here is what the code is supposed to be:


    Sort by 
    
        Price low to high
        Price high to low
    


Now, I want some javascript code to be executed when the user clicks on one of the items. After checking the module's documentation, I found where the menu item component was defined and edited its code as follows:

export default Component.extend({
    layout,
    classNameBindings: ['containerClass'],
    ....
    actions: {
        // My addition
        sortByPrice(param){
            alert("sorting");
        },
    // End of the addition

    toggleDropdown() {
        if (this.get('isOpen')) {
            this.send('closeDropdown');
        } else {
            this.send('openDropdown');
        }
    },

Then I updated the hbs file as follows:


   Prix croissant


This didn't work, and that's why you I added the *action* to the link-to element as well and declared similarly the action on its component file.

import LinkComponent from '@ember/routing/link-component';
   export default LinkComponent.extend({
   actions: {
      sortByPrice(param){
        alert("sorting");
        console.log("sorting");
      }
   }
});

As you can see, the *link-to* component extends the LinkComponent one. I eventually understood that it wasn't possible for this element to handle click events natively, as explained in this thread.

Out of frustration, I ended up with a less elegant approach that still does the trick:


   Sort by 
   
      <a class="dropdown-item" onclick="sortByPrice('low_to_high'); return false;" href="#">Price low to high</a>
   
 

Now here are my questions:

  1. Why is it that defining actions on both the Component file and the hbs one didn't change the result?
  2. Why doesn't the LinkComponent handle click events natively? I get that a link is supposed to redirect users to a new page (which is still arguable), but the DOM event is still fired, so does Ember deliberately ignore it and choose not to let developers handle it? I want to know the logic behind this.
  3. Is there a better approach than my solution?

Thanks




How to see which component called the handler in ember?

Currently I have two ember input boxes which both call the same onInputChange handler function.




I'm wondering how the onInputChange can determine which component actually called it. (Each one needs to do something specific).

Is there a more "ember" way to do it?




Using Ember Data Model

In an Ember app, is it a good idea to use data models for mapping attributes across different places in the app (in some route/controller/component, etc)

I think we need to use DS.Adapter to use models within Ember (have not tried it much though)

Are there any good practical examples of the same ? Essentially, I need it to map to server-side data models & may be match it to the XHR request payloads/JSON response..




How to globally swallow api error (findAll, query, adapter errors) in Ember js

Is there a way in Ember to globally swallow all api errors throughout the whole application rather than individually catching and reporting them in each component file?




mercredi 19 septembre 2018

Self Referencing JSON Object

I have a JSON object from an API that seems a bit tricky. I need to reference parts of the object with other parts. See below for some more context. I need the InboundLegId to reference the ID in the Legs object. Any ideas here?

enter image description here




How to update an element in Ember

I have a page with data shown in rows. Each row has an element: Stop or Play. This element is driven by the following code in handlebars:


  <a ><span class="glyphicon glyphicon-play" aria-hidden="true"></span></a>

  <a ><span class="glyphicon glyphicon-stop" aria-hidden="true"></span></a>


When user clicks "Stop" or "Play" icon, I would like the logic to make a call to the backend server, update the database, and change the icon to either stop or play. I am not sure how to do this in Ember. At the moment, this is how my toggle method looks like:

App.TestController = Ember.ObjectController.extend({
    toggle: function () {
        return "/my/backendserver/"+this.get('id')+"/toggle";
    }.property()
});

This works, however, it does a full page reload.

Question

How can I modify the toggle method so that it only calls the server (providing id as parameter, and switches the stop icon to play or vice and versa without doing a complete page reload?)




record was saved to the server, but the response does not have an id and your record does not either

I’m facing this error since yesterday, Error: Assertion Failed: 'todo' was saved to the server, but the response does not have an id and your record does not either.

I know it should come from app/serializers/todo.js or my app/routes/application.jsbut after looking into severals forum, I have to ask the question to expert emberJs dev, as i’m a newbie :smiley:

Here’s my app/serializers/todo.js:

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
  serialize: function(record, options) {
    var json = this._super.apply(this, arguments); // Get default serialization

    json.id = record.id;  // tack on the id

    return json;
  }
});

And my app/routes/application.js

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

export default Route.extend({
  model(){
    return this.store.findAll('todo');
  },
    actions: {
      createtodo: function() {

        var titleInput = this.get("newTitle")
        var todo = this.store.createRecord('todo', {
          title: titleInput,
          isCompleted: false
        }); 

        this.set('newTitle', '');
        todo.save();
      }
    }
});

The way the createtodo action is triggered app/templates/application.hbs:


<button >Save</button>

So my objec is created but not save. When i’m looking into my ember Inspector, I see that each object I create have an ID but the title field is null or "".

This is a todoApp with an Rails-API as back and Ember as front.

Anyone see what’s wrong here ?




How can i convert english into spanish language using ember i18n

Using ember js i want to convert english to spanish words bt now i can only convert by custom,how can i avoid that.

locales>es>translation.js

export default {
login: "hello",
};

routs>

i18n: Ember.inject.service(),

beforeModel(){
  this.set('i18n.locale', 'es');
}

template>

  




mardi 18 septembre 2018

EmberJS: How to update Ember CLI based apps

Angular has https://update.angular.io/ that guides with the proper way to update (along with dependencies et al.). Likewise, is there a way to know how to update an Ember app properly?

Obviously, changing the version of the ember package in bower.json and doing an bower install && npm install doesn't seem to be the ideal way.




how do I update ember-cli-babel?

Whenever I try to set up a server with ember on the CLI with

ember serve

and I end up getting the following warning:

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-bootstrap-switch -> ember-cli-babel
DEPRECATION: An addon is trying to access project.nodeModulesPath. This is not a reliable way to discover npm modules. Instead, consider doing: require("resolve").sync(something, { basedir: project.root }). Accessed from:   new NPMDependencyVersionChecker (/home/aihoque2/DIFM/afri-client/node_modules/ember-bootstrap-switch/node_modules/ember-cli-version-checker/src/npm-dependency-version-checker.js:11:33)

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-composability-tools -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-composability-tools -> ember-getowner-polyfill -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-composability-tools -> ember-wormhole -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-d3 -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-django-adapter -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-new-computed -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-paper-expansion-panel -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-paper-selection-dialog -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-paper-stepper -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-paper-tabs -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-simple-auth -> ember-cookies -> ember-getowner-polyfill -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-simple-auth -> ember-getowner-polyfill -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-simple-auth-token -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-suave -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> ember-transition-helper -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: DIFM -> paper-data-table -> ember-cli-babel
DEPRECATION: Addon files were detected in `/home/aihoque2/DIFM/afri-client/node_modules/ember-bootstrap-colorpicker/addon`, but no JavaScript preprocessors were found for `ember-bootstrap-colorpicker`. Please make sure to add a preprocessor (most likely `ember-cli-babel`) to in `dependencies` (NOT `devDependencies`) in `ember-bootstrap-colorpicker`'s `package.json`.
DEPRECATION: ember-cli-test-loader should now be included as an npm module with version 1.1.0 or greater.

Template Compiler Error (broccoli-persistent-filter:TemplateCompiler) in ember-font-awesome/components/fa-icon/template.hbs

compiler[param.type] is not a function

Stack Trace and Error Report: /tmp/error.dump.96eca08e71c1dd2d3941d677ca43981c.log

I have been trying to look for a way to update ember, as I am convinced that my error that I have is potentially because I do not have the latest version of ember.js. I tried ember update but that is not a command. I have also tried to use

ember install ember-cli-babel

and that didn't work either. So main question I have is, How do I update ember-cli-babel?




TodoMVC application - how to create tests for adding 100 items

I am trying to use TodoMVC(i have installed locally the last version on github) for some performance tests on js frameworks(react,angular2,ember,backbone).

I need to measure metrics/elements like : initial loading time for each application,time that each framework need for adding 100 items,for editing 100 items,time for completing all 100 items and time for deleting all 100 items.

What kind of modifications do i have to do for implementing this tests?

I have seen some similar examples on github like here but i think that they are been implementing using an old version of TodoMVC application.

Thanks in advance




Access webhook variables in front end

I'm developing the front-end and back-end of a web application using emberjs, now I have some data in webhooks.js in the back-end that I need to process in the front-end, the front-end javascript file is located in a handlebar(.hbs) under templates folder.

My question is, what's the best way to access a back-end variable in the front-end javascript?

For example, I use router.post to retrieve some data from the Stripe endpoint, then I want to send the data to my front-end, so I can do something to that data in the javascript.




Dynamically rendering ember component

I want a component to be re-rendered with different attributes on chaninging a controller property. So, I have my code like,


   

   


Changing the property diffView, throws me error like,

vendorrepository.js:13602 Uncaught DOMException: Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node. at clear(…) at UpdatableBlockTracker.reset (…) at TryOpcode.handleException (…)

This error was inside ember source code. I think there was some error trying to remove the older component. Pls help me out with this issue.




Caching dynamically-generated images in front-end

I am currently working with the following situation: I have an Ember front-end with N entities, and the user can view dynamically-generated chart images for each of these entities. For this purpose, when the user wants to view the chart for on an entity, the following happens:

  1. the front-end sends a request for generating a chart image to a back-end endpoint
  2. this image is then passed to the front-end in the endpoint's response, as a base64 encoded image
  3. the front-end displays this image
  4. now, the user can select a new entity, etc.

At the moment, the user has to wait for a chart image to be loaded 3-5 seconds, no matter whether this entity's chart has been viewed before. This is quite annoying: wait to view chart for entity A, then wait to view chart for entity B, then wait again if you want to see entity A again, etc.

I want to cache somehow the already viewed images in the front-end, in order to avoid this waiting time. (The content of the images does not change frequently, perhaps once a day or so, so this is not a problem).

Can this be done with Ember, or am I looking at this from a wrong point of view and an entirely different strategy is required?




Dialog box is not fit for the screen on multiple selecting files

I'm having dialog box with the upload files for the folder, when I'm selecting the multiple files (more than 25 files approx) for the upload, the dialog box getting increased the length to the bottom and scroll bar is not showing to scroll down to see the files fully.

Here is the screenshot:

enter image description here

Here I have added 36 files and when I want to see the uploaded file list its not showing fully and scroll bar also showing to scroll down to see the further.

Html for the dialog box is here:

<div class="upload-files-dialog" tabindex="0" role="dialog" style="position: absolute; height: auto; top: 0px; left: 277px; display: block; width: 270px; right: auto; bottom: auto;" aria-describedby="ui-id-3" aria-labelledby="ui-id-4">

Corresponding css style I have tried as:

div.upload-files-dialog {
 {
    position: absolute;
    height: auto;
    top: 0px;
    left: 226px;
    display: block;
    width: 270px;
    right: auto;
    bottom: auto;
 }

I have mentioned height as auto, then also its not getting adjust with the screen.

The corresponding hbr file for the dialog is here:


    


The fileList of corresponding ember code is here:

        menuContext: null,

        formData: function () {
            if (!this.get('menuContext.formData')) {
                this.set('menuContext.formData', Ember.Object.create({ data: Ember.Object.create({ }), files: [] }));
            }
            return this.get('menuContext.formData.data');
        }.property('menuContext'),

        uploadHandle: null,

        showFileList: function () {
            return (this.get('uploadHandle.files.length') || this.get('menuContext.formData.data.file.length')) > 1;
       }.property('uploadHandle.files.length', 'menuContext.formData.data.file'),

        fileList: function () {
            return this.get('uploadHandle.files') || [].slice.call(this.get('menuContext.formData.data.file'));
        }.property('uploadHandle.files', 'menuContext.formData.data.file')

When I'm pressing the console (F12), the scroll bar is getting coming and dialog box is also changed as fit for the page. But I need on when I'm upload the file time itself. I don't know where it is getting the problem either css or ember or jquery. Can anyone please suggest me regarding this.




lundi 17 septembre 2018

npm errors. DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6

I upgraded from ember 2.9.0 to ember 3.4.

I am using npm install.

Now I get these deprecation errors (for some packages which I have as dependancies in package.json):

DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: application -> ember-cli-d3 -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: application -> ember-cli-d3 -> ember-getowner-polyfill -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: application -> ember-disable-proxy-controllers -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: application -> ember-message-bus -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: application -> ember-simple-auth -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: application -> ember-simple-auth -> ember-getowner-polyfill -> ember-cli-babel
DEPRECATION: ember-cli-babel 5.x has been deprecated. Please upgrade to at least ember-cli-babel 6.6. Version 5.2.8 located: application -> ember-simple-auth-token -> ember-cli-babel

If I use yarn, the above errors go away. yarn seems to manage dependancies better and perhaps it isolates the dependancies of dependancies better? Not sure exact reason why.

Could someone explain why it works with yarn and not with npm? Also, how I can make it work with npm?

I need to make it work with npm to go live with it.




how to have ember 3.4 component properties combining 'computed' and 'on()'

We have code in our ember 2.9.0 project which has Components with properties like this:

hide: on("init", computed("hasEnoughData", function () {
    return !this.hasEnoughData;
})),

When I migrate it to ember 3.4, it breaks with this error:

Assertion Failed: on expects function as last argument

Basically, the on() function expects the last param to be a function. This code used to work with 2.9 to combine both computed and on().

Is there a recommended way to do this with ember 3.4?




How to exclude a route and related files while ember build

I have a repo with in-repo 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, for developers. As this route is only for dev purpose I want this route (dev-docs) and related *.css, *.js and *.hbs files to be excluded from /dist.

My requirement is that I don’t want to host dev-docs separately as it becomes complex to maintain if the number of add-ons grow.

Is there any way to do it. I am currently looking into this package. But looking for other ways to implement the same.




Why does my routing doesn't work in Ember Js?

I'm working on a todoApp with a rails API and frontend as Ember. I've followed this tutorial Ember todo App However, it a bit old and I kinda lost in my routing.

I've a todos.hbs which should be rendered localhost:4200/, but it is a clear page.

Here's what my router.jslooks like :

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.resource('todos', { path: '/' });
});

export default Router;

And my routes/todos.js:

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

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

On my application.hbs, there's only an ```

and my todos.hbs looks like this :

<section id="todoapp">
  <header id="header">
    <h1>todos</h1>
  
  </header>

  <section id="main">
  <ul id="todo-list">
  
    <li >
    
      
    
        
        <label ></label>
      <button  class="destroy"></button>
    
    </li>
  
  </ul>

    <input type="checkbox" id="toggle-all">
  </section>
</section>

<footer id="info">
  <p>Double-click to edit a todo</p>
</footer>


So now, I dont know where the mistake is, it only rendered me a blank page. If anyone can explain what is wrong into my work, I would appreciate.




dimanche 16 septembre 2018

How to find an object by ID in an ember template

I have a data structure like this:

let colors = {colorArray: [{id: 1, color: "blue"}, {id: 2, color: "red"}], anotherVariable: "anotherValue"}

I have an each helper like this:


    <div>...</div>


I want to return the object in colors.colorArray that corresponds to the ID of the post I'm iterating over. I'm unsure how to go about this. I tried using an ember-composable-helper, but nothing logs (no errors, either). Here is what I tried:


   
      
   


What am I do wrong? Is there another way I could go about this?




vendredi 14 septembre 2018

EmberJS: Observing JavaScript object's getter in computed properties

I have a JavaScript object with dynamically computed properties (using getter and setters), returned by a third party library and I want to observe them on my Ember computed properties.

If I pass such a property as a dependency in my computed property like below,

someProperty: computed('jsObject.property', function () {
    // Do something
})

Ember makes it undefined. Is this is bug in Ember or am I doing something wrong?




jeudi 13 septembre 2018

Rails, Ember, Redis, nginx and docker

Colleagues, I have a front-end application based on Ember and Rails (running on nginx) which also uses redis as a cache.

I want to dockerize this application, but not sure about best practices. Would it be best to create one container with a dockerfile that pulls in all these pieces, or should each component be in its own container?

For bonus points: I have to retrieve the code from private bitbucket repos and.. how are we meant to store our secrets and other config files when using containers?




Trigger Ember action from javascript console

I don't know much about Ember but I'm trying to manipulate an Ember web app. There's an element in the DOM that has this property "data-ember-action-981="981"" and I'd like to trigger the function linked to it in order to access its output.

Any ideas on how to do it ? Thanks




Simulate tab key press (Ember.js)

Good day!

I have a collection of textfields and they're arranged horizontally, What I want is to imitate Mircosoft excel's behaviour when I press the enter key it would automatically go down to the next row and focus on first input.

One approach I'm looking forward is to simulate tab press when I press the enter key.

For now I'm using this jquery approach:

function save() {
  let focusedElement = Ember.$(event.target);
  let nextForm = 5; //some integer value to get the next ember-id
  Ember.$("#ember"+ nextForm +"").select();
}

I want to make it more Ember way because right now it's anti component pattern.




Unknown Global Errors when upgrading Ember

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);




Store and go back to an Ember route

On an Ember app, I am implementing a Wizard. It is composed of several steps (each step has its own route).

I want to store the route from which the user start the Wizard (with its model and query params if any). At the end of the Wizard, I want to redirect the user to the initial route.

For example:

/myapp/some/route   --> click on a link to start the wizard
/myapp/wizard/step1
/myapp/wizard/step2
/myapp/wizard/step3 --> click to end the wizard
/myapp/some/route   --> the initial page

How can I do that?

In the beforeModel(transition) of the Wizard step 1, I found that:

  • this.get('router.currentRouteName') give me the name of the previous route
  • this.modelFor(previousRoute) give me the model
  • this.paramsFor(previousRoute) give me the params

But, I do not find how to replay the transition backward, or to recreate a transition to go back to the initial route.




mercredi 12 septembre 2018

Ember.js two API's same resource name

Desired outcome: To have two models available; "bc-theme" and "ra-theme" in ember pulled from two different API's that use the resource name "theme".

I have a simple way of serializing the model name for one "rename" but have not found a way to determine the rename based on what API it's requested from and thus be able to rename appropriately. As you can see from the provided code, the mappings will fail if I introduce another "theme" because their will be muliple of the same keys on the mapping for normalization.

Without the extra theme the mappings work as expected.

Is there some way to see what adapter is being used in the serializer? Or since it's being request by an ember findRecord and via relationships could the theme "type" be determined some other way on each request?

The backends are written in Ruby on Rails and can be modified as well, but it seems like ember should be the one to handle the differences since the API's are independent of one another.

// adapters/ra-theme.js
import RaAdapter from './ra';

export default RaAdapter.extend({
  pathForType() {
    return this._super('themes');
  }
});

// adapters/bc-theme.js
import bcAdapter from './bc';

export default bcAdapter.extend({
  pathForType() {
    return this._super('themes');
  }
});


// serializers/application.js
import DS from 'ember-data';

const keysMappingForSerialization = {
  'bc-theme': 'theme',
  ...
};
const keysMappingForNormalization = {
  'theme': 'bc-theme',
  ...
};

export default DS.JSONAPISerializer.extend({
  payloadKeyFromModelName(key) {
    if (keysMappingForSerialization[key]) {
      return this._super(keysMappingForSerialization[key]);
    } else {
      return this._super(...arguments);
    }
  },
  modelNameFromPayloadKey(modelName) {
    if (keysMappingForNormalization[modelName]) {
      return this._super(keysMappingForNormalization[modelName]);
    } else {
      return this._super(...arguments);
    }
  }

});

// serializers/bc-theme-group.js
import ApplicationSerializer from './application';

const keysForRelationshipsMapping = {
  'bcThemes': 'themes'
};

export default ApplicationSerializer.extend({
  keyForRelationship(key) {
    if (keysForRelationshipsMapping[key]) {
      return this._super(keysForRelationshipsMapping[key]);
    } else {
      return this._super(...arguments);
    }
  }
});

// serializers/bc-theme.js
import ApplicationSerializer from './application';

const keysForRelationshipsMapping = {
  'bcThemeGroups': 'themeGroups'
};

export default ApplicationSerializer.extend({
  keyForRelationship(key) {
    if (keysForRelationshipsMapping[key]) {
      return this._super(keysForRelationshipsMapping[key]);
    } else {
      return this._super(...arguments);
    }
  }
});



timeout with google recaptcha

I am seeing a Uncaught (in promise) timeout when running ember qunit tests for a page that includes a google recaptcha. Does anyone have any insight into what would cause this?

I am including the script on the index page like this: <script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>

and I am rendering the element like this: grecaptcha.render(document.getElementById('myid'), { 'sitekey': mySiteKey, 'expired-callback': this.get('expiredCallback').bind(this), 'error-callback': this.get('errorCallback').bind(this) });

I am using the google recaptcha test sitekey.




Ember conditional rendering is adding a weird element in DOM

Whenever a condition is not respected in my template I noticed this green thing in the DOM

enter image description here

Can this behavior be avoided ?




Find the class name of a relation from the instance of a model in ember JS

I have foo an instance of the ember-data model thing. thing.js has the following property :

owner: DS.belongsTo('user')

If I have foo with an empty owner, how can I, with only foo and the 'owner' string, retrieve the value 'user' representing the model of the owner relation?




mardi 11 septembre 2018

Ember can't find my template when using the renderTemplate hook

I can’t figure out why Ember can’t find and render the template specified in my renderTemplate hook override. I have the following route configuration as per router.js:

  this.route('posts', function() {
   this.route('history', function() {
    this.route('new', { path: '/new/:id'});
   });
  });

I’m also making use of my history index route. Therefore, my history.hbs is just an outlet, and all my templating for this route is actually housed in index.hbs. This way, I can render my new.hbs template on its own page.

In new.hbs, I’d like to render an outlet, in addition to some other content. To handle this, I attempted to override the renderTemplate hook in routes/new.js, like this:

  renderTemplate() {
   this.render('posts/history/test', {
    into: 'new',
    outlet: 'test',
   });
  }

I created the new template under templates/posts/history:test.hbs`. File structure for my templates folder looks like this:

templates > posts > history > new.hbs, test.hbs

Finally, in new.hbs, I added my outlet for this new template:

When I navigate to my new route, I get the following error: Assertion Failed: You attempted to render into ’new' but it was not found. Anyone know how I can get past this?




Reflexive relation with nested data

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!




lundi 10 septembre 2018

Triggering an action on the parent route from a component in the sub route

In my application I currently have a parent route that manages my query params. I have a component that resets these params using a closure action. The current implementation works and looks like this:

// Component

import Component from '@ember/component';

export default Component.extend({
  tagName: '',
  actions: {
    actionTest() {
      this.get('onClick')()
    }
  }

});


  <div class="text-muted" style="cursor: pointer" ><small></small></div>

// Parent Route Controller

import Controller from '@ember/controller';

export default Controller.extend({

  actions: {
    resetAllParams() {
      this.set('param1', null)
      this.set('param2', null)
    }
  }

});

// Template



I would like to move the component from the Parent Route Template to a Sub Route template. When I do this I no longer have the ability to reset the params - my understanding that it isn't possible to manipulate the params of a parent route on a sub-route.

I think that I need an extra step in the closure action feature but I don't understand it very well. I tried to use Ember Route Action Helper but this doesn't appear appropriate for this use case.

I tried to 'bubble up' the action by adding the following:

  // Sub-Route Template



// Sub Route Controller

import Controller from '@ember/controller';

export default Controller.extend({
resetAllParams(){}
});

But it error'd out with a 'this.get is not a function' error from the action in the component controller.

Any help greatly appreciated




Using fetch inside an action within my component

I'm curious about how I could implement this, I'd like to not hit this API every time the page loads on the route, but would rather start the call on an action (I suppose this action could go anywhere, but it's currently in a component). I'm getting a server response, but having trouble getting this data inside my component/template. Any ideas? Ignore my self.set property if I'm on the wrong track there....Code below..Thanks!

import Component from '@ember/component';

export default Component.extend({
  res: null,
  actions: {
    searchFlight(term) {
      let self = this;
      let url = `https://test.api.amadeus.com/v1/shopping/flight-offers?origin=PAR&destination=LON&departureDate=2018-09-25&returnDate=2018-09-28&adults=1&travelClass=BUSINESS&nonStop=true&max=2`;
      return fetch(url, {
        headers: {
          'Content-Type': 'application/vnd.amadeus+json',
          'Authorization':'Bearer JO5Wxxxxxxxxx'
        }
      }).then(function(response) {
        self.set('res', response.json());
        return response.json();
      });
    }
  }
});




JWT Authentication with Rails and Ember JS

What is the right way to proceed the logout action of the User when using JWT, Rails API and a JS front-end framework, for example Ember JS ? What I'm actually doing is: - check the presence and pass in a token in every request between Rails API and Ember JS apps.

Should I keep a token value in the backend model (User, for example) ? I need it to make another request in the background on the backend side.

Should I set the token value to nil when the User logs out ?

Actually the token value is kept in a cookie on the client side (see https://github.com/simplabs/ember-simple-auth for more details).

Thank you.




EmberJS "detail" page fetches the model automatically - is this normal?

Long time reader - first time questioner here.

I am developing a medium sized application in EmberJS which is a framework that I have been using for a while.

Today I have realised that it fetches model data from the server without me writing any code.

I have a main route called "students". Then there is a "list" sub route where the model() function of this route calls the store to fetch all the students and lists them on a table.

On each row of this table I link to another sub route called "detail" where it accepts the ID of each student as an argument. However inside the route.js file for this route there is no model() function querying any information about the specific student from the server.

Ember does this automatically somehow as I can see the appropriate network request being made using chrome dev tools.

How is this happening and is it normal?

Thank you in advance.




Pushing array of string data in model in ember

I have an API response that returns something like this

{
  texts: ["Text1", "Text2", "Text3"]
}

I have created the Ember model as follow (text.js - model file)

import DS from 'ember-data';
export default DS.Model.extend({});

I am unsure of what to add in the attributes for the model since the response is an array of string.

I am also getting

You must include an 'id' for topic in an object passed to 'push'

error with the above snippet.

I am new to ember.js and kind of badly stuck at this point.




BelongsTo not returning the value in Ember?

Response:

data:{type: "individuals", id: "xxx-xx-x--x--x",…}
attributes:{user_id: "xxx-xx-x--x--x", ces_user_id: "dsffdsf", first_name: "Test",…}
id:"xxx-xx-x--x--x"
relationships:{addresses: {data: [{type: "addresses", id: "0fe0e6ad-27a1-4e90-9d1f-034716f0ccc4"}]},…}
addresses:{data: [{type: "addresses", id: "0fe0e6ad-27a1-4e90-9d1f-034716f0ccc4"}]}
degrees:{data: [{type: "degrees", id: "2f00d21a-01dc-4391-8aca-a61491a2e7b8"},…]}
emails:{data: [{type: "emails", id: "e0166097-1e2f-4502-8fbc-7522a256c69a"},…]}
faxes:{data: []}
licenses:{data: [{type: "licenses", id: "294e19ac-a7f2-4316-9454-0b0b7276ebd9"},…]}
memberships:{data: []}
organizations:{data: [{type: "organizations", id: "c4178037-3ffc-4984-a317-9a489f2dca54"}]}
phones:{data: [{type: "phones", id: "c04d850b-0174-47f7-95ee-d01d7c51dbf0"}]}
user_image:{data: {id: 23811, type: "user_image"}}
data:{id: 23811, type: "user_image"}
id:23811
type:"user_image"
type:"individuals"
included:[
{type: "addresses", id: "0fe0e6ad-27a1-4e90-9d1f-034716f0ccc4",…},
{type: "emails", id: "e0166097-1e2f-4502-8fbc-7522a256c69a",…},
{type: "emails", id: "47de146a-00b5-4c4d-a492-5f865e14fd6a",…},
{type: "degrees", id: "2f00d21a-01dc-4391-8aca-a61491a2e7b8",…},
{type: "degrees", id: "2b131aec-79c7-4169-8fbc-68fc06aa7e6f",…},
{type: "phones", id: "c04d850b-0174-47f7-95ee-d01d7c51dbf0",…},
{type: "organizations", id: "c4178037-3ffc-4984-a317-9a489f2dca54",…},
{
attributes:{cloudinary-id: "dsfdfsfsddsfsdf", created: "2018-09-08T17:59:53+00:00", published: true,…}
id:23811
type:"user_image"
},
{type: "licenses", id: "294e19ac-a7f2-4316-9454-0b0b7276ebd9",…},
{type: "licenses", id: "21f0c34e-2a51-44b5-bd88-ad57bb28e066",…},
{type: "licenses", id: "43972613-a115-4f6c-937f-16ba823d70f3",…},
{type: "licenses", id: "75be099d-0926-4101-92db-e8e5eb283867",…},
{type: "institutions", id: "61EB6A22-3082-486A-B15E-96E976CD2289",…},
{type: "institutions", id: "339DF935-E3B1-41C5-A3E6-F53120C2856E",…},
]

In ember application, I am getting the above response, and not able to get the user-image. I created a separate model for user-image and relate it to the parent model 'individual' with a belongsTo relationship. Can someone help with that?




dimanche 9 septembre 2018

How to set all attributes of ember object to null ?

I have an ember object 'Person' . For example ,

        person = { 
                  name: "Rahul" , 
                  age: "29", 
                  companyDetails: { tel: "9809823897" , name: "Amazon"},
                  phone: "2377373893" 
        } 

How do i set all properties of this 'person' to null? I want the result to be

        person = { 
                  name: null , 
                  age: null, 
                  companyDetails: { tel: null , name: null},
                  phone: null 
        } 




vendredi 7 septembre 2018

(Ember) Get/lookup component in controller

In my route.hbs I have several components that have computed properties. In my controller I want to see the state of these computed properties. I can't two-way bind the values since they are computed properties. Is it possible to do get the instance of a component inside of a controller and inspect its values?

I have tried Ember.$(#) but this just returns the dom object.




Click inside click option making difficult in my code

I had created the background color as yellow while selecting the gear icon for the menu option as delete in the table row, I have tried the below code for highlighting the table row,

            click: function () {
                        var ibmm = this.get('parentView.rowView.object');
                        var ibmms = this.get('parentView.rowView.tableView.model');
                        $(function() {
                              $("table.content-table.highlighted tr.content-row").on("focusout", function() {
                                  $(this).toggleClass("my-line");
                              });
                            });
                        var model = Core.model.Menu.create({
                            loadState: 'done',
                            content: [
                                Core.model.Menu.Item.create({
                                    label: 'Delete',
                                    icon: 'delete',
                                    invoke: function () {
                                        var fmtLabel = ibmm.label ? (ibmm.label + " ("+ibmm.name+")") : ibmm.name;
                                            Core.confirm(
                                                "Delete Definition",
                                                "Are you sure you want to delete the Definition for " + fmtLabel + "?",
                                                "Delete",
                                                "Cancel"
                                            ).then(function () {
                                                Core.services({
                                                    service: 'ibmm',
                                                    type: 'delete',
                                                    data: {
                                                        name: ibmm.name
                                                    }
                                                }).done(function () {
                                                    ibmms.reload();
                                                    Core.notify({
                                                        title:"Delete LMD Definition",
                                                        message: "LMD Definition " + fmtLabel + " deleted"
                                                    });
                                                });
                                            });

                                    }
                                })
                            ]
                        });
                        var view = Core.view.Menu.create({
                            model: model,
                            menuContext: { ibmm: ibmm },
                            anchor: this.$(),
                            highlight: this.$().parents('tr:first')
                        });
                        view.show();
                        return false;
                    }

Corresponding CSS I'm using as:

table.content-table.highlighted tr.content-row.my-line {
  background: #FFFF99 none 0 0 repeat;
}

While selecting the menu from the table row (hidden) with the gear icon, the background color is coming well by using the focusout function. But when I select the next table row with the gear icon, the background color is getting disappear. Because of main click function is going by using return. I'm having click function inside the click function. So only these problem occuring.

Please suggest me some suggestion on this. Thanks in advance




is there a way to differentiate ember serve from ember build in environment.js?

I would like to either be able to pass an argument in ember build that differentiates it from ember serve (http://localhost:4200).

I am trying to have a different rootURL when running locally through localhost:4200 and when it is build in the dev server using ember build https://www.example.com/app .

Otherwise is it possible to set the default environment of ember serve to be 'local' instead of 'development?

Thanks




jeudi 6 septembre 2018

Using a session based Rails API with Ember

I am trying to use a Rails API with Ember. I need the ember app to connect to a different server by setting the host property on the adapter. When a user logs in, I set the session to have the user id by doing this: session[:user_id] = user.id. However, on the calls to the api after logging in, the session is blank. Is there something I can do to make the session work? I can use postman without any problems using the api, so I believe it can be possible.

I realize a token based API approach would be better, but I am trying to get something to work now and look at using tokens later.




Ember.js project compatibility with IE 10

I'm trying to get my project work on IE10 (Ember.js 2.18). First, i was getting error on Intl API... Then i found https://github.com/alexlafroscia/ember-cli-polyfill-io and worked pretty well. Now I found myself with this error:

SCRIPT5007: Unable to get property 'polymorphic' of undefined or null reference vendor.js, line 16342 character 3

I tried to debug and found that maybe is a problem with Popper.js (or ember-popper who use the same file). Someone already faced it before? Any tips on how can I sort of debug the vendor bundle in a better way?




Need to remove the row highlight after select the next row

I need to remove the row highlight when I click on the next table row.

When I'm using the below code the table row is highlighted while clicking the menu in the gear icon. Then when I click for the another table row or gear icon the existing table row highlight is not getting removed. Can anybody please provide me suggestions on how to fix this.

$(function() {
  $("table.content-table.highlighted tr.content-row").on("focusout", function() {
    $(this).css({
      'background': '#FFFF99 none 0 0 repeat'
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="ember18549" class="ember-view content-table focus-group object-table container-view highlighted">
  <tbody>
    <tr id="ember18784" class="ember-view content-row body-row-view container-view" tabindex="0" aria-label="">
      <td id="ember19010" class="ember-view lmdd-menu actions container-view">
        <rs-icon id="ember19015" class="ember-view action-menu icon clickable-icon" title="Acciones y Transiciones" style="width: 1em; height: 1em; font-size: 20px">
          <icon glyph="action" class="action" style="font-size: 20px;">
          </icon>
        </rs-icon>
      </td>
      <td id="ember19021" class="ember-view content-data view view-core_component_data-view-mixin name">
      </td>
    </tr>
    <tr id="ember18784" class="ember-view content-row body-row-view container-view" tabindex="0" aria-label="">
      <td id="ember19010" class="ember-view lmdd-menu actions container-view">
        <rs-icon id="ember19015" class="ember-view action-menu icon clickable-icon" title="Acciones y Transiciones" style="width: 1em; height: 1em; font-size: 20px">
          <icon glyph="action" class="action" style="font-size: 20px;">
          </icon>
        </rs-icon>
      </td>
      <td id="ember19021" class="ember-view content-data view view-core_component_data-view-mixin name">
      </td>
    </tr>
  </tbody>
</table>



mercredi 5 septembre 2018

Configure ember-cli production build with sourcemaps to different domain

I'd like to configure the ember-cli build in a way that I'm able to change the URL for the sourcemaps. In production I only want to make them available for members inside the private network.

I can already get those sourcemap-files to the desired location.

The sourcemap reference at the bottom of the minified js files has to change from //# sourceMappingURL=app-cfe74707c5fabd05465ffc575495dc46.map to //# sourceMappingURL=http://localhost/sourcemaps/app-cfe74707c5fabd05465ffc575495dc46.map

Is there an ability to change it in the ember-cli config or do I have to use something like ember-cli-deploy?




Data down binding for child components in Emblem.js

Environment, Ember w/ Emblem.js

Working on a project, and I'm trying to make it modular to dynamically pull in the correct form layout (child component) depending on what choice the user makes.

Problem I'm having is I have a child component with references to mutable objects in the parent that I am trying to access for read, and write.

I believe that I need to bind the data down, then push the mut action back up to the parent based on DDAU.

JS Parent.js

export default Ember.Component.extend({
store: Ember.inject.service(),
name: null,
infoArray: Ember.computed.map(....),
isVisibleChild1: false;
actions: {
    picker() {
        if(dropdown.value==1)
            this.set('isVisibleChild1', true);
    }
},

Child1.js

needs to contain a variable childInfoArray somewhere

I found online that to bind data from parent to child forms with hbs



Emblem.js Parent.emblem

if isVisibleChild1
    = Child1
    childInfoArray = infoArray

Child1.emblem I recognize that infoArray should probably be childInfoArray

select id="newInfo" onchange={action (mut infoArray) value="target.value"}
    each optionsArray as |selectOption|
        option selected={is-equal selectOption.key infoArray} value="#{selectOption.key}" = selectOption.value

I'm not sure where exactly the childInfoArray should go in Child1.js and I'm not totally sure how to bind it to an object in Child1.emblem

any help would be fantastic!




How to use function with arguments in ember.js template - Handlebar

Currently Im trying to use a function that observes a field of a controller/component in ember template (handlebars).

index.hbs


   <span>This field is required</span>


index.js

hasFieldError: function(val) {
   return true if val is found in an array
}.observes('field1'),

But this of course returns a build error:

{#if hasFieldError('compa ----------------------^ Expecting 
'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 
'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 
'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'

Any idea how to achieve this?




unable to start a docker container running ember.js image, node_modules empty

I am trying to get ember.js to run in a docker container based on the image danlynn/ember-cli image

Tried different versions of Dockerfile and docker compose.yml, but I always end up with the docker-compose up command complaining of the following :

node_modules appears empty, you may need to run npm install

The image and container are created, but the container will not start.

I am new to the docker world, so any help would be greatly appreciated!

I am guessing I need to run npm install for the error to go away, but I added it to the Dockerfile so that It would run as the image is built, but that did not seem to help.

Here is my Dockerfile contents:

FROM danlynn/ember-cli
WORKDIR /code
COPY package.json /code
COPY bower.json /code
RUN ember init
RUN ember init --yarn
RUN bower --allow-root install
RUN npm install
COPY . /code
CMD ["ember", "serve"]

and the docker-compose.yml file:

version: "3"
services:
  ember_gui:
    build: .
    container_name: ember_dev
    volumes:
      - .:/code
    ports:
       - "4200:4200"
       - "7020:7020"
       - "5779:5779"

Finally, here is the package.json just in case

{
  "name": "EmberUI",
  "version": "0.0.1",
  "description": "Test app GUI",
  "main": "index.js",
  "author": "Testing",
  "license": "MIT",
  "dependencies": {
    "chai": "^4.1.2",
    "mocha": "^5.2.0"
  }
}




Highlight row is not getting disappear after I click the next table row

I need to create background as yellow while selecting the gear icon for the menu option in the table row, I have tried the below code for highlighting the table row,

var view = Core.view.Menu.create({
    model: model,
    menuContext: { ibmm: ibmm },
    anchor: this.$(),
    highlight: this.$().parents('tr:first').css('background-color','yellow')
});
view.show();

While selecting the menu from the table row, the background color is coming well. But when I move for the next table row, the past table row color is still in yellow color, not getting disappear. Can anybody suggest me code for this. I’m using Ember 1.4.0.




mardi 4 septembre 2018

How do I backgroundReload in multiple stages in Ember?

I'm fetching a list of records, say posts, without relationships. When I pick a single post, I would like to see the post immediately, and background-load its relationships.

This is possible like so:

this.store.findRecord('posts', params.id, {
    reload: false,
    backgroundReload: true,

Once the relationships are loaded, the view is automatically updated.

However, some relationships are complex and take some time to load. They become relevant after scrolling. There is one hasMany relationship that is important for the initial pageview. And their relationships are also important, but I prefer to defer them too.

So, is it possible to do the following points in order when clicking on a single post?

  • Open post directly from cache (reload: false)
  • Background-reload including one relationship excluding the relationship's relationships
    • Background-reload relationship including relationship's relationships
  • Background-reload including all relationships

E.g. after the initial template is drawn using the cached model, 3 more updates will happen.




Need to create the background color as yellow in the table row while I'm clicking on the menu

I need to create background as yellow while selecting the gear icon for the menu in the table row, I have tried the below code for highlighting the table row

                                var view = Core.view.Menu.create({
                                    model: model,
                                    menuContext: { lmdd: lmdd },
                                    anchor: this.$(),
                                    highlight: this.$().parents('tr:first')
                                });
                                view.show();

In that lmdd is a java service, it will show the menu list while click on the gear icon. By using the highlight only I need to do this operation.

Please suggest answers from this standpoint. thanks in advance.




How to create one class name in element while click on the table row

I need to include one class name inside the tag on clicking the corresponding row on the table. because I need to highlight the row while click on the corresponding row by using css. When I click on the row, its not showing any class name in the console. because of that I can't able to create the row highlight.

Here is the code I'm using:

        click: function () {
                var test = this.HeaderRowView.tableView.model;
                 $('.content-data').off('contextmenu');
                 $('.content-data').contextmenu(function(e){
                    if(e.which == 3){
                        var ibmm = this.hovered;
                        var model = Core.model.Menu.create({
                            loadState: 'done',
                            content: [
                                Core.model.Menu.Item.create({
                                    label: 'Delete IBMM Definition',
                                    icon: 'delete',
                                    invoke: function () {
                                        var fmtLabel = ibmm.label ? (ibmm.label + " ("+ibmm.name+")") : ibmm.name;
                                        Core.confirm(
                                            "Delete IBMM Definition",
                                            "Are you sure you want to delete the IBMM Definition for " + fmtLabel + "?",
                                            "Delete",
                                            "Cancel"
                                        ).then(function () {
                                            Core.services({
                                                service: 'ibmm',
                                                type: 'delete',
                                                data: {
                                                    name: ibmm.name
                                                }
                                            }).done(function () {
                                                test.reload();
                                                Core.notify({
                                                    title:"Delete IBMM Definition",
                                                    message: "IBMM Definition " + fmtLabel + " deleted"
                                                });
                                            });
                                        });
                                    }
                                })
                            ]
                        });
                        var view = Core.view.Menu.create({
                            model: model,
                            menuContext: { ibmm: ibmm },
                        });
                        document.styleSheets[1].cssRules["1538"].style.display ="none"
                        view.show();
                        Ember.run.next(view, (function () {
                            var X = e.clientX;
                            var Y = e.clientY;
                            if(document.getElementsByClassName('context-menu-items')[0]) {
                                document.getElementsByClassName('context-menu-items')[0].style.left = X+'px';
                                document.getElementsByClassName('context-menu-items')[0].style.top = Y+'px';
                                document.styleSheets[1].cssRules["1538"].style.display =""
                                document.getElementsByClassName('context-menu-items')[0].style.display = "block"
                            } else {
                                view.remove()
                                document.styleSheets[1].cssRules["1538"].style.display =""
                                return false;
                            }
                        }).bind(this));
                        return false;
                    }
                    }.bind(this))
            }

Here is the click option with the corresponding service code's. Please suggest me code from this. thanks in advance.




dimanche 2 septembre 2018

How to trim data before set using Ember.set

As a newbie to Ember.

I have an Object that has to be trimmed for white-spaces before updating/assigning with ember.set.

I know it can be done with using this.set(/**/).trim(). But just set() is not supporting trim(). And I have been told this.set() is not a best way than compared to just set()

set(Object, Key, NewValue) is how my syntax is.




Googlebot refuses to render more than index.html in Ember app

I am using Ember 3.0.0 to create a booking site. Title and meta tags are handled via ember-cli-meta-tags, and seem to be rendered correctly when pages are opened in the web browser.

However, Googlebot refuses to render the app normally. Whatever I do, it just renders a blank index.html page. We have tried to shorten the time of loading the model, but even non-dynamic pages (without Ember Data requests in the model) are not rendered.

Here is an example from https://www.muntra.se/tandblekning:

import { schedule } from '@ember/runloop';
import { get, set } from '@ember/object';
import ENV from '../config/environment';
import Route from '@ember/routing/route';

export default Route.extend({
  title: 'Tandblekning i praktiken: Allt du behöver veta',

  patientPortal: ENV.APP.patientPortal,

  headTags: function() {
        return [
            {
                type: 'link',
                tagId: 'canonical-link',
                attrs: {
                    rel: 'canonical',
                    href: get(this, 'patientPortal') + '/tandblekning'
                }
            }, {
                type: 'meta',
                tagId: 'meta-description-tag',
                attrs: {
                    name: 'description',
                    content: 'Konkret och praktisk guide för tandblekning som gör att du sparar pengar, minskar risk för skador och får vitare tänder.'
                }
            }
        ];
    },

  titleToken: function() {
        return 'Tandblekning i praktiken: Allt du behöver veta';
    },

  setupController(controller, model) {
    this._super(controller, model);
    schedule('afterRender', this, function() {
      set(controller, 'after_render', true);
    });
  }
});

When testing this page on http://www.botsimulator.com/, I get the same rendering as on index.html. And also in Google Search results when googling "tandblekning site:muntra.se".