jeudi 31 août 2017

EmberJS queryRecord do not returns all data

Hi starting to learn emberJS, and periodicaly become a little bit confused. maybe someone can suggest any examples more advanced than in official documantation?

Back to the current problem, I have:

Adapter

export default DS.JSONAPIAdapter.extend({
  queryRecord(store, type, query) {
    return Ember.$.getJSON("http://localhost:3000/user");
  }
});

Model

export default DS.Model.extend({
  username: DS.attr(),
  fullname: DS.attr(),
  email: DS.attr()
});

then in router:

  model() {
    this.get('store')
      .queryRecord('user', {})
      .then(function (res) {
        let username = res.get('username');
        console.log(`Currently logged in as ${username}`);
      });
  },

Why I get user name undefined, as well as all other properties exept id. Depite in browser response i see:

{
 "data":{"type":"user",
        "id":"u2",
        "username":"user2",
        "password":"pass2",
        "fullname":"Test User Two",
       "email":"user.two@test.com"}
}

What I missed?




How can i add a js file for a specific template/page in Ember?

I'm new with ember, and I want to add some js files for a specific template/page, not for all pages. I included some global js files in ember-cli-build.js , but i need to include others for specific pages IE: for dashboard page i need to add dashboard.js.

Any idea?




Path configuration for testing Ember-electron with Spectron

I am trying to integrate Spectron with Ember-electron for testing.

I found an example for Spectron but I am not sure what to assign in the electronPath part in case of Ember-electron.

I do not have an .exe or .cmd how to point to the location of the application in the test folder.

beforeEach(function () {
return helpers.startApplication({

  args:[path.join(__dirname, '..')] //**
}).then(function (startedApp) { app = startedApp })
})




mercredi 30 août 2017

Ember Data tracking store state

I want to push some updates using websocket and pushPayload. The problem is that sometimes websocket update comes earlier that actual transaction of store finishes, which brings the errors, like this one:

ember.debug.js:17636 Assertion Failed: You cannot update the id index of an InternalModel once set. Attempted to update 1569.

So I'd like to make sure that there are no transactions in flight before actually pushing any data.




Ember 2, ember-cli, custom addon, hook to modify text in js before final integrity (ember-cli-sri)

After this question Ember,js. Modify app.js and vendor.js before the final integrity seal. One custom step in build pipeline? I'm building an addon for modify the js before the final integrity step (with ember-cli-sri).

lib/modify-js-before-build/index.js

/* eslint-env node */
'use strict';

module.exports = {
  name: 'modify-js-before-build',

  isDevelopingAddon() {
    return true;
  },

  postprocessTree(type, tree) {

    // WHAT TO DO!?

  }

};

lib/modify-js-before-build/package.json

{ ...,
"ember-addon": {
    "before": "ember-cli-sri"
  }
}

But I'm stucked here, I don't know how to do (I do not know very well broccoli). How can I tell it to add some text in my app.js and vendor.js before ember-cli-sri and other build steps?

I found this one: http://ift.tt/2ekOrB4. They are using broccoli-concat and broccoli-merge-trees. Something similar to me? But how?




Is Auth0 worth paying for ?

I am building a web application which requires user logins. Whats the difference in using auth0.com and using an PHP library for authorisation ? http://ift.tt/1P2vPy8

Is there any substantial gain in paying to use auth0.com rather than creating my own server to deal with the authorisation ?

I am using Ember as the front end with Ember simple auth and hopefully using the linked library for the backend.




Does ember-data do any caching internally?

If using a simple JSONApi or REST Api backend (that complied with what ember-data requires), does ember-data perform any caching out of the box? For example if I consume /posts (an array of posts), and then go to /posts/1 route. Then I come back to /posts/ route. Is /posts downloaded again? Or the older data is used ?




ember-cli-deploy: revision ID not getting appended to the files

In the dist file where the deploy files are getting build, the revision number is not getting updated at the end of the file

I am using the following ember-cli-deploy plugins

"ember-cli-deploy": "1.0.1",
"ember-cli-deploy-lightning-pack": "1.1.2"

and my deploy.js file looks as below

var VALID_DEPLOY_TARGETS = [ //update these to match what you call your deployment targets
  'development'
];

module.exports = function(deployTarget) {
  var ENV = {
    build: {},
    redis: {
      allowOverwrite: true,
      keyPrefix: 'my-app:index'
    },
    s3: {
      prefix: 'my-app'
    }
  };

  if (deployTarget === 'development') {
    ENV.build.environment = 'development';
    ENV.s3 = {
     accessKeyId: process.env.ACCESS_KEY_ID,
     secretAccessKey: process.env.SECRET_ACCESS_KEY,
     bucket: process.env.BUCKET,
     region: process.env.REGION,
     filePattern: '**/*.{js,css,png,gif,ico,jpg,map,xml,txt,svg,swf,eot,ttf'
     +',woff,woff2,html}'
   }
  }
  return ENV;
}

what I understood from documentation is that the files generated for upload should be of format <filename>-<revisionID>. But when I run ember deploy development the following files are getting generated in the distFolder which gets uploaded to S3

my-app.css
my-app.js
brand.png
passed.png
test-support.js
tests.js
vendor.css
vendor.map
my-app.css.map
my-app.map
failed.png
test-support.css
test-support.map
tests.map
vendor.js

There is no revision ID and because of it when I try to upload the files the second time, the manifest doesn't picks the change and does not upload the changed file.

the ember -v --verbose is

ember-cli: 2.10.0
http_parser: 2.7.0
node: 6.10.1
v8: 5.1.281.95




How htmlUnit works with data-ember-action?

I have a input

<input value="http://change" id="view_data_edit" maxlength="2048" data-bindattr-29="29" class="ie6bug" type="text">   

and a button

<button class="atp_button pull-right marginright_17p fontweight_thick" id="submit" data-ember-action="24"><span id="i18n-8">Save</span></button>

I use

   final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
    webClient.getBrowserVersion().setOnLine(true);
    webClient.getBrowserVersion().setBrowserLanguage("ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3");
    webClient.setJavaScriptTimeout(20000);
    webClient.getOptions().setTimeout(20000);
    webClient.waitForBackgroundJavaScript(20000);
    webClient.setRefreshHandler(new ImmediateRefreshHandler());
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    webClient.getOptions().setGeolocationEnabled(true);
    webClient.getOptions().setRedirectEnabled(true);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setCssEnabled(true);
    webClient.getOptions().setActiveXNative(true);
    webClient.getOptions().setAppletEnabled(true);
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setThrowExceptionOnScriptError(false);

    webClient.addRequestHeader("Upgrade-Insecure-Requests", "1");
    webClient.addRequestHeader("DNT", "1");

and then after go to the site

  final HtmlTextInput url = (HtmlTextInput) advancetr069.getElementById("view_data_edit");
    url.setText("http://123453qw");


  final HtmlButton  save_submit = (HtmlButton) advancetr.getElementById("submit");
    final HtmlPage save_submitPage = save_submit.click();

The value in input does't change. I think that this is because button use

data-ember-action
How htmlUnit works with data-ember-action ?




EmberJS: Retransition to current route and reset dynamic segment

I have some routes defined like:

Router.map(function() {
      this.route('foo', function() {
         this.route('bar');
         this.route('bar', {path: 'bar/:fooid'});
      });
      // ...
});

The dynamic segment in /foo/bar/:fooid is an id that can be validated against some rules. To simplify the example, let's assume :fooid must consist of exactly 3 digits.

If an invalid value gets passed like in /foo/bar/1234567, I want reset the to url to foo/bar/.

Simplified foo.bar route:

export default Ember.Route.extend({

  model (params) {
     // If fooid is invalid, set model.fooid.isValid to false
  },

  afterModel (model, transition) {
     // If fooid is invalid...
     this.transitionTo('/foo/bar/');
  }

});

The validation process itself works but I can't get rid of the wrong :fooid parameter in the url!

If I transition to a different route it works fine.

Ember version is 2.14




Issue with the creation of a relationship with ember

I have a problem, I can't replace a hasMany relationships. I have a zone, which has a hasMany relationships parent. I need to change the relationships, I'm using the module ember-cli-jstree, and if I want to modify it with the plug-in dragAndDrop, I should be able to modify the data inside my store, because otherwise, there no point in moving it in my tree.

Here is my code :

let arrParent;
let newParent;

// This is an array that contain the position
arrParent = catchActualParent(node, this.get('zone'));
// This is an object which is in the good format
newParent = catchNewParent(node, this.get('zone'));

//Doesn't work
this.get('zone').objectAt(arrParent[0]).createRecord('parent', newParent).save();

Right there the problem is that it doesn't set the relationships, the object newParent format is correct, I checked it.

Here is my model :

export default DS.Model.extend(ZoneValidations, {
    numericId: Ember.computed('id', function ()
    {
        "use strict";
        return Number(this.get('id'));
    }),
    alias: DS.attr('string'),
    description: DS.attr('string'),
    type: DS.attr('zone-type'),
    doors: DS.hasMany('door'),
    children: DS.hasMany('zones'),
    parent: DS.hasMany('zones', {inverse: 'children'})
});

So i'm wondering if anyone as a tip about that.

TLDR: How do add an Ember.object with a relationship.




How can one structure nested routes when parent objects are not persisted (have no :id)?

How can one structure nested routes when parent objects are not persisted (have no :id)?

I'm basically building a object configuration wizard, where a book has several child configuration models. the user's path through the configuration is roughly:

  1. Users upload manuscripts, and the record is persisted.
  2. User transitions to book/configuration/cover
  3. User can go back and forth between various configuration subroutes.
  4. After configuring, user clicks to trigger persisting the parent and children.
  5. After the book is persisted, they could go back to edit.

Must I create two sets of routes - one for edit and one for new that omits the book.id in the path? Is there a way to do it in one go?

//my routes:
this.route('upload-manuscripts', function() {
  this.route('new');
});

Router.map(function() {
  this.route('book', {path: '/:id'}, function() {
    this.route('configuration', function() {
      this.route('cover');
      this.route('spine');
      this.route('pagination');
    });
  });
});

Thanks!




On brower back button app `init` method not called

I am showing and hinding a html tag by setting variable as true or false. it works fine. but when user clicks on back button of browser the method is not triggers. in my route my init look like :

init(){ this.controllerFor('auth-page').set('naviTab', true ); console.log('init called') },

it works if in case if the page refreshed. but not by using browsers back or forward button. how to fix this?




Ember route/controller lifecycle

I can't seem to find any documentation on route/controller lifecycle.

When is the controller created? When is the controller's init() executed? Is it upon entering the route or is it after beforeModel/model/afterModel has resolved?

Thanks in advance




Ember data post form data as JSON

Common feature - register user - store data in mongodb. In postman everything is ok, I can't make it good from app ui although.

My controller:

export default Ember.Controller.extend({
actions: {
    addUser: function(){
        let formData = {
            "fullname": this.get('fullname'),
            "firstname": this.get('firstname'),
            "lastname": this.get('lastname'),
            "email": this.get('email')
        };

        let newUser = this.store.createRecord('candidate',{
            fullname: formData.fullname,
            firstname: formData.firstname,
            lastname: formData.lastname,
            email: formData.email
        })
        newUser.save();

    }
}
});

My adapter:

import DS from 'ember-data';

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

My model:

import DS from 'ember-data';

export default DS.Model.extend({
  fullname: DS.attr('string'),
  firstname: DS.attr('string'),
  lastname: DS.attr('string'),
  email: DS.attr('string')
});

post request is successful with 201 status. In db I see new empty document. In console I see error "SyntaxError: Unexpected token C in JSON at position 0" I guess I should have declare JSON.parse. In adapter? Making JSON.parse(newUser) doesn't help. I am newbie with ember so I guess I silly mistake but I cannot find any.




mardi 29 août 2017

Add new element to DOM on action in Ember

What would be a proper way to dynamically add a new element to DOM in Ember? For example a tooltip. Currently I render all tooltips right away, but they're hidden and only shown on mouse over, which takes time to render anyways. I could use jquery or plain JS to append element on event and it would probably work, but would it be the most efficient way to do so? Also would be nice to still be able to use a template, so code wouldn't be too large.




Why isn't an HTTP request being issued when the route changes?

I have an Ember project with the following router:

import Ember from 'ember';
import config from './config/environment';

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

Router.map(function() {
  this.route('index', {path: '/'}, function() {
    this.route('folder', {path: 'folder/:folder_id'});
  });
});

export default Router;

The contents of routes/index/folder.js are as follows:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    console.log(params);
    return this.store.query('message', {folder_id: params.folder_id});
  }
});

My expectation is that when the route changes to /folder/1, the model() method will be invoked to fetch the messages for the folder.

However, this does not occur. The route indeed changes, but the model() method is never invoked (nothing is written to the console).

What am I missing?




Ember 2, PERFORMANCES DILEMMA, computed properties in route or controller?

I'm using Ember 2.14.1.

Is it better that computed properties and something like that (until routeable components land) is on route or in a controller?

For performances reasons I mean. Is there any difference?




How can I display a list components in my Ember.js application?

My Ember.js has many components that the end-user can use to compose a page. How can I display a dynamic list of the components that exist in my Ember Application?

I imagine the registered components is somewhere in the Ember.Application object, but I'm having a hard time finding something I can use.




How to wait for a global/event outside of Ember?

I am working with a third-party library that provides its own global "ready" function. I am creating an Ember component that will need to wait until this ready function has been called before executing some code in my didInsertElement function. How can I wait until this global ready function to execute before calling my didInsertElement code?

// index.html
<script src="http://ift.tt/2xJX4N6"></script>
<script>
function thirdPartyReady() {
  // Do something here. Maybe window.thirdPartyReady = true ?
}
</script>

// my-component.js
export default Ember.Component.extend({
  didInsertElement() {
    this._super(...arguments);
    // wait until thirdPartyReady before using it on this element
  }
});




Handlebars: Best Way to Show Spinner While Waiting for AJAX request

I know the answer to "Best Way to Show Spinner While Waiting for AJAX request?" but what would be best approach when we semantic templates e.g. handlebars are used.

I've a theoretical solution to share but would like to know if there is any better approach.

Here is the template I defined:

<script id="AnalyticsTemplate" type="text/x-handlebars-template">
    <div class="circle-tile-content dark-blue">
                                <div class="circle-tile-description text-faded">Free Subscriptions</div>
                                
                                <div class="circle-tile-number text-faded "></div>
                                
                                <div class="preloading"></div>
                                
                                @*<a class="circle-tile-footer" href="#">More Info <i class="fa fa-chevron-circle-right"></i></a>*@
                            </div>
</script>

Current approach is to use 'IF' condition, and compile the same template twice. First, before the AJAX call with empty data and later on AJAX success/error.

Hope this is understood, if not, feel free to ask.

Any suggestion or feedback would be highly appreciated.




How to async loading ember jstree for selected node

I am trying to use jstree plugin in ember js in one of my projects. I am using this plugin to load a folder structure, but I would like to do this operation async. The examples I've found on their site (called async) are ridiculous. I've tried to check on the Internet but it seems that most people load the whole tree. I would like to load a branch on every single node click. I am using JSON. data: [ 'Simple root node', { 'id': 'rn1', 'text': 'Single child node (has tooltip)', 'type': 'single-child', 'state' : { 'opened' : true,

            },
            'children': [
                'one child'
            ],
            'a_attr': {'class': 'hint--top', 'data-hint': 'Use a_attr to add tooltips'}
        },
        {
            'id': 'rn2',
            'text' : 'Opened node (has tooltip)',
            'state' : {
                'opened' : true,

            },
            'a_attr': {'class': 'hint--bottom', 'data-hint': 'This is a bottom mounted node tooltip'},
            'children' : [
                {
                  'text' : 'Child 1'
                },
                'Child 2'
            ]
        }
    ],
    addChildByText(id) {
    var data = this.get('data');
    data.forEach(function(node, index) {
    if (typeof node === 'object' && node["id"] === id) {
    data[index].children.push('added child');
    }
    });
    this.set('data', data);
    }




lundi 28 août 2017

Ember Data lazy load hasMany relationships without relationship ids

Is it possible to lazy load relationships without having the Ids of the relationship.( for both the JSON:API and REST serializer/adapter)

Currently given the model

// BaseModel
export default DS.Model.extend({
  related_model                   : DS.hasMany('related_model', {async:true}),
});

if the API responds with something like

{
  related_model_ids : [1,2,3]
}

then ember data with load fk models lazily.

/related_model/1
/related_model/2
/related_model/3

However for the performance cost of loading a 1:* relationship in a SQL backend is pretty much the same for fetching just the IDs or the entire data for all the related records I still have to JOIN the tables. to the backend/ORM it not really lazy or sideloading as all related records still need to be fetched on the baseModel request

The reasoning for requiring the model ids in the baseModel request seems to be that without knowing the IDs it will not be possible to make the relatedModel request. However that should be not required, a find query with baseModel id on the relatedModel should work just as well.

i.e. Is there way where Ember data can instead make directly the query on the relatedModel with something like this if the relationship is async

/related_model?base_model_id=1

This way the relatedModels are only loaded/joined when called required and not with every baseModel request




How to highlight a list-item in an unordered list when clicked?

We are creating a way to filter in our jobs portal.

           
                       <li >
                            All
                        </li>
                        <li active=true >
                            Intern
                        </li>
                        <li >
                            New Grads
                        </li>
                        <li >
                            Entry Level
                        </li>
                        <li >
                            Senior
                        </li>
            

When a user clicks a <li>, it will call the function filterWith which filters either/or (AKA exactly one filter is applied at any time). We want whichever filter is clicked to be highlighted a different color from the rest.

Implementing this has been very difficult because we want to do it in a way that doesn't use jQuerry (we have been having trouble with mixing jQuerry and Ember together). We might be able to do it just with Bootstrap to do it if we knew how to.




mber 2 performances, is javascript event delegation in #each automagically? How to coalesce similar listeners?

I'm reading a lot (for study) about "Event delegation" and also because in this video: https://www.youtube.com/watch?v=udix3GZouik (minute 22:28) Alex Blom talks about: "Coalesce similar listeners" for performance reasons.

enter image description here

My question is: is Ember automagically performing about this problem?

If I have an #each with many div in it how to coalesce listeners on the parent div? Does Ember do it in my place?

http://ift.tt/1QpBFdG




ember: How to open a ember modal from action in controller

Hi i am writing an ember web application. I have a modal which should be shown in particular case. how to open an ember modal from a action of a controller.




Trouble restricting Pikaday input

I have the following ember-pikaday input:

    = pikaday-input [
      value=person.birth_date
      class="form-control"
      placeholder="MM/DD/YYYY"
      format="MM/DD/YYYY"
      yearRange=dateYearRange
      readonly=(is-readonly disabled)
      onSelection=(action "setField" person "birth_date") ]

There's a problem with this input in that I can type something like "asdf" into it. I want it only to accept valid dates.

I found a keyboardInput option in ember-pikaday's configuration documentation so I tried it like this:

    = pikaday-input [
      keyboardInput=false
      value=person.birth_date
      class="form-control"
      placeholder="MM/DD/YYYY"
      format="MM/DD/YYYY"
      yearRange=dateYearRange
      readonly=(is-readonly disabled)
      onSelection=(action "setField" person "birth_date") ]

It had no apparent effect. I also tried a couple of the other configuration options and they didn't seem to work as expected, either.

I thought maybe I was just editing the wrong file or something. But I removed some of the existing configuration options as a test, and that had an effect, as expected. So I'm really confused about why some options seem to work and some don't.

Any ideas on how to move forward with this problem would be greatly appreciated. I'm open to any solution that forces the Pikaday input to contain a valid date.




How to interpret with each loop?

I am trying to interpret with each loop. but I am not able to come with a good solucation ( ember way! )

how to handle this scernario?

From the loop I am printing 16 digit. whenever the index reach 4 ( index % 4 == 0 ) I would like to add a hyphen.(-)

how to achive this?

here is my route.js :

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
  }
});

my hbs file:

<h1>Each with condition </h1>

    
 

but I look like:

<h1>Each with condition </h1>

      --  
 

So, what is the correct ember approach for this?

Twiddle here




dimanche 27 août 2017

I want loaded index.html from the file system rather than severed from a host

When I run the project at http://localhost:4200, it working fine .but I want open index.html directly use browser (like file:///super-rentals/dist/index.html), it seems like didn't working. Anyone know why? thanks.




Path configuration for testing Ember-electron with Spectron

I am trying to integrate Spectron with Ember-electron for testing.

I found an example for Spectron but I am not sure what to assign in the electronPath part in case of Ember-electron.




install of ember-bootstrap 1.x hangs

ember-cli: 2.14.2 node: 8.4.0 os: win32 x64

For some reason, my npm installation of any ember-bootstrap 1.x version always hangs on fsevents.

C:\Users\rrush\Documents\GitHub\xxxxxxxxxxx>npm install
[            ......] | extract:fsevents: sill extract is-descriptor@0.1.6

I've tried several versions of ember-bootstrap 1.x, node and ember(-cli). They always hang up on fsevents installation.

Any 0.x version will install just fine though.

From what I've gathered, fsevents is only meant to be installed on Mac, not on a Windows machine. Is there any way to circumvent the (trying to) install of fsevents ? I did npm install --no-optional, but to no avail...




samedi 26 août 2017

Displaying marker on the Google Maps in Ember.js

I need your help in fixing the problem and understanding what the error is and how to fix it. I am trying to display the google map with help of Google Maps API in Ember.js but getting this error below please take a look and help.

Error while processing route: search google.maps.Attribution is not a constructor TypeError: google.maps.Attribution is not a constructor
    at Class.setupController (http://localhost:4200/assets/places-finder-app.js:1151:26)
    at Class.setup (http://localhost:4200/assets/vendor.js:42767:12)
    at callHook (http://localhost:4200/assets/vendor.js:61048:38)
    at _handlerEnteredOrUpdated (http://localhost:4200/assets/vendor.js:62643:7)
    at handlerEnteredOrUpdated (http://localhost:4200/assets/vendor.js:62655:7)
    at setupContexts (http://localhost:4200/assets/vendor.js:62610:9)
    at finalizeTransition (http://localhost:4200/assets/vendor.js:62819:7)
    at http://localhost:4200/assets/vendor.js:62217:14
    at tryCatch (http://localhost:4200/assets/vendor.js:63470:14)
    at invokeCallback (http://localhost:4200/assets/vendor.js:63485:15)

ember.debug.js:26513 TypeError: google.maps.Attribution is not a constructor
    at Class.setupController (search.js:14)
    at Class.setup (ember.debug.js:32172)
    at callHook (ember.debug.js:50453)
    at _handlerEnteredOrUpdated (ember.debug.js:52048)
    at handlerEnteredOrUpdated (ember.debug.js:52060)
    at setupContexts (ember.debug.js:52015)
    at finalizeTransition (ember.debug.js:52224)
    at ember.debug.js:51622
    at tryCatch (ember.debug.js:52875)
    at invokeCallback (ember.debug.js:52890)

Here is the file where I am getting error from at Attribution and markerPlace. app/routes/search.js

 export default Ember.Route.extend({
      setupController: function(controller) {
        controller.setProperties({
          selections: {
            markerOptions: {
              animation: google.maps.Animation.DROP,
              anchorPoint: new google.maps.Point(),
              attribution: new google.maps.Attribution(),
              icon: 'beachflag-8f33bab9b0c154462489b35140f29fae.png',
              label: 'A',
              optimized: true,
              place: new google.maps.MarkerPlace(),
              position: new google.maps.LatLng(),
              shape: new google.maps.MarkerShape(),
              title: 'string',
              zIndex: 999
            }
          }
        });
      }
    });




Get access to current Ember route inside component

I have my custom Ember component which is inside a controller.

Now I am trying to get the current route name dynamically

So I get access to the controller using

this.get('parentView')

But I am unable to get the current route name after this. How do I get the current route name ? I tried doing

this.get('parentView').routeName




How to use dot characters in Ember query params

I have an Ember v2.14 app in which I'm trying to query an external API. The API takes query params that have dots (".") in the keys, like this:

http://ift.tt/2vf3GGI

I've tried setting up the queryParams in my controller like this:

// app/controllers/records.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['query.code', 'code.system'],
  query.code: null,
  code.system: null
})

The Ember build fails with "Unexpected token" at the first dot character in the line after my queryParams declaration.

I've tried using percent-encoding to replace the dots, and this works fine if I enter this in the browser:

http://ift.tt/2vf3GGI

But the Ember build again fails if I attempt the same percent-encoding of my query params in the controller.

// app/controllers/records.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['query%2Ecode', 'code%2Esystem'],
  query%2Ecode: null,
  code%2Esystem: null
})

Is anyone aware of something I should be doing differently?




How to get a value from a promise in EmberJS with custom Adapter

I am pretty new to EmberJS, I am trying to get back a value from a promise given by a custom adapter since the backend is not rails API compliant

Here is my custom adapter:

import DS from 'ember-data';
import Ember from 'ember';

    export default DS.Adapter.extend({
      findRecord( store, type, id ) {
        return Ember.$.getJSON("http://localhost:8000/user/by-username/" + id );

  }
});

I also modified my serializer:

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
  primaryKey:'alias',
});

my controller looks like this (where I am stuck):

import Ember from 'ember';

export default Ember.Controller.extend({
  username:'',
  actions: {
    searchUser : function(){
      var id = this.get('username');
      var promise = this.get('store').findRecord('roles', id);
      var self = this
      promise.then(function(value) {
        self.set('username', value.get('ID'));
      }, function(reason) {
        // on rejection
      });


    }
  }
});

Specifically on this line from above controller, I can not get it to work:

self.set('username', value.get('ID'));

The ajax is exectued succesfully since I can see it happen on chrome dev tools returning json following data:

{"ID":"73ebf44f-71bf-4b60-a755-a4bbef208ef1","mjID":34049137,"alias":"isgarbe","registration_date":"2017-07-07T20:03:11Z","information":{"payer":false,"last_payment_date":null,"show_tutorial":false,"last_game_played_game_id":null,"last_game_played_date":null,"last_application_connection_close_date":null,"social_links":null,"payment_count":0},"avatars":{"base_url":"http://ift.tt/2wPLJhh","asset_id":"0a8d02c4278000100000d0000000000580000000000849480020000048888888888800","sizes":["cabecera","normal","medio","maxi"]},"gender":"Female","economy":{"accountId":"34049137","balance":2000000000,"currency":"chips"},"experience":{"user_id":34049137,"level":1,"points":0,"loops":0,"max_points_by_level":20,"min_points_by_level":0},"payment_segment":1000,"security_key":null,"role":null}

I am not able to get the ID value to be set to the username property




How to inject `responsive` object to application

I am trying to inject the ember-responsive module to application. for it's not works. I have installed http://ift.tt/1my8I5B responsive module to application. I directly tried to get the value of media in my route like :

`export default Ember.Route.extend({

init(){
    console.log("initated", this.get('media.isMobile') ); // => true );
},

But not worked. then I created ajsfile atapp/breakpoints.js` and configured like:

`export default { mobile: '(max-width: 768px)', desktop: '(min-width: 769px)' }

`

But still my route gives this.get('media.isMobile') as undifed. now I am tryinng to inject my breakpoints to app. for that I try like this:

export function initialize(application) {
   application.inject('route', 'mockService', 'service:mock-service');
   application.inject('route', 'media', 'breakpoints');
}

export default {
  name: 'mock',
  name: 'media',
  initialize
};

But still getting error as :

TypeError: Invalid Fullname, expected: 'type:name' got: breakpoints how to solve this? and what is wrong I did here?




vendredi 25 août 2017

Can't get value of array inside computed property

I'm having trouble with a computed property in Ember.

The problematic item is timeZones, which is set like this:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return Ember.RSVP.hash({
      account: this.store.findRecord('account', params.id),
      timeZones: this.store.findAll('time-zone'), <------------ timeZones
      users: this.store.query('user', { by_account_id: params.id })
    });
  },

  setupController(controller, model) {
    this._super(controller, model.account);
    controller.set('users', model.users);
    controller.set('timeZones', model.timeZones);
  }
});

Then I have something called selectedTimeZone which looks like this:

  selectedTimeZone: Ember.computed('location.timezone', 'timeZones', function() {
    console.log(this.get('timeZones'));

    const timeZoneName = this.get('location.timezone');
    var result;

    this.get('timeZones').forEach(function(timeZone) {
      if (timeZone.name === timeZoneName) {
        console.log('yes'); // <------------------- never gets here
        result = timeZone;
      }
    });

    return result;
  }),

The problem is that this.get('timeZones') isn't really accessible inside the component. timeZones makes it to the template just fine. I'm populating a dropdown with timeZones right now. But when I console.log it, it just comes through as Class.

How can I get my hands on timeZones inside this computed property?




Can't figure out how to get x-select to have proper pre-selected value

I have the following time zone select field:

  x-select value=location.timezone class="form-control"
    each timeZones as |timeZone|
      x-option value=timeZone.name
        ' (GMT) 

The problem with the select field is that it doesn't pre-select the value of location.timezone. This isn't surprising. Each timeZone is an object, not a string, but timezone is a string.

How can I make this x-select match timeZone.name with location.timezone?




Ember query repeating same record over and over

I have an Ember route handler that looks like this:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return Ember.RSVP.hash({
      account: this.store.findRecord('account', params.id),
      timeZones: this.store.query('time-zone', {}),
      users: this.store.query('user', { by_account_id: params.id })
    });
  }
});

I also have a template that does this:

 each timeZones as |timeZone|
    '   ,

Even though I can tell the server is returning the right thing—149 time zones—my template just shows the last of these 149 time zones repeated 149 times.

What could be the cause of this issue?




Ember.js, Performances, Performances: VS

In this amazing video (https://www.youtube.com/watch?v=udix3GZouik) Alex Blom talks about "hacks" in Ember for mobile world.

At 22:00 he says something about <button onclick=()> vs simply .

enter image description here

Can you say something more about this? What he really means? Is today still like this?

It works just for <button> tag? And for <a>?




Is it possible to alias a computed property in a component from a controller?

I am trying to alias a computed property in a component from a controller. The component is called comments-sidebar.js

I have tried both of the following but neither of them worked.

unreadCommentsOrChanges:Ember.computed.alias('comments-sidebar.unreadCommentsOrChanges'),

unreadCommentsOrChanges:Ember.computed.alias('commentsSidebar.unreadCommentsOrChanges'),

Does anyone know the correct syntax for doing this or if it is even correct? I have not been able to find any similar examples online.




Track actions that are being triggered in application

Can someone think of a way in which the following is possible:

If a user triggers the following actions:

  • selectUser(action defined and handled in component)
  • closePrompt(action defined in controller, passed to component)
  • deleteAllUsers(action defined in component above, passed to child component)

Without manually adding code to each action, but rather inspecting some action "pipeline" of sorts when actions are triggered, and record them then. I've been looking at the code of the EventDispatcher, Action "modifier" and ActionManager to try and understand this better.




Ember Data incompatible with Rails JSON response: Encountered a resource with an undefined type

I'm trying to set up Ember Data to talk to a Rails backend. Ember succeeds at calling the endpoint, gets both a 200 and some response data. The problem is that Ember is unable to match the response data to one of my Ember models I've made.

My model code:

export default DS.Model.extend({
  user_id: DS.belongsTo('user'),
  transcription: DS.attr('string'),
  transcription_time: DS.attr('date'),
  transcription_date: DS.attr('date'),
  recording_url: DS.attr('string'),
  state: DS.attr('string')
});

Below is an image of how the backend returns data along with the error from Ember:

enter image description here

Error: Encountered a resource with an undefined type.

I don't need to include created_at or updated_at in my Ember models do I? Also, how does Ember know to connect user_id with my User Ember model? Is that what's causing the error? I specified user_id to belongTo('user') though. Do I need to explicitly include type field in my JSON response? This doesn't seem right though.

I've read a couple of Ember guides, including their guide on models and their guide on serializers. I don't need to write a custom JSONAPISerializer, do I? Most of the guides I read did not say to do this. Any help and tips would be greatly appreciated!




jeudi 24 août 2017

Ember Cli - Added Polyfill Internet Explorer Error Object Expected

I have a problem and I don't see someone who has this kind of problem with this. Basically I made a helper to format a date, it has some syntax of EcmaScript like let, or expoorts. Its working in all the browsers except INTERNET EXPLORER, so I though ok its time to configure Polyfill, so I read the documentation to configure it with ember-cli-babel and I am not able to see the results as expected.

I have an ember app, with ember cli

DEBUG: -------------------------------
DEBUG: Ember  : 2.14.1
DEBUG: jQuery : 2.2.4
DEBUG: -------------------------------

I include POLYFILL in my broccoli file like this ember-cli

var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    'ember-cli-babel': {
      includePolyfill: true
    },
    storeConfigInMeta: false,
    minifyJS: {
      enabled: false
    },
    minifyCSS: {
      enabled: false
    },
    vendorFiles: {
      'jquery.js': {
        development: 'bower_components/jquery/dist/jquery.js',
        production: false,
        development: false
      }
    }
  });

  app.import('vendor/jquery.lumanetix.all.min.js');

  return app.toTree();
};

I have a ember helper to format a date here it is:

import Ember from 'ember';

export function dateAuctionFormat(date/*, hash*/) {
  let dateObj = new Date(date);
  let monthName = getMonthName(dateObj.getUTCMonth());
  let dayNumber = dateObj.getUTCDate();
  dayNumber = dayNumber + formatDateNotation(dayNumber);
  let dayName = getWeekDayName(dateObj.getDay());
  let time = dateObj.toLocaleString('en-US', { hour: 'numeric', minute:'numeric', hour12: true });
  return dayName + ' ' + dayNumber + ' ' + monthName +  ' ' + time;
}

function getMonthName(date) {
  let month = [];
  month[0] = "Jan";
  month[1] = "Feb";
  month[2] = "March";
  month[3] = "April";
  month[4] = "May";
  month[5] = "June";
  month[6] = "July";
  month[7] = "Aug";
  month[8] = "Sept";
  month[9] = "Oct";
  month[10] = "Nov";
  month[11] = "Dec";
  return month[date];
}

function getWeekDayName(date) {
  let weekday = new Array(7);
  weekday[0] =  "Sunday";
  weekday[1] = "Monday";
  weekday[2] = "Tuesday";
  weekday[3] = "Wednesday";
  weekday[4] = "Thursday";
  weekday[5] = "Friday";
  weekday[6] = "Saturday";
  return weekday[date];
}

function formatDateNotation(d) {
  if (d > 3 && d < 21) {
    return 'th';
  }

  switch (d % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
}

export default Ember.Helper.helper(dateAuctionFormat);

But when Internet Explorer 11 is rendering the site, I have an error in the debugger like this: Error Image

The error said Object Expected. and you can see the error showing just after the line

export default App.extend({
  // rootElement: '#listings-search'
});

So I don't know from where start, I try to modify a little bit, app.js, but no luck, also I tried to convert my ES6 code to ES5 with this converter: http://ift.tt/1AQUemp

But of course it didn't work and also its not the idea.




Ember adapter unbiddenly changing model name from plural to singular

I have the following Ember adapter for a model called time-zone:

import Ember from 'ember';
import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  namespace: 'api/v2',
  pathForType: function(type) {
    // type here is "time-zone"
    return Ember.String.underscore(type);
  }
});

What I want is for my HTTP request to be sent to /api/v2/time_zones, but it's coming through as /api/v2/time_zone, which is wrong.

This is my model file:

import DS from 'ember-data';

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

And this is the relevant part of my routing file:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return Ember.RSVP.hash({
      timeZones: this.store.findAll('time-zone')
    });
  }
});

Adapting a name like timeZone or time-zone to an endpoint URI like /api/v2/time_zones seems like an extremely common use case for Ember, so I'm perplexed at the fact that what I'm trying isn't working.

I can do this and make it work:

    return Ember.String.pluralize(Ember.String.underscore(type));

But that seems like a silly hack for what again must be a super common use case.




EmberJS / Ember-data: hasMany collection incomplete, despite all IDs exist

A little perspective:

I have a service called menu that performs store queries inside computed properties. One of these store queries is behaving rather weird. It fetches all records under the model name product-segment from a fully functional JSON API. This model has a hasMany relationship to a model called product. I have checked the API's response - it is all good.

The problem:

Now, when I fetch these product-segment models, I instruct the API to { include: 'products' }, and the API does as is requested. The response includes 15 related product models, which is correct. However, access from the view only results in display of 12 models, so 3 are missing.

More perspective

I initially thought I was dealing with a race condition of some kind, and to be sure I created a computed property - test - to find out.

Here's the bare minimum info inside services/menu.js

export default Component.extend({

    activeProductSegment: null,

    productSegments: computed('store.product.[]', 'store.product-segment.[]', function() {
        return get(this, 'store').findAll('product-segment', { include: 'products' });
    }),

    test: computed('activeProductSegment', function() {
        let segment = get(this, 'activeProductSegment');

        if (segment) {
            console.log(segment.hasMany('products').ids());
            console.log(get(segment, 'products').mapBy('id'));
        }
    }),
});

The property activeProductSegment is being set to different product-segment model instances through an action of a component , which looks like this:

export default Component.extend({
    menu: inject(), // menu service is injected here...

    actions: {
        setProductSegment(segment) {
            get(this, 'menu').set('activeProductSegment', segment);
        }
    }
});

The action itself works as expected, and is actually quite unrelated to my problem. activeProductSegment is never updated in any other way. The view passes this action product-segment model objects:


    <li ></li>


Troubleshooting attempt

To come back to my problem, when I now try to get all related product models, only 12 of 15 models are present within the returned collection. To be sure that the JSON response was really fine I checked the amount of product IDs that one of my segment models contained, I logged the following line:

console.log(segment.hasMany('products').ids());

That returned me an array with 15 correct IDs, so the model has all id's as it is supposed to, and all product models of those id's have been included in the response. The following line however gave me an array of 12 id's:

console.log(get(segment, 'products').mapBy('id'));

I tried putting the 2 logs into a 2-second setTimeout, but the result stayed identical:

This is the 2 logs

Unless I misunderstand, the models should be live, so any relationship is supposed to update as data becomes available. What am I doing wrong?

I've been tearing my hear out because of this :O




ember-cli-mirage skips the use of a serializer

i have a question about ember-cli-mirage.
i'm doing the frontend work in an application and setting up mirage to mock the backend while it's being made. my problem is the following:
i have two models (as an Ember and a Mirage model too) category and subcategory. category hasMany() subcategories while subcategories belongsTo() a category. now, the backend expects a GET request for subcategories to /api/v2/categories/:slug/subcategories so i made a serializer for category to modify the default Mirage behaviour from GET /api/v2/subcategories/:id. this is what i did last time i faced a similar API and it worked then.

here is the file:
mirage/serializers/category.js

import { JSONAPISerializer } from 'ember-cli-mirage';

export default JSONAPISerializer.extend({
  links(category){
    return{
      'subcategories': {
        related: `/api/v2/categories/${category.slug}/subcategories`
      }
    };
  }
});

but when running it, it still tries to fetch it from /subcategories/:id and gives the following error:

Mirage: Your Ember app tried to GET '/api/v2/subcategories/1',
         but there was no route defined to handle this request.
         Define a route that matches this path in your
         mirage/config.js file. Did you forget to add your namespace?

i only use subcategories in the category template:

category.hbs


  


and here is mirage/config.js

this.get('/categories');

this.get('/categories/:slug', function(schema, request) {
    let slug = request.params.slug;
    return findBySlug(schema.categories, slug, 'category');
  });

  this.get('/categories/:slug/subcategories', function(schema, request) {
    let slug = request.params.slug;
    let category = findBySlug(schema.categories, slug, 'category');
    return category.subcategories;
  });

//this.get('/subcategories/:id');

of course, if i enable the last line i don't get the error and get the data but not from where i want it.

any ideas or help would be very much appreciated!




When I install ember and execute ember server. appear this: node_modules appears empty. I'm working on PC win10 x64

Command console:

C:\Users\Documents\emberjs>ember server
node_modules appears empty, you may need to run `npm install`

I'm new in Ember,Any help will be appreciated. Thanks in advance!




Small issue with the way I should call several plug-in for ember-cli-jstree


as the title say I have a small problem. I can't figure out how to call multiple plug-in of ember-cli-jstree. Right now, I have that

export default Ember.Component.extend({
    "plugins" : "dnd",
    data: 
      [...],
});

Here, I can use the plug-in drag and drop, but if I want to use several plug-in, how should I write it?
I already tried:
    "plugins" : "dnd", "type",
    "plugins" : {"dnd", "type"},
    "plugins" : ["dnd", "type"],
    "plugins" : "dnd" + "type",

Maybe I'm dumb or something, but I can't figure it out.


Ember model fields with number don’t get underscored properly

I have some fields in my order model: address1 and address2. They need to be sent to my API as address_1 and address_2.

When I run Ember.String.underscore inside of keyForAttribute I get:

Ember.String.underscore('address1')
"address1"

Any ideas how I can explicitly tell Ember what to do with these?




Access a ember service from mirage config.js

How can I access an ember service from within mirage config.js? I tried 2 ways, but both are not working:

Try 1:

// mirage/config.js
export default function() {
  this.get('/post', function(schema, request) {

    let mystore = Ember.inject.service('mystore');

    // ..
  });
}

Try 2:

// mirage/config.js
export default function() {
  this.get('/post', function(schema, request) {

    let mystore = Ember.computed(function() {
      return Ember.getOwner(this).lookup('service:mystore');
    });

    // ..
  });
}




How to keep separate folder for desktop and mobile?

I am trying to keep 2 separate template folder(s) for desktop and mobile. But I am not able to figrueout the correct way.

Any one help me for this?

If I am wrong, please correct me.

here is my requirement what I looking for :

enter image description here

Twiddle




mercredi 23 août 2017

put a HTML element over a map tile

When I was working with ember-leaflet v2.2.7, the HTML elements were displayed over the map tiles like in the picture below, but in the version 3.0.11 the map is in the front.

ember-leaflet v2.2.7 and v3.0.11

Setting the z-index of the leaflet-container element to -1 the map is pushed to the back but the map is inaccessible, I mean, the map cannot be zoom-in/out or the tooltip of the marker is not displayed when it is tapped.

In v3.0.11 the button element is like hidden, I mean when the map tiles are loading the button is visible (see picture below) but when the tiles are loaded the button disappears but if it's location is tapped the action related with the button is triggered.

map tiles loading




template is not a function - EmberJs/ROR Application

I'm getting this error when loading the app via browser. Not sure what's wrong.

ember:7062 Uncaught TypeError: template is not a function
    at renderLegacyTemplate (ember:7062)
    at renderView (ember:7026)
    at renderView (ember:33679)
    at Class.render (ember:33702)
    at EmberRenderer_createElement [as createElement] (ember:35727)
    at EmberRenderer.Renderer_renderTree [as renderTree] (ember:7699)
    at EmberRenderer.scheduledRenderTree (ember:7774)
    at invoke (ember:879)
    at Queue.flush (ember:944)
    at DeferredActionQueues.flush (ember:749)




How can I load ember model after successful ajax call in Emberjs?

I have defined a model called todo.js in app/models like this:

export default DS.Model.extend({
  title: DS.attr('string'),
  created_at: DS.attr('date'),
  updated_at: DS.attr('date'),
  is_deleted: DS.attr('boolean'),
  is_done: DS.attr('boolean')
});

Let's say I don't want to use to ember-data & I simply want to use plain old ajax like this:

export default Ember.Route.extend({
  model() {
    return Ember.$.getJSON('http://localhost:3001/todo').then((data) => {
       // How would I load the data into the model here?
    });
  }
});

How would I load the data I am getting from the successful ajax call into the model?

I have defined a component to show todos like this:

<ul>
  
    <li></li>
  
</ul>

And here's the router.js:

Router.map(function() {
  this.route('todos');
  this.route('todo', { path: '/todo/:todo_id' })
});




How to pay with credit / debit card in paypal checkout?

I successfully integrated Paypal as payment method in my website through APIs. Here is the code:- frontend:

paypal.Button.render({
        env: self.get('paypalEnv'), // 'production' Or 'sandbox'
        commit: true, // Show a 'Pay Now' button
        payment: function() {
            return paypal.request.post(self.get('creationUrl')).then(function(data) {
                return data.id;
            });
        },
        onAuthorize: function(data) {
            return paypal.request.post(self.get('executionUrl'), {
                paymentID: data.paymentID,
                payerID: data.payerID
            }).then(function() {
                // The payment is complete!
                // You can now show a confirmation message to the customer
            });
        }
    }, '#paypal-button3');

backend:

module PortalPaypalPaymentService
    def self.create_payment(request)
        #debugger
        price_in_egp = request.initial_price
        output = CurrencyExchange.convert(price_in_egp*100, 'EGP', 'USD')
        price_in_usd = (output.cents/100.0).round(2)
        params = {
            "intent": "sale",
            "redirect_urls": {
                "return_url": APP_CONFIG['paypal_return_url'],
                "cancel_url": APP_CONFIG['paypal_cancel_url']
            },
            "payer": {
                "payment_method": "paypal"
            },
            "transactions": [{
                "amount": {
                "total": price_in_usd,
                "currency": "USD"
                }
            }]
        }
        response = send_request_post(PAYMENT_URL, params)
        JSON.parse(response.body)["id"]
    end

    def self.execute_payment(payment_id, payer_id)
        params = {
            payer_id: payer_id
        }
        response = send_request_post(PAYMENT_URL + '/' + payment_id + '/execute', params)
        JSON.parse(response.body)
    end
end

This is working perfectly. However, I want to enable customer to pay via credit / debit cards. My question is How to enable that from frontend and backend?

Thank you in advance.




Cant clear the selected option from ember-power-select

I am using the ember-power-select library link here --> ember-power-select

When I select a value from the power-select and then re-draw the div:


  <div class="col-md-4">
    
  </div>


..controller

vm.set('condition', false);

 Ember.run.later((function () {
      vm.set('condition', true);
    }), 100);

the selected value stays the same.

The behavior that I expect is that the selected option inside power-select will be deselected.

How do I achieve that?




After ember updates the login no longer works

After I have updated some versions, the login no longer works. I get the following error.

Anyone an idea why?

My package.json Updates

My Code in new.js:

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

 // Delete all existing sessions to avoid conflicts in the store
 store.destroyRecord('user_session');

 // Create new session object
 let userSession = store.createRecord('user_session', {
                email: this.get('email'),
                password: this.get('password')
 });

 // Save new session object (authentication on the server)
 userSession.save().then(
                () => {
                    // Authentication successful, store session and go to the dashboard
                    this.get('session').registerUserSession(userSession);
                    this.transitionToRoute('dashboard');
                },
                (e) => {
                    // Authentication failed
                    Ember.Logger.error('Login failed', e);

                    // TODO translate
                    this.get('toast').error('Login failed');
                }
 );




`active` class not switching based on `route` update

on load of new route the active class not switching to new tab. I am not able to find the solution for this.

but the new page is loading without any issue. the only issue is the active class not switching to new page and not remove from the old page.

how to fix this?

here is my hbs file :

<div class="navbar-sub-header navbar-sub-header---tab-bar" style="border:1px solid red;">
        <div class="rdc-tab-bar">
            
                Credit Card //by default active added
            
            
                Online Baning //when click page loads, active not swithing
            
        </div>
    </div>

my router.js :

 this.route('auth-page', function() {
    this.route('credit-card', function() {
      this.route('credit-cardno');
      this.route('credit-otp'); //works fine
    });
    this.route('i-banking'); //not updating to active state
  });




Pass value from `route` to template

I am trying to pass a value from route to template. But I am not able to get the result. how to pass the value from route to template.

here is my try:

my route.js :

import Ember from 'ember';

export default Ember.Route.extend({
  name:"SCB"
});

here is my hbs file :

<h1>My Name is : </h1>

Live Twiddle




mardi 22 août 2017

Ember.js component with HTML input range does not set value correctly

I have a simple Ember component that only contains a single input range slider, like so:

<input
  type="range"
  value=500
  min=0
  max=500
>

When it renders initially, the slider's position is not set to the very end as you would expect. It is set at around the 100 position.

enter image description here




Cannot call set with

I am trying my hands on ember js and I am not able to use multiple models within models,

model/client.js
export default DS.Model.extend({
  person: DS.belongsTo('person', {async: false, inverse: 'client'}),
  postalAddress : DS.belongsTo('address', {async: false}) ,
  residentialAddress : DS.belongsTo('address', {async: true})  ,
  personName: DS.attr('string'), //added from person
  greeting : DS.attr('string') //added from person
  });
model/person.js
export default DS.Model.extend({
  name : DS.attr('string'),
  personName : DS.attr('string'),
  greeting : DS.attr('string')  ,
  client: DS.belongsTo('client', {inverse: 'person'})
});

My Route routes/client/create

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({

        'client': this.get('store').createRecord('client'  ,
          { //does this not initialize person
            person: 'person', address: 'address'
          } ),
        // )
//does this not initialize person
          'person': this.get('store').createRecord('person',{
            client: 'client'
          }),
          'address': this.get('store').createRecord('address')
      }
    );
  }
});

my template has only one line :



in my client-form.hbs i had some fields that referred to client.person.personName or client.person.greeting, and when i would type the first character I would get for greeting or personName

Assertion Failed: Cannot call set with 'greeting' on an undefined object.

So I added personName and greeting in client model directly as well and added two fields referring to client.personName and client.greeting and those fields dont give me any issue. I believe that the person model is not initialized and perhaps the client is instantiated but person and address is not and person is an undefined object.

The reason for such a model is that I have a java backend and my ClientDTO looks like:

public class ClientDTO /*implements IsSerializable*/ {

    private PersonDTO personDTO;
    private AddressDTO postalAddress;
    private AddressDTO residentialAddress;

Where have i missed initializing the person and address, I can find ppl having errors "cannot call get on undefined" but not in set.




Maximum Call Stack Size Exceeded Ember Mirage CLI

I am working with Ember 2.0, and I'm trying to correctly set up a many to one relationship with my model. I am using ember-mirage-cli to simulate the backend, and send me data. I have been struggling with this for quite some time, and looked at the marked issues on the ember-cli-mirage github. I saw similar issues that were marked as resolved, but no one posted a direct answer on how to fix this error. I was hoping someone on here could point out the error that I have in my setup... It is currently complaining about a Maximum Call Stack Size Exceeded.

app/models/parent.js

import DS from 'ember-data';

export default DS.Model.extend({
    childEntries : DS.hasMany('child-entry'),
});

app/models/child-entry.js

import DS from 'ember-data';

export default DS.Model.extend({
    parent: DS.belongsTo('parent')
});

mirage/models/parent.js

import { Model, hasMany } from 'ember-cli-mirage';

export default Model.extend({
    childEntries: hasMany('child-entry'),
});

mirage/models/child-entry.js

import { Model, belongsTo } from 'ember-cli-mirage';

export default Model.extend({
    parent: belongsTo()
});

mirage/scenarios/default.js

export default function(server) {
  server.create('parent', 'withGeneratedChildren');
}

mirage/factories/parent.js

import Mirage, { Factory, faker, hasMany, trait } from 'ember-cli-mirage';

export default Mirage.Factory.extend({
    childEntries: hasMany('child-entry'),

    withGeneratedChildren: trait({
        afterCreate(parent, server) {
            parent.update({
                childEntries: server.createList('childEntry', 10, {parent: parent})
            });
        }
    }),
});

mirage/factories/child-entry.js

import Mirage, { faker, association, trait } from 'ember-cli-mirage';

export default Mirage.Factory.extend({
    parent: association()
});




Ember.JS change handlebars operators

is it possible to change the way the handlebars mustache binding is working within Ember? My case is that I want to use Ember within metalsmith.IO static site builder which is already using handlebars, so when the template is being built binding is being interpreted by handlebars instead of ember.

My template:

<!DOCTYPE html>
<html xmlns="http://ift.tt/lH0Osb" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://ift.tt/zbanWc" dir="ltr"
  lang="en-US">

<head>
  
  <title></title>
  <meta name="description" content="">
  <!-- Typekit Javascript -->
</head>

<body class="stretched no-transition">
  <!-- Document Wrapper
    ============================================= -->
  <div id="wrapper" class="clearfix">
    <div id="header-trigger"><i class="icon-line-menu"></i><i class="icon-line-cross"></i></div>
    <!-- Header
        ============================================= -->
    <header id="header" class="transperent-header full-header no-sticky">
      <div id="header-wrap">
        <div class="container-fluid clearfix">
          <div id="primary-menu-trigger"><i class="icon-reorder"></i></div>
          <!-- Logo
                    ============================================= -->
          
          <!-- #logo end -->
          <!-- Primary Navigation
                    ============================================= -->
          
          <!-- #primary-menu end -->
        </div>
      </div>
    </header>
    
    <!-- Slider  start -->
    
    <!-- Slider end -->
    
    <!-- No Slider -->
    <!-- No Slider end -->
    <!-- Content
        ============================================= -->
      <h2>Welcome to Ember.js</h2>

      

      <ul>
        
        <li></li>
        
      </ul>

    <section id="content">
      <div class="content-wrap notoppadding nobottompadding">
        
        <div class="container notopmargin bottommargin clearfix">
          <p align="right"><small>&mdash; }</small></p>
        </div>
        <!-- To be Done: implemet metalsmith tags module -->
        
        <div class="container bottommargin clearfix">
          <p><small>}</small></p>
        </div> 
      </div>
      <div class="content-wrap notoppadding nobottompadding">
        <!-- No Background Image -->
        
        <div class="container bottommargin clearfix">
          <blockquote>}</blockquote>
        </div>
            
        <div class="container bottommargin clearfix">
          }</div>   
        <!-- Footnotes -->
        <!-- To be Done: "back to top" links in footnotes or switch to a custom module -->
        <div class="container bottommargin clearfix">
          <h2 class="visually-hidden" id="footnote-label">Footnotes</h2>
          <ol class="post-footnotes">}</ol>
        </div>
        
        <!-- Footnotes End -->
      </div>
    </section>  </div>
  <!-- #wrapper end -->
  
</body>

</html>

My Ember part that I have problem with is :
  <h2>Welcome to Ember.js</h2>

  

  <ul>
    
    <li></li>
    
  </ul>

Unfortunatel only the H is being rendered, nothing from is as handlebars is trying to interpret it before Ember has a chance.




Create a new user using emberfire

I am writing a EmberJS web application. I want to create and authenticate the user using firebase. I am using the emberfire

http://ift.tt/1w7fh3T

I am not able to create a user using the emberfire. There is no info regarding user creation.

Any thoughts?

Thanks




How to add the number with `index` in `hbs` template

I am trying to add a number with existing index but getting error. how to solve this?

here is my try : both tabindex="",class="digit" throw error.


            <input type="number" tabindex="" min="0" max="9" maxlength="1" value='' 
                onKeyUp= 
                onKeyPress= class="digit" >
        




Using EmberJS in metalsmith.IO

I need to use EmberJS within an already existing codesmith.IO project that previously was using Angular 1. I feel like I'm missing something simple in terms of implementing that, and since I've always used Ember CLI to generate the template for a new app I'm a bit lost in terms of what is actually needed for Ember to run within an enviroment like codesmith which is a regular static site generator.

If anyone could enlight me on where I'm overcomplicating the implementation in my head I'd be more than grateful :-)




lundi 21 août 2017

ember data relationships with same model used twice

I have an ember application with a Java Spring boot back end.

I tried the whole with simple objects and it worked fine. Now I wanted to make it a bit more complex like a real world scenario.

I have a clientDTO which looks like this

public class ClientDTO {


    private PersonDTO personDTO;
    private AddressDTO postalAddress;
    private AddressDTO residentialAddress;

My ember Models look like this.

import DS from 'ember-data';
//client.js
export default DS.Model.extend({
  person: DS.belongsTo('person', {async: false, inverse: 'client'}),
  postalAddress : DS.belongsTo('address', {async: false}) ,
  residentialAddress : DS.belongsTo('address', {async: true})
  });
//address.js
export default DS.Model.extend({
  line1: DS.attr('string'),
  line2: DS.attr('string'),
  postCode: DS.attr('string'),
  suburb: DS.attr('string'),
  client: DS.belongsTo('client')
});
//person.js
export default DS.Model.extend({
  name : DS.attr('string'),
  personName: DS.attr('string'),
  identificationNumber: DS.attr('string') ,

  client: DS.belongsTo('client', {inverse: 'party'})
});

I can define the address as an Arraylist with hasMany in the ember but that does not serve the purpose I need to have two different addressDTO objects bind with ClientDTO.

When I try to run the ember application and even load an empty /createNewClient form it gives me

ember.debug.js:17636 Assertion Failed: You defined the 'client' relationship on fo-ui@model:address:, but multiple possible inverse relationships of type fo-ui@model:address: were found on fo-ui@model:client:. Look at http://ift.tt/1aomJhS for how to explicitly specify inverses
Error

which is understandable, if i remove one of the addresses from the client.js model it works. So how can i have multiple models of the same model. As i understand there should be one 'address' model. i dont think i should need two address model one for residentialAddress and one for postalAddress. That would seem redundant.




ember-cli-code-coverage mocha showing 0% coverage when there are tests

I'm using ember-cli-code-coverage with ember-cli-mocha. When I run COVERAGE=true ember test I'm getting 0% coverage for statements, functions, and lines. Yet, I have tests that are covering those sections. Any I missing something in my setup?

enter image description here

unit test file:

  beforeEach(function() {
    controller = this.subject();
  });

  it('sets selectedImage to null', function() {
    expect(controller.get('selectedImage')).to.eql(null);
  });

  describe('setCoverageTest', function() {
    it('sets selectedImage to true', function()  {
      expect(controller.get('selectedImage')).to.eql(null);
      controller.setCoverageTest();
      expect(controller.get('selectedImage')).to.be.true;
    });
  });

config/coverage.js:

module.exports = {
  excludes: ['*/templates/**/*'],
  useBabelInstrumenter: true
};




EmberCLI runtime configuration

We're running an EmberCLI application in our infrastructure, and I'm tasked to make it work better with the rest of our services. One thing that's a bit interesting about EmberCLI is that all it's configuration variables are baked into the build by default. (Specifically in the <meta> tag).

I had trouble finding a way to supply runtime configuration. We have an "API_URL" environment variable that's supplied to all our services so they can find the API. What is the recommended way to supply this url to EmberCLI at run-time, so I can avoid a rebuild and have fully-built docker containers with our frontend application.




Ember js 2, Using scss @import in my app.scss production doesn’t remove comments in final css

In my app.scss file I'm using

@import "./node_modules/bootstrap/scss/bootstrap";

because I'm using (and sometimes changing) some Bootstrap variable into my app.scss.

I found that with ember build -prod it doesn't remove comments from within Bootstrap imports in my final app.css.

So in my production css I have this:

/*!
 * Bootstrap v4.0.0-beta (http://ift.tt/18L5oJl)
 * Copyright 2011-2017 The Bootstrap Authors
 * Copyright 2011-2017 Twitter, Inc.
 * Licensed under MIT (http://ift.tt/1nE3KCd)
 */address,dl,ol,p,ul{margin-bottom:1rem}body,caption{text-align:left}........

Why?

How can I remove those superfluous comments?




Ember JS component accessing store

I would like to know if it considered good practice in Ember.js to inject the ember data store in a component to be able create/delete records directly from the component instead of bubbling up to the route controller.




Tracking Blocker on Firefox broke my web app

It's kinda weird or it's just me. I am building an app using ember and it works properly in most browser. But when i used firefox in private mode (with tracking blocker enabled) it just froze. I knew that this is related to the resources i had like Google analytic or Facebook. I already tried to remove it but the problem still remain.




Can't undestand why ember tests working so strange

I can't understand why my emberjs test code runs so strange. I wrote a test which should only select some html elements and give me number of them. This code works:

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

  // if i remove this andThen test becomes failed
  andThen(function(){
    find(".feedback-item");     
  });
  
  andThen(function(){
    assert.equal(find(".feedback-item").length > 0, true, "There are more than 0 feedback");
  });

  click(".feedback-item:first a");

  andThen(function() {
    assert.equal(currentURL(), '/feedback/1', "New URL is /feedback/1");
  });
});

But the same code but without (if i delete / comment it) this part andThen(function(){ find(".feedback-item")}); doesn't work. It throw's an exception: Element .feedback-item:first a not found.




How to watch properties in `router` on change?

In my app, user setting the 6 seperate digits. they can delete/re-enter/enter the values in input. controller sending this values to router.

when router watches all this properties, then it will take user to next page. my question is how to watch the properties ( specified properties ) and react accordingly?

here is my router code ( snippet ):

    export default Ember.Route.extend({

example//
myWatcher(){
console.log('all proeprty available enable next')
},

        setupController(controller,model) {
            this._super(controller, model);
            this.controllerFor('auth-page.credit-card.credit-cardno').set('enableNext', false); 
        },

        otp1:null,
        otp2:null,
        otp3:null,
        otp4:null,
        otp5:null,
        otp6:null,

        actions:{
            setupCardNumber( number, index ){
                this.set('opt'+index, number ); //setting values
                console.log( 'setting', this.get('opt'+index) );//gets properly
            },




how can I implement Mosaico into Ember application?

I'm beginner Ember developer and now I try to implement Mosaico.io into my Ember application. Previously, I used CKEDITOR. I joined to my index.html file like this:

<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>

and then I used create() action in controller for getting text of message like this:

create() {
  let model = this.get('model');
  let kind = this.get('model.kind');
  if (kind !== 'sms') {
    model.set('message', CKEDITOR.instances['campaign-content'].getData());
  };
  model.save().then(() => {
    return this.transitionToRoute('campaigns.index');
  });

But I don't understand, how can I manage with Mosaico. Does anybody have idea, how can I implement Mosaico into Ember application?




`keyUp` not working, what is the correct way to trigger a keyup on input field

I am trying to integrate a keyup event in my input element. but not works at all. any one help me to showing the correct way to trigger an event?

here is my hbs file:

<span class="opt-num">
            <input type="number" tabindex="1" min="0" max="9" maxlength="1" value="" onKeyUp= style="border:1px solid red" >

        </span>

my route.js file :

actions:{

        numberValidate(){ console.log("hi") }
}

But getting error as : Failed: An action named 'numberValidate' was not found




bootstrap@4.0.0-beta install issue for the Ember js

Im try to installbootstrap@4.0.0-beta for the Ember js application im used following method npm install bootstrap@4.0.0-beta,but its not work for my projects, anyone know how to install correctly Ember js for the bootstrap@4.0.0-beta

Boostrap 4 beta> http://ift.tt/PPrDZs

Thanks




dimanche 20 août 2017

cp-validation not working as expected

I am integrating the cp-validaiton with my ember app. but I am not getting any response. any one help me here.

my route js :

import Ember from 'ember';
import Validations from '../validation'

export default Ember.Route.extend(Validations, {
  num:null,
    message: '',
  model(){
    return { num:null}
  },
  actions:{ 
    check(){
        this.set('message','');

      this.validate().then(({model, validations})=>{
        if(validations.get('isValid')){
          console.log('statge', validations.get('isValid') )
                    this.set('message','');
                }else{
        if(model.get('validations.attrs.num.isInvalid')){
                        this.set('message',model.get('validations.attrs.num.messages'));
                    }
        }
      })
    }
  }
});

my validation.js :

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

export default buildValidations({
    num: [
        validator('number',{
        allowString: true,
        integer: true,
        message: 'Error! This is not an integer!'
}),
    validator('presence', true)
]
});

template :

<h1>This is my Route</h1>

Enter Age:<br>
<br>
<div style='color: red'><br></div>
<button >Check</button><br>

Live in Twiddle




EmberJS nested subroute custom index path not working as expected

I'm following one of the Ember Guides on routing (v2.14.0) and I'm trying to set up a nested sub-route where the index route should redirect to a different subroute.

Router.map(function() {
  this.route('about');
  this.route('dashboard', function() {
    this.route('index', { path: '/dashboard/calendar'});
    // ^should direct all dashboard index requests to dashboard/calendar right?
    // setting path = '/calendar' also doesn't work

    this.route('calendar');
    this.route('daily-journal');
  });
});

However when I load up http://localhost:3000/dashboard, I get this error: enter image description here

Any ideas what I did wrong?




Correct way to import all assets from external library with Ember CLI

I'm working on an Ember.js project and would like to leverage the Slick Carousel library. I've installed the library via Bower in my project folder, and am having difficulty with importing it into my project.

In my ember-cli-build.js, I've added import statements as follows:

app.import('bower_components/slick-carousel/slick/slick.css');
app.import('bower_components/slick-carousel/slick/slick-theme.css');
app.import('bower_components/slick-carousel/slick/slick.js');

The issue I am running into is that the rest of the required assets do not get built and included in the dist folder when I do a build (fonts, assets, etc.), leading to errors with missing fonts and assets that are present in the "bower_components/slick-carousel" folder, but not in the build of my actual Ember application.




ember-bootstrap: Navbar component repeats itself 12 times

I am using ember-bootstrap's Navbar example code in a simple Ember test app:


  <div class="navbar-header">
    
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  
    
      
        Home
      
      
        Navbars
      
    
  


However I'm having strange results; the navbar is showing up 12 times in my page. For what it's worth, the toggle button doesn't do anything either - but that might be connected to the reason the navbar appears 12 times. See the following screenshot:

Screenshot from simple test page

Here are the steps I took to set up this project:

  1. ember new bootstrap-test
  2. Inside /bootstrap-test:
    1. ember install ember-bootstrap
    2. ember g ember-bootstrap --bootstrap-version=4

Here is the contents of my ember-cli-build.js file:

/* eslint-env node */
'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    'ember-bootstrap': {
      'bootstrapVersion': 4,
      'importBootstrapFont': false,
      'importBootstrapCSS': false
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};

Finally, I'm using ember-cli version 2.14.2. Any help to figure this out would be greatly appreciated. Thank you!




samedi 19 août 2017

Ember light-table sorting column

I would like to sort a table by column. This works as expected but the icons for ascending is displayed at every 3rd click.

This is my code (working with ember 2.14):

export default Ember.Component.extend({

  model: null,
  table: null,

  sortProps: ['lastName:asc'],
  sortedPeople: computed.sort('model', 'sortProps'),

  columns: computed(function() {
    return [{
      label: 'Vorname',
      valuePath: 'firstName',
    }, {
      label: 'Nachname',
      valuePath: 'lastName',
    }];
  }),

  table: computed('sortedPeople', function() {
    return new Table(this.get('columns'), this.get('sortedPeople'));
  }),

  actions: {
    onColumnClick(column){
      let dir = column.ascending ? ':asc' : ':desc';
      this.setProperties({
        sortProps: [ column.get('valuePath') + dir ]
    });
  }
)};




When running a HTTP server using Tornado with content generated using Ember cannot refresh page

Note: I am new to Tornado.

To recreate my problem I have the following Python file:

import tornado.httpserver
import tornado.ioloop
import tornado.web

class IndexHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.render("dist/index.html")

def start_server():
    app = tornado.web.Application([
        (r'/', IndexHandler),
        (r'/assets/(.*)', tornado.web.StaticFileHandler, {"path": "dist/assets"}),
    ])

    ioLoopInstance = tornado.ioloop.IOLoop.instance()

    http_server = tornado.httpserver.HTTPServer(app, io_loop=ioLoopInstance)
    http_server.listen(34567)
    ioLoopInstance.start()

if __name__ == '__main__':
    start_server()

I then have an Ember project that has two routes (/route1 and /route2) with one button on each which just transitions to the other route, and an application route that transitions to route1 in beforeModel. I copy the dist directory generated by Ember to the directory which contains the Python file above. When I run the Python file and navigate to localhost:34567 this automatically transitions to localhost:34567/route1, I can then press the buttons to navigate between pages fine. However, when I refresh the page or enter localhost:34567/route1 in the address bar I get a "404: Not Found" page. What am I missing from my Tornado setup?

Thanks




Ember,js. Modify app.js and vendor.js before the final integrity seal. One custom step in build pipeline?

I need to change something in my final

app.js and vendor.js

but obvioulsy I need to modify them before the ember-cli-sri integrity http://ift.tt/2fVnVlP does its job.

How to do?

There are somewhere the pipeline steps?

Can I insert one step before the final one?




ember computed not being updated

i have a computed property in ember

  isCurrentUserLikeIt: Ember.computed('likestatuses.@each.user_id', function () {
    const userId = parseInt(this.commonService.getId());
    const likestatuses = this.get('likestatuses');

    return likestatuses.filterBy('user_id', userId).get('length') !== 0;
  })

the computed property must be updated when user invoke an action.

this.doSave("likestatus", likestatus).then(function (result) {
        if (result.userlike) {
          const likestatuses = context.get('likestatuses');
          likestatuses.push(likestatusItem);
          context.set('likestatuses', likestatuses);
        } else {
          const likestatuses = context.get('likestatuses').filter(function (item) {
            return item.user_id !== userId
          });
          context.set('likestatuses', likestatuses);
        }

        context.debug(context.get('likestatuses'));
      });

the isCurrentUserLikeIt property is updated when the statement in this.doSave, is in else. but when the statement is in if (result.userlike) the isCurrentUserLikeIt property did not change :(

can anyone solve this




vendredi 18 août 2017

How to take input from template and store it in javascript variable in Ember?

I tried like this

app/template/print-dept.hbs

<form action="/print-dept-wise">
Department: <input type="text" id="dept"><br/><br/>
<input type="submit" value="Submit">
</form>

app/template/print-dept-wise.hbs


Employee Id:  <br/>
First Name:  <br/>
Last Name:  <br/>
Employee Dept:  <br/>
<br/>


app/route/print-dept-wise.js

import Ember from 'ember';

export default Ember.Route.extend({
model() {
var text = document.getParameterById("dept");
return Ember.$.getJSON('http://localhost/EmpDir/app/jsonRes/jsonR/'+text);
}
});

But it is not work as i expected

how can i change last part of my JSON url depending on user input?




Ember syntax to get element by ID not working

My HTML template is a basic:

<h1>Upload Photo</h1>

<form >
  
  <button type="submit">Upload</button>
</form>

I have this in my controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  firebaseApp: Ember.inject.service(),

  actions: {
    upload() {
      console.log('Uploading photo from controller');
      var storageRef = this.get('firebaseApp').storage().ref();

      // var selectedFile = Ember.$('#image').files[0];
      var selectedFile = document.getElementById('image').files[0];

      console.log('selectedFile = ', selectedFile);

      // var photoRef = storageRef.child('ember-mascot.png');
    }
  }
});

If I use the normal javascript way:

var selectedFile = document.getElementById('image').files[0];

It works, I get a console log of the file.

However, if I use Ember's syntax of retrieving file:

var selectedFile = Ember.$('#image').files[0];

I get a javascript console error:

TypeError: Cannot read property '0' of undefined

If I use:

var selectedFile = this.$('#image').files[0];

I get this error:

TypeError: this.$ is not a function

According to this Stackoverflow answer:

Getting element by ID in Ember

Ember.$() or this.$() should work but it isn't for some reason.




How can a component obtain a value synchronously from its parent?

Consider the following Ember component which is using Semantic UI:

import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['ui', 'mini', 'modal'],
  didInsertElement() {
    this.$().modal({
      onApprove: () => {
        let promise = // obtain promise from parent... somehow
        promise.then(() => {
          this.$().modal('hide');
        });
        return false;
      }
    });
  }
});

The modal dialog is initialized as soon as the element is accessible. The onApprove option specifies a callback to be invoked when the user clicks "OK" in the dialog. The component's parent supplies an Ember.RSVP.Promise, which when resolved, closes the dialog.

Herein lies the problem — how do I obtain the promise from the parent? I considered the following possibilities:

  • The parent could supply an action to be invoked:

    
    
    

    However, actions cannot return values, so although the component could invoke the action, it could not use it to obtain the promise.

  • The parent could supply the promise as a bound property:

    
    
    

    The problem with this approach is that didInsertElement() cannot obtain the promise itself since the component must wait for the promise property to mutate.

Is there a way for a component to ask the parent for a value in a synchronous manner?




Ember CLI: Broccoli Funnel not copying files

I have several JSON files in my Ember project in a directory called data within the app directory:

App directory structure

I am attempting to copy these files into another data directory within the public directory using a Broccoli funnel. However, when running ember serve, the files are not copied and no errors are reported. After reading the answer to this question, I started using broccoli-merge-trees which did not fix the issue.

/* eslint-env node */
'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');
const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    // Add options here
  });

  var json = new Funnel('app/data', {
      destDir: 'public/data',
      include: ['*.json']
  });

  return new MergeTrees([json, app.toTree()]);
};

Empty public/data directory after running ember serve




ember adapter pass id

I want to be able to pass an id to rest point while using ember data. My end-point looks like v3/enterprise/inventory/items/{id}/links. I want to inject the id while making the request such as this.store.findAll('each-item-links', { id: itemId }). However, it does not work. I extended the Ember REST adapter and override the namespace but nothing seems to be working.




ember, nginx, reverse proxy

I have my app deployed to a file server here at: http://ift.tt/2fR3TsO

We want our app to be facing at: http://amazingapp.com

So far this is what I have on nginx

server {
  listen 80;
  server_name http://amazingapp.com;
  location / {
      proxy_pass http://ift.tt/2fR3TsO;
  }
}

This works for initial http://amazingapp.com but any subsequent requests http://ift.tt/2id2MnV result in 404

Most of the ember deploy examples have the file being served from the same location as the web server, using try_files $uri $uri/ index.html So i don't believe i'm able to go down that path?

I've tried using regex on the location but that requires the proxy_pass to have parameters.

If you could point me in the right direction would be so grateful. Thanks in advance!




Object.values throws TypeError in IE browser

In my ember app,I am using Object.values method, which is throwing the below error in IE browser.

Object doesn't support property or method 'values' TypeError: Object doesn't support property or method 'values'

In my package.json

"ember-cli-babel": "^6.3.0" 

my target.js file shows,

module.exports = {
  browsers: [
    'ie 9',
    'last 1 Chrome versions',
    'last 1 Firefox versions',
    'last 1 Safari versions'
  ]
};

I am using

ember-cli: 2.13.3
node: 6.3.1

Object.values is supported only in EDGE. How do I polyfill this in my ember project?. Similarly for String.endsWith I just the included the polyfill in app.js file. Here I want to use babel-polyfill so that it will automatically polyfill for the browser I mentioned in target.js




Ember observer when session is active on page load

I am writing a EmberJS web application. I have a piece of code which should run only when the page has completed loaded and the session authentication is complete.

I tried setting an observer on session.isAuthenticated but it does not seem to be working.

Any thoughts?

Thanks