mardi 28 février 2017

Sahrethis emberJs

I want to add sharethis in emberjs templates. After a lot of test i manage to make it work by adding the script tag inside the template itself.

<script type="text/javascript" src="http://ift.tt/2mDlfZ3"></script>

Is their a way to do it in a better way ? I would like to add the script in the page header and to force rerendering of sharethis in the controller of my view after the rendering. But i was not able to make it work in ember.

Note : i use ember 1.13




How can a variable be used to set the src of an image in a production Ember app?

I have some images in my Ember app that are static files declared in ember-cli-build.js.

When the app is used in production, the URLs of the images will change from /icons/icon.png to something like /icons/icon-9ace8daf640d474c5472a54df98a4299.png. So this:

<img src="/icons/icon.png">

becomes:

<img src="/icons/icon-9ace8daf640d474c5472a54df98a4299.png">

How don't know why this happens (browser cache?). This breaks my images where the src comes from a variable. For example:

<img src="">

If imgURL equals /icons/icon.png, then the browser will be dealing with <img src="/icons/icon.png"> and the request will fail because the URL leads to nothing. In development everything works as expected.

How can a variable be used to set the src of an image in a production Ember app?




Ember-boostrap to trigger modal from javascript

From the link here if you scroll down to the example with the button label 'Reopen Modal' They seem to be triggering the modal from javscript. I have tried Ember.$('.modal).modal('show') with no luck, and cant seem to figure out a way to trigger it from js.

My goal is, after a user submits a form and it is successfully validated, the modal appears.

Template


  
  
  



    This is a Modal.


Component

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    submit() {
      Ember.$('.modal').modal('show');
    },
  },
});




Ember Data findAll() causing "TypeError: Cannot read property 'type' of undefined"

Hooking up my 1st model to my backend and am getting the following error when calling Ember Data's findAll()

TypeError: Cannot read property 'type' of undefined

The route,

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        this.store.findAll('restaurant');
    }
});

The model,

import DS from 'ember-data';

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

I can see that Ember is hitting my local server and returning properly formatted JSON from the correct url,

{  
    "restaurants": {  
        "id":1,
        "name":"Restaurant Name"
    }
}

I have seen similar questions about this but it usually has to do with improperly formatted JSON.




Redirect to index only parent route

I am trying to find a way to redirect to the index route if access the parent route but not redirect if a user access the parent.child1 or parent.child2 route.

Is something like this possible?

this.route('parent', function() {
      this.route('child1');
      this.route('child2');
});




i get connection reset while loading emberjs vendorjs file

I deploy my application using ember-cli-deploy. Sometimes when request application from web browser i noticed connection reset for vendorjs file. which cause error and application not loading.




lundi 27 février 2017

How to generate a child model dependant on data from it's parent with ember-factory-guy?

What's the best way to have the data generated in a child model be dependant on data from the parent?

Two particular examples of what I'm trying to accomplish:

  1. I have two types of (one-to-one) linked models that, if linked, will be returned from the API with the same name. So if I create a parent object with a given name, i'd like the child to inherit the same name

  2. the models also have creation timestamps. The childrens' timestamps should be the parent's plus some delta, and the grandchildrens' should be their parent's (the "child" model) plus some additional delta

So, given these models:

Parent = DS.Model.extend({
  name: DS.attr('string'),
  child: DS.belongsTo('child'),
  createdAt: DS.attr('date')
})

Child = DS.Model.extend({
  name: DS.attr('string'),
  parent: DS.belongsTo('parent'),
  children: DS.hasMany('grandchild'),
  createdAt: DS.attr('date')
})

Grandchild = DS.Model.extend({
  parent: DS.belongsTo('child'),
  createdAt: DS.attr('date')
})

Two things I tried:

Approach #1: Using an inline function on the child properties hash that I'm embedding in the parent factory definition

// tests/factories/parent.js

FactoryGuy.define('parent', {
  default: {
    child: FactoryGuy.belongsTo('child', {
      name: (parent) => parent.name,
      createdAt: (parent) => new Date(parent.createdAt.getTime() + OFFSET),
      grandchildren: FactoryGuy.hasMany('grandchild', {
        createdAt: (child) => new Date(parent.createdAt.getTime() + OFFSET)
      });
    })
  }
});


// tests/factories/child.js

FactoryGuy.define('child', {
  default: {
    grandchildren: FactoryGuy.hasMany('grandchild', {
      createdAt: (child) => new Date(child.createdAt.getTime() + OFFSET)
    });
  }
});

I was hoping these functions would recieve the parent object, but instead this seems to just directly assign the function as the value of the field on the child object.

Approach #2: Accessing related objects from inline functions

// tests/factories/child.js

FactoryGuy.define('child', {
  default: {
    name: (child) => child.parent.name,
    createdAt: (child) => new Date(child.parent.createdAt.getTime() + OFFSET),
    grandchildren: FactoryGuy.hasMany('grandchild')
  }
});


// tests/factories/grandchild.js

FactoryGuy.define('grandchild', {
  default: {
    createdAt: (grandchild) => new Date(grandchild.parent.createdAt.getTime() + OFFSET)
  }
});

This just blows up with TypeError: Cannot read property 'createdAt' of undefined (ie the related model isn't available yet)

So, how should this be done?




Using custom authenticator with ember-simple-auth and promises returning undefined for resolve

I am using Ember.js and ember-simple-auth.

I have a custom authenticator named apps\authenticators\jwt.js with a method called authenticate:

  authenticate(credentials) {
    const { identification, password, secret } = credentials;

    const data = JSON.stringify({
      name: identification,
      password: password,
      secret: secret
    });

    const requestOptions = {
      async: true,
      crossDomain: true,
      url: 'http://ift.tt/2mELxsW',
      processData: false,
      method: 'POST',
      contentType: 'application/json',
      data: data,
    };

    return new Promise(function(resolve, reject) {
      Ember.$.ajax(requestOptions).then(function(data) {
        Ember.run(null, resolve, data);
        console.log(data); 
      }, function(jqXHR , textStatus, errorThrown) {
        jqXHR.then = null;
        Ember.run(null, reject, jqXHR, textStatus, errorThrown);
      });
    });
  },

and the controller for my login.hbs template:

import Ember from 'ember';

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

  actions: {
    authenticate() {
      var credentials = this.getProperties('identification', 'password', 'secret'),
      authenticator = 'authenticator:jwt';

      this.getProperties('identification', 'password', 'secret');
      this.get('session').authenticate(authenticator, credentials).then(function(result) {
        console.log(result);
      }, function(err) {
        console.log(err);
      });
    }
  }
});

If I successfully fill out the form and submit it I get a status code 200 and the proper response from the server from the line console.log(data); in the authenticate method in jwt.js But the line console.log(result); in the controller returns undefined.

However, if I fail to fill the form out and submit it I get the proper response from the server from the authenticate method AND I get that message from the console.log() in the controller.

My goal is to get the response on success to the template.

I can't seem to figure out why this is happening, any help is appreciated.

Edit: I am able to achieve my goal using localStorage however I would like to figure out the issue with the promise.




How to make Ember sass compatible with glob match

I would like to import scss files using glob match such as components/* but seems Ember-sass-cli does not support this feature.




Getting undefined from a return of a promise, but printing the response to the log works

I am attempting to get the return of a promise however I am getting undefined.

The promise

return new Promise((resolve, reject) => {
  ajax(requestOptions).then((response) => {
    const { jwt } = response;
    run(() => {
      resolve({ token: jwt });
    });
  }, (error) => {
    run(() => {
      reject(error);
    });
  });
});

Trying to get the value

  this.get('session').authenticate(authenticator, credentials).then((response) => {
    console.log(response);
  }, (reason) => {
    this.set('errorMessage', reason.error || JSON.stringify(reason));
  });

The error returns just fine, however the response returns undefined. But if I print the response in the promise method it shows that it has a value.




How to check if the change in nested data is permissible

We have a nested JSON structure in our web app on the frontend like Rows > Columns > Elements > Rows > Columns > Elements ...

We also have an API call which sends the entire data as JSON to backend.

In the backend we have a set of several permissions, like column size change, row background change, element ordering change, etc that are permitted or denied for various types of users.

We want to identify in the backend if the change of the nested structure is permissible.

Example 1 [Update data]:

The user has CHANGED the size of a 'Column', where the size is represented as a property in 'Column' object.

or

Example 2 [Remove/Add data]:

The user has removed/added an 'Element' from a 'Column'.

We know that we can do full traverse on the entire tree, and understand if the change was permissible or not, but we are looking for a better and faster, resource saving solution for concurrent connections and many users/big trees.


This question seems to be general for different technologies, but I want to let you know that we are using Laravel / Lumen / Dingo in the backend & Ember.js on the frontend.

Thanks for reading and helping :)




EmberJS - Computed on async relationships

How can I use computed to monitor async loaded relationships?

In the following example, I would expect the parent title to be displayed as soon as it's loaded into the store.

http://ift.tt/2mwpeGL




How can I translate routes in ember-cli?

I create some routes in app/router.js

Router.map(function () {
    let i18n = this.service('i18n');
    this.route("lang", { path: '/:lang' }, function () {
        this.route('home', { path: '/', template: 'home' });
        this.route('about', { path: '/' + i18n.t('router.about'), template: 'about' });
        this.route('locales', { path: '/' + i18n.t('router.locations'), template: 'locales' });
    });
});

But the i18n translates only the first time.

How can I translate these routes by change language?

I'm using:

ember-cli: 2.11.1

node: 7.4.0




Qunit for rendering modal in application route

In my application route, I have code provided from the ember website on how to render the opening and closing of modals. http://ift.tt/2m2g47F

export default Ember.Route.extend({
  actions: {
      openModal: function(name, controllerName) {
        this.render(name, {
          into: 'application',
          outlet: 'modal',
          controller: controllerName
        });
      },
      closeModal: function() {
        this.disconnectOutlet({
          outlet: 'modal',
          parentView: 'application'
        });
      }
    }
});

I've been trying to find examples of how to do a unit test for the rendering action but could not find much documentation.

In my unit test for the application route, just for the sake of triggering the action on the route and seeing what would happen this is what I have and the error I get. Thank you for any guidance anyone might be able to provide.

test('route open modal', function(assert) {
  let route = this.subject();
  route.send('openModal', 'cancel-modal');
  assert.ok(route);
});


Died on test #1     at Module.callback (http://localhost:4200/exampleApp/assets/tests.js:1113:24)
    at Module.exports (http://localhost:4200/exampleApp/assets/vendor.js:140:32)
    at requireModule (http://localhost:4200/exampleApp/assets/vendor.js:32:18)
    at TestLoader.require (http://localhost:4200/exampleApp/assets/test-support.js:7124:7)
    at TestLoader.loadModules (http://localhost:4200/exampleApp/assets/test-support.js:7116:14)
    at Function.TestLoader.load (http://localhost:4200/exampleApp/assets/test-support.js:7146:22)
    at http://localhost:4200/exampleApp/assets/test-support.js:7030:18: Cannot read property 'state' of undefined@ 31 ms
Source:     
TypeError: Cannot read property 'state' of undefined
    at parentRoute (http://localhost:4200/exampleApp/assets/vendor.js:41309:64)
    at buildRenderOptions (http://localhost:4200/exampleApp/assets/vendor.js:41371:27)
    at Class.render (http://localhost:4200/exampleApp/assets/vendor.js:41191:27)
    at Class.openModal (http://localhost:4200/exampleApp/assets/exampleApp.js:1118:14)
    at Class.send (http://localhost:4200/exampleApp/assets/vendor.js:40471:39)
    at Class.superWrapper [as send] (http://localhost:4200/exampleApp/assets/vendor.js:54491:22)
    at Object.<anonymous> (http://localhost:4200/exampleApp/assets/tests.js:1115:11)
    at runTest (http://localhost:4200/exampleApp/assets/test-support.js:3471:30)
    at Test.run (http://localhost:4200/exampleApp/assets/test-support.js:3457:6




dimanche 26 février 2017

How to load a 'POST' type page into an iframe in Ember?

I have an old JSP page in my project. I need to include this page into my new page, where my new UI side is complete EmberJS.

Things that I have tried

  1. I got the rendered HTML from JSP using an ajax call and try to render with } handlebar, But there are lots of scripts inside the page. They are not getting parsed or executed.

How can I load the page into an iframe? The page is POST type.




session does not persist after refresh in ember while using torii

I'm using facebook login for my app. I am able to complete login successfully but when i refresh the page session.isAuthenticate becomes undefined. I think the logic to persist the session stays inside fetch method of torii-adapter. Below is my torii-adapter. Please tell me what is missing

import Ember from 'ember';
import {createToken} from 'myapp-new/utils/myapp-utils';
//import User from 'myapp-new/user/model';

export default Ember.Object.extend({
  store: Ember.inject.service(),
  session: Ember.inject.service('session'),
  fetch(){
    let token = session.token;
    if(Ember.isEmpty(token)){
      throw new Error("No session found");
    }
    else{
      return Ember.RSVP.resolve({token});
    }
  },

  open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    let adapter = this;
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://ift.tt/2mANLd8',
       //url:'http://localhost:4200',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then(function(data){
      let user = data.user[0];

      return {
        token:token,
        user: user
      };
    });
  }
});




Neo4j/graphenedb on Heroku Node.js/Ember.js WebSocket ERR_CONNECTION_RESET issue

I am using Neo4j database as graphenedb on Heroku connecting using Ember.js framework. The application is being run locally through Node.js (Not being run through Heroku server).

On a call to driver.session(); I receive this error:

WebSocket connection to 'ws://hobby-blablabla.dbs.graphenedb.com:24786/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

I import driver using ember-browserify:

import Neo4j from 'npm:neo4j-driver';

I call the code:

var neo4j = Neo4j.v1;

var driver = neo4j.driver(graphenedbURL, neo4j.auth.basic(graphenedbUser, graphenedbPass));
var session = driver.session(); // error it thrown here

I retrieved the connection infos using Terminal commands with Heroku CLI like: heroku config:get GRAPHENEDB_BOLT_URL

Chances are that Heroku doesn't actually allow me to connect to the database from my local machine. But it would be really nice to work around this issue and be able to connect. Thank you for help.




EmberJS 2: How to set checkbox property checked from model?

Is there a way to bind the property of a checkbox to a property in the model, for example:

I have this simple model on a route:

export default Ember.Route.extend({
   model:function(params) {
       return { "isAdmin": true }
   } 
});

And on the template I want to display the checkbox checked when the isAdmin is true:

 <input id="adminControll" name="isAdmin" type="checkbox" onchange= />

Any ideas on how to achieve this?




Ember.js: Assertion Failed: An action named 'actionTest' was not found in (generated myroute controller)

I'm trying to use the component bs-button of Ember Bootstrap to dispatch a simple action that will write something in the log. For this, I've created a new app using ember-cli and installed ember-bootstrap according the project Github page.

Then, I've created a route using ember-cli (ember g route myroute) and wrote the code below:

app/routes/myroute.js

import Ember from 'ember';

export default Ember.Route.extend({

  actions: {
    actionTest(value){
      console.log('on actionTest:', value);
    }
  }

});

app/templates/myroute.hbs

Run test action

But when I try to access, the following error appears in console (nothing is rendered):

message: "Assertion Failed: An action named 'actionTest' was not found in (generated myroute controller)"

Followed by:

Uncaught TypeError: Cannot read property 'getAttribute' of undefined

Maybe a completely stupid error, but I haven't found nothing on docs neither on examples.

Environment:

ember-cli:

$ ember -v
ember-cli: 2.10.1
node: 6.9.2
os: darwin x64

chrome console:

DEBUG: -------------------------------
DEBUG: Ember      : 2.10.2
DEBUG: Ember Data : 2.11.3
DEBUG: jQuery     : 3.1.1
DEBUG: -------------------------------




Ember addon ember-cli-sass issue

I have used .css in my Ember addon, now I want to use SCSS. First I changed extensions of style files to .scss, I have app.scss in addon/styles that includes other style files for components etc.

I also added ember-cli-sass (6.0.0) version as dependecy in package.json. Now when I try to serve ember addon, I get following error:

File not found: /addon.scss
in any of the following include paths:
  .../ember/addons/my-addon/tmp/sass_compiler-input_base_path-b2aPW625.tmp
Error: File not found: /addon.scss
in any of the following include paths:
  .../ember/addons/my-addon/tmp/sass_compiler-input_base_path-b2aPW625.tmp
    at Object.findFileSync (.../ember/addons/v/node_modules/include-path-searcher/index.js:12:9)
    at SassCompiler.build (.../ember/addons/v/node_modules/graph-lib/node_modules/broccoli-sass-source-maps/index.js:63:31)
    at .../ember/addons/v/node_modules/broccoli-caching-writer/index.js:149:21
    at tryCatch (.../ember/addons/my-addon/node_modules/rsvp/dist/rsvp.js:538:12)
    at invokeCallback (.../ember/addons/my-addon/node_modules/rsvp/dist/rsvp.js:553:13)
    at publish (.../ember/addons/my-addon/node_modules/rsvp/dist/rsvp.js:521:7)
    at flush (.../ember/addons/my-addon/node_modules/rsvp/dist/rsvp.js:2373:5)
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

Any idea what is causing this issue? Do I need to add/edit anything else in my addon? I am using ember-cli 2.3.0. I have tried adding addon.scss file, it didnt help.




Ember Changest –– cannot return field to original value

I've run into an issue using ember-changeset and ember-changeset-validations –– I have form fields that I am able to change to a new value, but once changed, I am unable to reset them to their original value.

This line from the set property method seems to be the problem somehow ––the it seems that my object should be returning yes that it does have the key but it is returning false:

} else if (obj.hasOwnProperty(key)) {

For example I start with value:

Start value: Canada Change to: Burundi - ok Change to: Canad -- unable to add final "a" -– when submitted, form will be submitted with value of "Canad" instead of "Canada"....

I assume this is not an issue with ember-changeset but an issue either with something I am doing wrong and/or something about my objects (JSON-API from Ember Data).

Have tried this in three different projects, trying to eliminate all possible external sources of trouble and have yet to find a solution.




"this" is undefined in torii-adapter in ember

I am trying to store some data post login inside store. Below is code of my torii-adapter

import Ember from 'ember';
import {createToken} from 'myapp/utils/app-utils';

export default Ember.Object.extend({
  store: Ember.inject.service(),

  open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then(function(data){
      let user = data.user[0];
      this.set('storage.token',token); //this is undefined
      return {
        user: user
      };
    });
  }

});

Error i am getting is "TypeError: Cannot read property 'set' of undefined". I am injecting the store service as well. Could you please tell me what exactly is going wrong here?




How redirect to another route inside index of Ember Engine?

Inside a engine, in index route, I need transitionTo another route, but when create route with ember g route index --in-repo-addon identify broccoli expose this error Object.fs.symlinkSync.




How to import handlebars template in controller and place it in another handlebars template

I am sorry if this question is silly. I have started working on front end with ember js and I am loving it. I am stuck at a point where I want to import a handlebars template in ember js controllers and attach it to div.

So How to import a handlebars template in controller and populate it and place it inside another handlebars template.

Here is my controller:

import Ember from 'ember';

export default Ember.Controller.extend({

    actions: {
    search: function() {
            alert("done");
          }
    }

});

here is the handlebars template:

<table class="table table-striped">
   <thead>
   <tr>
       <th>Name</th>
       <th>Mark</th>
       <th>Subject</th>
   </tr>
   </thead>
   <tbody>
   
   <tr>
       <td></td>
       <td></td>
       <td></td>
   </tr>
   
   </tbody>
 </table>

I have published the code on github and url is : http://ift.tt/2mrHFfG




samedi 25 février 2017

Getting {"readyState":0,"status":0,"statusText":"error"} when making a JSON request to a different url

I am attempting to make a JSON request to an API located on a different url using ember-simple-auth and a custom adapter. When I make the request and check the the console the request returns Status code: 301 Moved Permanently and I am returned the error {"readyState":0,"status":0,"statusText":"error"}

import Base from 'ember-simple-auth/authenticators/base';

const { RSVP: { Promise }, $: { ajax }, run } = Ember;

export default Base.extend({
  restore(data) {

  },

  authenticate(credentials) {

    const { identification, password } = credentials;

const data = JSON.stringify({
  name: identification,
  password: password,
  secret: '012345'
});

const requestOptions = {
  async: true,
  crossDomain: true,
  url: 'http://ift.tt/2mja9LE',
  processData: false,
  method: 'POST',
  contentType: 'application/json',
  data: data,
};

console.log(JSON.stringify(requestOptions));
console.log(data);

return new Promise((resolve, reject) => {
  ajax(requestOptions).then((response) => {
    const { jwt } = response;
    run(() => {
      resolve(
        // response
        {token: jwt}
      );
    });
  }, (error) => {
    run(() => {
      reject(error);
    });
  });
});
  },

  invalidate(data) {
  }
});

When I print the requestOptions variable I get {"async":true,"crossDomain":true,"url":"http://ift.tt/2mja9LE","processData":false,"method":"POST","contentType":"application/json","data":"{\"name\":\"foo\",\"password\":\"bar\",\"secret\":\"012345\"}"}

I'm not sure what the issue is, any help is appreciated.




Ember : classNameBinding for a component - class is added, but CSS transition is skipped

Ember (latest) classNameBinding for a component - class is added on didInsertElement(), but CSS transition is seemingly skipped.

When I add and remove the class in dev tools or comment out the loaded class in the stylesheet the animation occurs, but otherwise - when the element is inserted it just goes from 0 to 100 immediately.

Here is a full example in an ember-twiddle

example-component.js

import Ember from 'ember';

export default Ember.Component.extend({
  tagName: 'section',
  classNames: ['example-component'],
  classNameBindings: ['loaded'],

  loaded: false,

  didInsertElement() {
    this.set('loaded', true);
  },
});


CSS

.example-component {      
  opacity: .1; /* so you can see it */
  transform: translate(0, -100px);
  transition: 3s;
}

.example-component.loaded {
    opacity: 1;
  transform: translate(0, 0);
}




Using sendAction() implement data down actions up in Ember.js

I'm doing a little app to try and learn Ember, but I'm really struggling with the implementation of a data-down-actions-up component. For some reason I don't seem to be able to 'send' an action back up to the router properly. My code is below:

My Component (editable-cell.js):

import Ember from 'ember';

export default Ember.Component.extend({
  isEditing: false,
  startingText: "",
  saveAction: null,
  asdf: 'asdf jkl;',

  actions: {
    edit() {
      this.set('isEditing', true);
    },
    cancelEdit() {
      this.set('isEditing', false);
    },
    save() {
      console.log("SAVE");

      this.sendAction('action', this.get('asdf'));
      this.set('isEditing', false);
    }
  }
});

My Component Template (editable-cell.hbs):

<td>
  
    <form  class="form-inline">
      <div class="input-group">
        <input class="form-control" value="">
        <div class="input-group-btn">
          <button type="submit" class="btn btn-success" >Save</button>
          <button class="btn btn-danger" >Cancel</button>
        </div>
      </div>
    </form>

  
    <span ></span>
  
</td>

My Template (books.hbs):

<h1>Books</h1>

<table class="table table-bordered table-striped">
  <thead>
  <tr>
    <th>
      Title
      <br><small class="small not-bold">(Click on name for editing)</small>
    </th>
    <th class="vtop">Author</th>
    <th class="vtop">Release Year</th>
    <th class="vtop">Library</th>
  </tr>
  </thead>
  <tbody>
  
    <tr>
      <td>
        
      </td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  
  </tbody>
</table>

The Router (books.js):

import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.store.findAll('book');
  },
  actions: {
    saveBook: function(book) {
      console.log("In the book controller");
      console.log(book);
      book.save();
    }
  }
});

The Controller (books.js):

import Ember from 'ember';

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




How to add text in Text Area when i select text from list using checkbox

We have text-area component and list component,Now when we click in text-area,it loads the list component with data respectively.

When clicked on list it gets list data and set into text-area component.

This list component should work as multi select and get data of selected list and on event set respective data to a text-area. Currently on every click of list text area set accordingly but on every next click of list it replaces previous selected data in text-area.

I am trying to achieve list contains check boxes,on checked it select text and set to text area value without replacing previous text.

How can we put Action when check-box checked?And How can we achieve this task.I am using Ember 1.12 version.

template.hbs
<ul class="list-group" style="font-size: 11px;">
       
             <li class="list-group-item" 
         style="cursor:pointer;">

                 <div class="patient-details" id="masterNotesData" >
                      
                 </div>

             </li>
      
 </ul>


Controller.js

addNotesToTemplate: function(textNotes) {
        console.log("textNote is ",textNotes);
        this.set('textNoteData',textNotes);
        console.log("textnote data is ",this.get('textNoteData'));
        var x=this.get('textNoteData');
        var i=this.get('divId');
        console.log('i value ',i);
        $('.textarea').eq(i).val(x).focus();



    }

Here '.textarea' class define in text-area component




How ember consider the host name and path?

My Domain - 'http://bharath-1234:8080/folder/folder-id' namespace - 'api/1'

I've a folder model which will contain the folder's response and I need to sort the model based on user's sorting. To that I do overwrite the query in folder's adapter. I do expect that my url will be like, http://bharath-1234:8080/api/1/folder/folder-id/folder?sort[folder][last_modified]=desc but it goes like http://bharath-1234:8080/folder/api/1/folder/folder-id/folder?sort[folder][last_modified]=desc this way. I need to cut down the /folder from my API call.

How can I do achieve that? router.js

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




this.get('session') returns undefined for torii

I'm trying to use Facebook login using torii in an Ember app. I am using ember 2.0 (2.11 to be specific). Below is handlebar of my component my-login

Login Using Faceboo

action in my component is defined as

import Ember from 'ember';

export default Ember.Component.extend({
    actions:{
        loginUsingFacebook(){
            let session = this.get('session'); //session comes undefined
            console.log(session);
        }
    }
});

i have setup my environment as defined [here][1]

in my application route i am using it as

 


I am using torii-adapter which on path app/torii-adapters and exactly as provided here

i have installed torii using npm install torii. Could you please let me know what i am missing.

I am not able to get the session.




vendredi 24 février 2017

Ember js integrating with D3

I want to include a graphs which have 2-y axis with relevant 2 data sets in my ember project.Since I am newbie to D3 js as well as ember js I do some googling and come up with npm packages for doing that like these "ember-d3","ember-charts" "ember-d3-helpers" ...etc.But all of them seems to me there is a bit of learning curve. My questions are , from using those kind of packages can I integrate and draw my graphs? or else can I use directly D3 without any npm plunging ? Are there any suitable way to integrate D3 in ember project?




Deploying an Ember.js application with a Node.js backend

I’m new developing with ember and I’m confused with deploying a project. Essentially I have a Linux box running nginx that I want to deploy to. I have a Node.js backend and I’m using ember-cli-delpoy and ember-cli-deploy-build. When I do a ‘ember deploy production’ I can take the ‘deploy-dist’ output directory and point MAMP(apache server) to that directory, and I can access the built ember application. However, the application doesn’t have access to my Node.js backend server. How can I modify my Node.js backend to serve my ember application in a production environment? Below is what my server looks like. I tried to modify the server to point to the ‘deploy-dist’ directory because that made sense to me. But that doesn’t work I get a ‘Cannot GET /‘ message. How can I modify my Node.js application to work in a production environment? Any help is greatly appreciated.

// Working server in ember development mode

/** Dependencies **/
var express    = require('express'),
      path       = require("path"),
      logger     = require('morgan'),
      bodyParser = require('body-parser'),
      connection = require('./config/connection'),
      routes     = require('./config/routes')
      jwt        = require('jsonwebtoken'),
      morgan     = require('morgan'),
      gravatar   = require('gravatar'),
      Router     = express.Router();

module.exports = function(app) {
// Setup
 // Log proxy requests
  app.use(morgan('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended: true}));
  // Requires
  connection.init();
  routes.configure(app ,gravatar ,Router );

}

// modified server

/** Dependencies **/
var express    = require('express'),
      path       = require("path"),
      bodyParser = require('body-parser'),
      connection = require('./config/connection'),
      routes     = require('./config/routes')
      jwt        = require('jsonwebtoken'),
      morgan     = require('morgan'),
      gravatar   = require('gravatar'),
      Router     = express.Router();

/** Setup **/
var app = express();

// Setup
// Log proxy requests
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.set('views', __dirname + '/client'); // general config
app.engine('html', require('ejs').__express);
app.set('view engine', 'html');
// Requires
connection.init();
routes.configure(app ,gravatar ,Router );

/** Port **/
app.listen(8000,function(){
  console.log("Listening on Port 8000...");
});




Web Speech API and Ember - continuous recognition

I am using Web Speech API and ember:

init: function () {
    this._super();

    var self = this;
    var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    var recognition = new SpeechRecognition();

    recognition.continuous = true;
    recognition.interimResults = true;

    this.set("recognition", recognition);

    this.get("recognition").start();

    recognition.onstart = function () {
        console.info('recognition:start');
        self.set("isActive", true);
        self.trigger("start");
    };


    recognition.onend = function (event) {
        console.info('recognition:end', event);

        alert("recognition stopped");

        this.get("recognition").start();


    };


},

The above code starts voice recognition and I thought should make it continuous (ie. keeps listening forever), but it stops after 15 seconds or so. The recognition.onend function I thought is supposed to be called when voice recognition stops, but it never runs the code I have in there. How can I make the web speech API continue recording?




Updating to 1.11.1 - View not accessible inside an helper

We are in the process of updating our ember app from 1.10 to 1.11 and we are running into an issue. We have a simple sort-toggle helper that is not working anymore.



Code of the helper:

Ember.HTMLBars._registerHelper('sort-toggle', function(params, hash, options, env) {
    var target = this.get('controller.sortTarget') || hash.target,
        view = env.data.view,
        field = params[0];

    hash = {};
    hash[target] = view.getStream(this.get('controller').createToggleString(field));

    options = {
        hash: hash,
        data: options.data
    };

    return Ember.Handlebars.helpers['query-params'].helperFunction.call(this, [], hash, options, env);
});

It appears that since we updated to ember-cli 0.2.3 (ember 1.11.1), this is now undefined and so we cannot access the view or the controller.

We did not see anything in the changelog related to this, what changed ? and how should we migrate this ?




get 'self', 'next' and 'previous' links (ember v2)

I'm developing an Ember-js application where I'd like to link each 'article' to the next and previous article. I want to work according to the JSON API.

I've managed to load/show the article's (blog) author in a decent and to load and show a 'teaser' of the next (related) article. That works fine.

Now, the next piece should be fairly simple: how can I load the 'links' defined in my article? How can I add them to my model or show them in any other way in my Handlebars-template?

Let me give an exerpt from my JSON-repsonse (the payload):

{

  "data": {
    "type": "blogs",
    "id": "5",
    "links": {
      "previous": "blogs/4",
      "self": "blogs/5",
      "next": "blogs/6"
    },
    "attributes": {…},
    "relationships": {
        …
      },

The most important issue is how to get this 'self' link from the JSON reply. Can this data be used straight from the 'model'?




How to set nested route path same level as the parent route?

  this.route('browse', { path: '/points' }, function() {
    this.route('quiz', { path: '/quiz' });
    this.route('learn', { path: '/learn' });
  });
  this.route('post', { path: '/post' }, function() {
    this.route('star', { path: '/star' });
    this.route('marked', { path: '/marked' });
  });

The reason I want to do this is that I would like to share same base template between nested routes and I do not put all these into application template (otherwise I need to place so many condition block in it).

What I want to achive is

browse       -> /points
browse.quiz  -> /quiz
browse.learn -> /learn

post         -> /posts
post.star    -> /star
post.marked  -> /marked




How to auto redirect after authenticate using ember-simple-auth

I am using JWT (JSON Web Token) to authenticate user. I am using ApplicationRouteMixin in application.js route which supports to handle two events (success login and success logout) by default.

Now when I login with a user credential using code below,

  login(credential) {
    const authenticator = 'authenticator:jwt';
    const session = this.get('session');

    session.authenticate(authenticator, credential)
      .catch(() => {
        const errorMessage = "Wrong email or password. Please try again!";
        this.set('errorMessage', errorMessage);
      });
  },

The URL stay the same even the response is success which includes the valid JWT.

{"jwt":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0ODg1NDIyMTcsInN1YiI6Mn0.Ma0ZtLWhoO1mb5cluGJZcKuHb-J2ZJdZOd3AFhVI258"}

I have to refresh the page manually to get the page redirect. However, when I am in the protected route. The auto redirect is working for this.get('session').invalidate().

I know I can just add a then after authenticate method (see code below) to redirect the URL to the right one, but after browse so many examples I see no one do this.

    session.authenticate(authenticator, credential)
      .then(() => {
        this.transitionTo('browse');
      })
      .catch(() => {
        const errorMessage = "Wrong email or password. Please try again!";
        this.set('errorMessage', errorMessage);
      });

I am missing anything here?




How to write acceptance tests on ember.js for download file form?

I have a form which will download file from back-end.

<form action="" method="GET">
    <input type="hidden" name="access_token" value="">
    <input type="submit" value="Download Template">
</form>

How can i test it?




Recognize the kind of retrieve-record-object in Ember

I am building a crud-route-mixin where I define default functions and actions for routes.

One of the functions has as argument a query object; within the action I perform the call:

_doSomething(query) {
    query.then( result => {
        //do something default with this result
    })
}

The routes call the _doSomething function with different kind of methods. For example:

Route A

export default Ember.Route.extend(CrudRoute, {
    setupController() {
        this._super(...arguments);
        this._doSomething(this.get('store').findAll('paper'));
    }      
}

Route B

export default Ember.Route.extend(CrudRoute, {
    setupController() {
        this._super(...arguments);
        this._doSomething(this.get('store').findRecord('blog-post'));
    }      
}

I was wondering, is it possible to retrieve the method name or type of the query object? So I could do something like this (pseudo code):

_doSomething(query) {
    query.then( result => {
        if (query.getRetrieveMethodName() === 'findAll') {
            //do something default with this array result
        } else if (query.getRetrieveMethodName() === 'findRecord') {
            //do something default with this single record result
        }
    })
}

P.S. Check if the payload is a single record or array is not an option, because I need this distiction in the error handling as well.




jeudi 23 février 2017

Ember ArrayProxy with init not working

I have an class that extends Ember.ArrayProxy like:

export default Ember.ArrayProxy.extend({
    init() {
      this._super(...arguments);
      this.set('content', Ember.A([]));
      // doing some stuff
    },
});

and I am using this like:

const myProxy = ProxyClass.create({});
myProxy.addObject(0.5);

but because of init hook override, the changes aren't propagated, so my template is not changing



I think I am doing something wrong, but funny thing is that I can use myProxy.content property to see changes (though I should just refer this by myProxy). Maybe someone can point me in the right direction




Where is a great place to introduce some constants into a project?

I would love to remove all the magic numbers inside my project, so I think import a constant to where they need to be is a great idea.

See my constant declaration below,

export default { validation: validation };

const validation = {
  password: 6,
  email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
};

However when I try to import the constant into a component I get a import error which state the model could not be found.

Inside my component,

import Ember from 'ember';
import { validation } from '../../../../config/constants';

export default Ember.Component.extend({
  classNames: ['login-panel'],
  // ...
}

My question is where is a good place to store this kind of constants and how to import into it to the right place?




A token request using ember-simple-auth-token won't include the identification field

A have an Ember (v2.12.0-beta.1) app that uses ember-simple-auth-token to request a JWT token.

The important part happens in the login controller.

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

    // Properties
    username: 'user1',
    password: 'password123',

    // Actions
    actions: {
        login(username, password) {
            console.log('Attempting login...');

            let creds = this.getProperties('username', 'password');
            let authenticator = 'authenticator:jwt';

            this.get('session').authenticate(authenticator, creds).then(function() {
                console.log('LOGIN SUCCESS')
            }, function() {
                console.log('LOGIN FAIL')
            });
        }
    }
});

When submitting the form, there is a request that is being made by the browser and my backend receives it.

The problem is that only the password is included in the request. The body of the request has the form {"password":"password123"}, but it should look like {"username":"user1","password":"password123"}. If course, the login attempt fails and LOGIN FAIL is printed.

When is the username not included in the token request?

I tried using earlier versions of ember-simple-auth-token and ember-simple-auth.

Here is my configuration:

ENV['ember-simple-auth'] = {
    authorizer: 'authorizer:token',
};

ENV['ember-simple-auth-token'] = {
    serverTokenEndpoint: 'http://ift.tt/2mj58Q4',
    identificationField: 'username',
    passwordField: 'password',
    tokenPropertyName: 'token',
    authorizationPrefix: 'Bearer ',
    authorizationHeaderName: 'Authorization',
    refreshAccessTokens: false,
};




Ember-paper: Cannot set property element of [object Object] which has only a getter

I am using Ember-paper 0.2 which seems to be latest stable version. i'm creating navbar learning from tutorial. whenever I add paper-button i am getting error " Cannot set property element of [object Object] which has only a getter".

It looks like i have mistaken some where but not able to figure out what. Below is my code for navbar.


  <div class="md-toolbar-tools">
      
      <div class="paper-right">
                  
      </div>
  </div>



is my logo component below is the component code

<img src="assets/images/logo_sm_app.png" class="logo">

I have defined my styles in app.scss file

I have used steps as stated in the ember-paper documentation. Could you please tell me what is missing? Below is the stack trace of the error i am getting

Uncaught TypeError: Cannot set property element of [object Object] which has only a getter
    at Class.didInsertElement (ripple-mixin.js:31)
    at Class.superWrapper [as didInsertElement] (ember.debug.js:40424)
    at Class.trigger (ember.debug.js:42259)
    at Class.superWrapper [as trigger] (ember.debug.js:40424)
    at CurlyComponentManager.didCreate (ember.debug.js:12725)
    at Environment.commit (ember.debug.js:50904)
    at Environment.commit (ember.debug.js:9283)
    at InteractiveRenderer._renderRoots (ember.debug.js:12121)
    at InteractiveRenderer._renderRootsTransaction (ember.debug.js:12150)
    at InteractiveRenderer._renderRoot (ember.debug.js:12071)




How to generate model using Ember-cli with attributes using options (include relationship)?

I remember there is a way to generate a model with all the attributes and relationship for a model using ember-cli something like below,

ember g model user name:string email:string user:has-many

So that I can avoid to type all attr again and again.

name: DS.attr('string')

But I could not find any reference about it. Where can I find more ref. about the detailed usage on how to generate a model with attritbues and relationships?

Question

Where can I find the detailed option reference for command ember generate <generator-name> <options>?




Ember.js: how do I override one of my superclass's actions in a component?

This is Ember.js 2.11. If I have a Component:

app/components/a/component.js

export default EmberComponent.extend({
   actions: {
      foo() { ... }
   }
});

and another component which inherits from it:

app/components/b/component.js

import A from 'components/a';

export default EmberComponent.extend(A, {
  ...
});

How do I override foo in B? Defining my own actions object does not appear to work.




Bootstrap css files are not found in tmp folder while Ember build

The CSS files are not generated in the app/styles directory while ember build. The error that occurs while Ember Build is given below:

    "C:\Program Files\Java\jdk1.8.0_25\bin\java" -Dmaven.home=D:\JavaProjects\apache-maven-3.0.3 -Dclassworlds.conf=D:\JavaProjects\apache-maven-3.0.3\bin\m2.conf -Didea.launcher.port=7534 "-Didea.launcher.bin.path=D:\IntelliJ IDEA 14.1.7\bin" -Dfile.encoding=windows-1252 -classpath "D:\JavaProjects\apache-maven-3.0.3\boot\plexus-classworlds-2.4.jar;D:\IntelliJ IDEA 14.1.7\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain org.codehaus.classworlds.Launcher -Didea.version=14.1.7
-DskipTests=true clean install
    [INFO] Scanning for projects...
    [INFO]                                                                         
    [INFO] ------------------------------------------------------------------------
    [INFO] Building CMTEmberUI 1.0.0-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO] 
    [INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ CMTEmberUI ---
    [INFO] Deleting D:\sigdev\IntegrateCareManagement\CMTEmberUI\target
    [INFO] 
    [INFO] --- build-helper-maven-plugin:1.5:maven-version (add-mvn-version) @ CMTEmberUI ---
    [INFO] 
    [INFO] --- build-helper-maven-plugin:1.5:parse-version (add-mvn-version) @ CMTEmberUI ---
    [INFO] 
    [INFO] --- maven-dependency-plugin:2.8:unpack (copy) @ CMTEmberUI ---
    [INFO] Configured Artifact: org.jacoco:org.jacoco.agent:0.7.2.201409121644:jar
    [INFO] Unpacking C:\Users\dt202197\.m2\repository\org\jacoco\org.jacoco.agent\0.7.2.201409121644\org.jacoco.agent-0.7.2.201409121644.jar to D:\sigdev\IntegrateCareManagement\CMTEmberUI\target\jacoco with includes "" and excludes ""
    [INFO] 
    [INFO] --- maven-resources-plugin:2.6:copy-resources (liquibase) @ CMTEmberUI ---
    [INFO] Using 'UTF-8' encoding to copy filtered resources.
    [INFO] skip non existing resourceDirectory D:\sigdev\IntegrateCareManagement\CMTEmberUI\src\main\resources
    [INFO] 
    [INFO] --- maven-resources-plugin:2.6:copy-resources (liquibase-test) @ CMTEmberUI ---
    [INFO] Using 'UTF-8' encoding to copy filtered resources.
    [INFO] skip non existing resourceDirectory D:\sigdev\IntegrateCareManagement\CMTEmberUI\src\test\resources
    [INFO] 
    [INFO] --- maven-surefire-plugin:2.11:test (unit-tests) @ CMTEmberUI ---
    [INFO] Tests are skipped.
    [INFO] 
    [INFO] --- maven-antrun-plugin:1.7:run (ember-cli) @ CMTEmberUI ---
    [INFO] Executing tasks

    building:
         [echo] *** NPM INSTALL ***
         [echo] *** BOWER INSTALL ***
         [echo] *** EMBER production BUILD ***
         [exec] 
         [exec] Running without elevated rights. Running Ember CLI "as Administrator" increases performance significantly.
         [exec] See http://ift.tt/1r0dnSM for details.
         [exec] 
         [exec] cleaning up...
         [exec] Build failed.
         [exec] File: assets/vendor.css
         [exec] The Broccoli Plugin: [broccoli-persistent-filter:CleanCSSFilter] failed with:
         [exec] Error: 3 errors found while optimizing CSS with clean-css:
         [exec]   1. Ignoring local source map at "D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\tmp\broccoli_persistent_filterclean_cssfilter-input_base_path-daTKhwFh.tmp\assets\bootstrap.min.css.map" as resource is missing.
         [exec]   2. Ignoring local source map at "D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\tmp\broccoli_persistent_filterclean_cssfilter-input_base_path-daTKhwFh.tmp\assets\bootstrap-theme.min.css.map" as resource is missing.
         [exec]   3. Ignoring local source map at "D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\tmp\broccoli_persistent_filterclean_cssfilter-input_base_path-daTKhwFh.tmp\assets\bootstrap.css.map" as resource is missing.
         [exec] 
         [exec] clean-css dangerously ignores these errors but broccoli-clean-css doesn't, because it's much more reasonable to update the CSS to fix all problems than to pretend that you didn't see the errors.
         [exec]     at minify (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css-promise\index.js:63:18)
         [exec]     at D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\clean.js:107:9
         [exec]     at Object.callback (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\read-sources.js:29:9)
         [exec]     at doApplySourceMaps (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\apply-source-maps.js:61:23)
         [exec]     at D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\apply-source-maps.js:86:12
         [exec]     at extractInputSourceMapFrom (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\apply-source-maps.js:122:14)
         [exec]     at fetchAndApplySourceMap (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\apply-source-maps.js:79:10)
         [exec]     at doApplySourceMaps (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\apply-source-maps.js:57:14)
         [exec]     at D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\apply-source-maps.js:86:12
         [exec]     at extractInputSourceMapFrom (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\clean-css\lib\reader\apply-source-maps.js:122:14)
         [exec] 
         [exec] The broccoli plugin was instantiated at: 
         [exec]     at CleanCSSFilter.Plugin (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\broccoli-plugin\index.js:7:31)
         [exec]     at CleanCSSFilter.Filter [as constructor] (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\broccoli-persistent-filter\index.js:62:10)
         [exec]     at CleanCSSFilter (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\broccoli-clean-css\index.js:29:5)
         [exec]     at module.exports.preprocessMinifyCss (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\ember-cli-preprocess-registry\preprocessors.js:112:12)
         [exec]     at EmberApp.styles (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\ember-cli\lib\broccoli\ember-app.js:1377:23)
         [exec]     at EmberApp.toArray (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\ember-cli\lib\broccoli\ember-app.js:1675:10)
         [exec]     at EmberApp.toTree (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\ember-cli\lib\broccoli\ember-app.js:1696:30)
         [exec]     at module.exports (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\ember-cli-build.js:26:14)
         [exec]     at CoreObject.setupBroccoliBuilder (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\ember-cli\lib\models\builder.js:84:19)
         [exec]     at CoreObject.init (D:\sigdev\IntegrateCareManagement\CMTEmberUI\cmt\node_modules\ember-cli\lib\models\builder.js:64:10)
         [exec] 
         [exec] 
         [echo] *** EMBER COMMAND RESULTS ***
         [echo] 1
         [exec] Result: 1
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 22:30.494s
    [INFO] Finished at: Fri Feb 24 01:47:06 IST 2017
    [INFO] Final Memory: 11M/143M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.7:run (ember-cli) on project CMTEmberUI: An Ant BuildException has occured: unless=cmdsuccess
    [ERROR] around Ant part ...<fail unless="cmdsuccess"/>... @ 42:30 in D:\sigdev\IntegrateCareManagement\CMTEmberUI\target\antrun\build-building.xml
    [ERROR] -> [Help 1]
    [ERROR] 
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR] 
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://ift.tt/1bGwP7h

    Process finished with exit code 1

I am new to ember and am unable to find the reason behind this error. Ember is failing to generate CSS files.

I tried to add ember-cli-shims and bootstrap manually via bower install but still the issue does not get resolved.




Ember RSVP.hash with RSVP.all unexpected token

Currently I am struggeling with Ember.RSVP.all in combination with Ember.RSVP.hash

I am doing several API requests and the idea was to collect all these requests in an array (different types) and then resolve them alltogether. I think in RSVP.hash everything breaks with "Uncaught error, unexpected token u (or :,. its every time something other) in JSON..." In the error I can see parts of the data delivered by the API so the request as is seems to work.

The idea of the code structure worked totally fine with bluebird in a other version (without ember). Would it be possible simply to use bluebird in ember ?

This is what I am doing (maybe there is a better solution ?):

in my Service:

testRequest (result){ 
var sources = result[0];    // that are multiple sources from the store received in the controller
var startDate = result[1];
var type1 = [];
var typ2 = [];
  console.log(sources);
  sources.forEach(function (item, index, enumerable) {
    var identifier = item.get('identifier');
    var query = {id: item.get('bid'), params:{since:startDate}}; //build the query in

    if (identifier == "type1"){
      console.log("got", identifier, "with query:", query);
      //type1.push(dummy(query));
      type1.push(usabilla.websites.buttons.feedback.get(query)); // do a request for type1 structure and push to array
    }
    else if (identifier == "type2"){
      console.log("got", identifier, "with query:", query);
      //type2.push(dummy(query));
      type2.push(usabilla.apps.forms.feedback.get(query)); // do a request for type 2 structure and push to array
    }
    else {
      console.log("not supported");
    }
  });
 return [type1, type2];
},

and the controller part:

//Controller:
//...
store.findAll('feedbacksource')
.then(function(feedbackresources){
var result = feedbackresources.toArray();
  return [result, startDate];
})
.then(myService.testRequest)
.then(myService.logRes)
.then(function(results){
  return Ember.RSVP.hash({
         type1: Ember.RSVP.all(results[0]),
         type2: Ember.RSVP.all(results[1])
        });
})
.then(myService.logRes)

Thanks so much for your help, I have tried so many things but nothing seems to work or maybe I am totally wrong where I search the error. I am running out of ideas.




Objects in Ember Data

This has been asked a couple times, but the examples didn't help a whole lot.

I want to post 'posts' to my server, so I have a 'posts' model and then a 'single' model. The 'posts' model represents all the posts, and then my 'single' model represents what each post needs... I am new to Ember.js, and really could use a hand here/direction.

So when I submit the form (for creating a new post):

// When the form is submitted, post it!
actions: {
// createNew begin
createNew() {
  var title = this.controller.get('title');
  var content = this.controller.get('content');

  const data = {
    "posts": [
      {
      "title": title,
      "content": content
      }
    ]
  };
  return this.store.createRecord('posts', data).save().
    then(function(post) {
      console.log(post);
    }, function(error) {
      console.log(error);
    });
} // end of createNew
}

'posts' model:

import DS from 'ember-data';

export default DS.Model.extend({
    posts: DS.hasMany('single'),
});

'single' model: import DS from 'ember-data';

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

And then my serializer to hook the two together...

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    posts: { embedded: 'always' }
  }
});

Currently, this is the error that outputs:

"Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [[object Object]]"

In Short: I need to create data models that can represent the following JSON structure:

{

"posts": [

    { "title": "Title", "content": "Content" }

 ]

}

Thanks!




Ember Data won't load related models from API

I have a model with several related models. I'm trying to call in my route return this.store.findAll('my-model'), which gets JSON data from the API. It returns attributes, which I can access fine, and has the related model names in relationships, and the models also appear in the included section. However, the related models are not being populated into the Ember store, unless I make a separate findAll request for them.

In Ember Inspector I can see 'my-model', and the list of relationships appears, but for the related model all that appears is <(subclass of Ember.ObjectProxy)>, which I believe is a promise object. However, the promise is coming up as fulfilled.

It was my understanding that Ember is supposed to get related models automatically along as their relationships are defined. If I have a model 'my-model' with a property 'property', and a related model 'related-model' with a property 'related-property', I thought I should be able to do 'myModel.property', and 'myModel.relatedModel.relatedProperty', but only the first item works.

I've tried the advice in Couldn't access related models in ember.js 2.0 using ember-data but no joy. And much of the previous seemingly relevant questions on here are too old to be of use as Ember changes so much. I cannot seem to get the models to relate to each other. I've tried loading each model separately in the route, I've tried an RSVP hash, I've tried .then(), nothing works. Is there something extra I have to do to handle an API, or is there something I'm missing? How can I access the related models?




Ember tutorial - Server not starting after installing ember-cli-mirage

Following along with the ember tutorial and got to installing ember-cli-mirage here. After I install the add-on the server will not start. I get to "Serving on http://localhost:4200/" and then it just hangs there. When I try to kill the server via Ctrl-C it also hangs at "cleaning up...". If I remove ember-cli-mirage from package.json and node_modules then everything will start again.

I have been able to dig around to get live server and other aspects running, but this one is giving me nothing to work with. Are there any additional settings/pieces that the tutorial is missing or do I have a version/environment issue? Is there a way to get additional information at startup (I know --verbose is not one)?

Vagrant: ubuntu/trusty-64 (14.04.5 LTS)

Node: v7.5.0

NPM: v3.10.8

ember-cli: 2.11.1




MathJax + Ember.js Re-rendering issue

I've encountered an issue with ember's (app is on 2.6.0, but seems to happen in latest as well) rendering process and its compatibility with the MathJax.js library. I have an ember twiddle (linked below) that isolates the problem, but essentially it seems like MathJax's rendering of inline equations that occur in the middle of a single text node breaks ember's re-rendering, in that the single text node becomes multiple text nodes after MathJax transforms the inline equation text into its Math elements, and the 2nd text node becomes orphaned, and remains in the DOM across re-renders.

http://ift.tt/2mbNtgG

It may just be that my integration of mathjax with ember is just not correct, so I'd love some pointers if thats the case.




Test the "loading" state in an Ember acceptance test

In my acceptance test, I want to confirm that the "loading indicator" is properly shown and hidden during an async action. Let's say I have an action that looks like this:

myAction() {
    this.set('isLoading', true);
    someAsyncMethod().then(answer => {
        this.set('isLoading', false);
    });
}

And a template that looks like this:

<button class="my-button" >
  
    <i class="loader"></i>
  
  Click me !
</button>

And finally, the test:

test('My super action', function(assert) {
    visit('/my-route');
    andThen(() => {
        click('.my-button');
        // Here, since the click() helper is async, the action isn't 
        // called, so the loader isn't shown yet.
    });
    andThen(() => {
      // Here, the load is finished, so the loader is removed
    });
});

My question is : Where can I do the assertion that the loader is shown ?




Ember.js + prototype.js conflict

we want to add a Ember.js-App to a existing site. The app is something like a widget what you integrate into your website. The website has prototype.js version 1.7.1 and our Ember.js-App has version 2.6 (but i tried 2.10 as well and the ember-twiddle uses 2.10).

Our problem is, that Ember seems to use the prototype Array instead of the Ember.js Array so methods like .clear() does not work properly because it calls the .clear() method from prototype.js instead that one from Ember.js.

Twiddle with prototype.js: http://ift.tt/2mp2KXt

Twiddle without prototype.js: http://ift.tt/2mbzk2I

If you click the "Output the .clear function to console" button to output the code of the .clear function. Those are different.

Shouldn't http://ift.tt/2moXpiX handle exactly what I want?

Does anyone know if that is intended or maybe a bug? Or am I missing something?

Thanks




Ember.js - formdata returns null in ember ajax request

I have encountered an issue with formdata in ember ajax call.when im trying to send formdata with ajax request it returns null value for formdata.

heres my formdata

    var formData = new FormData();  
    formData.append('url', "http://emberjs.com");
    formData.append('urlType',2);

and ajax call

this.ajax(url, 'POST', {           
      data: formData,
      headers: {
           'Content-Type': false,
           'processData': false               
      }
 });




ember-i18n did not find a default locale; falling back to "en"

I am getting this warning for ember-i18n ("ember-i18n": "5.0.0")

//environment.js

module.exports = function(environment) {
   var ENV = { **removed default code** };
   ENV.i18n = { defaultLocale: 'en' };

   return ENV;
}

//package.json

{
  "devDependencies": {
      "ember-i18n": "5.0.0"
  }
}

//app/initializer/i18n.js

import Ember from 'ember';

export default {
    name: 'i18n',
    after: 'ember-i18n',
    initialize: function()
    {
        var application = arguments[1] || arguments[0];
        application.inject('controller', 'i18n', 'service:i18n');
        application.inject('route', 'i18n', 'service:i18n');
    }
}




mercredi 22 février 2017

Ember - advanced routing structure for user impersonation

In my app I have the following user hierarchy organisation (org) > reseller > customer. From a business perspective all three user types in the hierarchy are a customer with a :customer_id. From an app perspective they are seperate concerns, with the ability to impersonate users down the hierarchy.

So their base URL would all be the equivalent of:

localhost/org/:customer_id.

But An organisation could route into a reseller as:

localhost/org/:customer_id/reseller/:customer_id.

And both organisation and resellers could route into customers as:

localhost/org/:customer_id/reseller/:customer_id/customer/:customer_id or localhost/reseller/:customer_id/customer/:customer_id

Problems with this structure

The main issue is that every customer has it's own site and service route. And I want to avoid repeating routes under the top level :customer_id. Essentially ending up with the following.

Router.map(function() {
  this.route('org', { path: 'org/:customer_id' }, function() {
    this.route('site');
    this.route('service');
    this.route('reseller', { path: 'reseller/:customer_id' }, function() {
      this.route('site');
      this.route('service');
      this.route('customer', { path: 'customer/:customer_id' }, function() {
        this.route('site');
        this.route('service');
      });
    });
  });
});

But I'm unsure how to split the routes so that they inherit the correct URL structure but aren't nested. And in a way where each customer can access/impersonate at the correct level.

As an aside

If I can't figure out how to execute this I'm planning on using a user-service to set a currentUser variable for impersonation, and then stripping the URL to localhost/org/:org_id/ for every customer. But this won't reflect the level of impersonation in the URL.




Read Route Request Headers

I have an emberjs app where all requests are sent through a proxy that inserts some user information into the header. In my ember app I would like to read that header data and save it as a 'current user' object for every route. I cannot find how I would get access to the route request headers.

In a node app I would do this:

app.get('/', function(req, res){
  req.get('Content-Type');
});

But my emberjs route looks like this (no request variable):

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

How do I get a request object in emberjs to read the headers?




Async Headers in Ember.js

I need to insert the headers into the adapter asynchronously because the token function should check if the token is not expired and refresh it (per Ajax) if it is expired and then return the new token. But it seems the adapter can't handle the returned promises. Can anybody help me out with that issue?

import DS from 'ember-data';
import config from '../config/environment';

export default DS.JSONAPIAdapter.extend({

  // Application specific overrides go here
  host: config.APP.api_endpoint,

  headers: Ember.computed(function() {

    return this.auth.getToken().then(
      (accessToken) => {
        if (accessToken) {
          const auth = `Bearer ${accessToken}`;
          return {
            Authorization: auth
          };
        } else {
          return {

          };
        }        
      });

  }).volatile()

});



Ember order list alphabetically

I want to order the output of Extensions by name. My template includes the code below to list all extensions:

      
        
      

And my controller defines Extensions as follows:

      extensions: Ember.computed('model.stats', function() {
        let selectedExtensions = this.get('selectedExtensions');
        if (!this.get('model.stats.extensions')) { return []; }
        return this.get('model.stats.extensions').map(extension => {
          let flag = selectedExtensions.length === 0 || selectedExtensions.includes(extension);
          return new Ember.Object({value: extension, selected: flag});
        });
      }),

  setDefaultFilters: Ember.observer('model.stats', function() {
    if (this.get('selectedExtensions').length === 0 && this.get('model.stats.extensions')) {
      this.set('selectedExtensions', this.get('model.stats.extensions'));
    }

    if (this.get('selectedCountries').length === 0 && this.get('model.stats.countries')) {
      this.set('selectedCountries', this.get('model.stats.countries'));
    }

    if (this.get('selectedLangauges').length === 0 && this.get('model.stats.languages')) {
      this.set('selectedLangauges', this.get('model.stats.languages'));
    }
  }),

But the output is not ordered alphabetically. How do I order the output in such a way?




mardi 21 février 2017

Globally monitor unfulfilled promises to show indicator

I want to show "loading" indicator if there is any unfulfilled promise. And this should be global, i.e. I don't want to show/hide this indicator manually in every place.

The reason why is that Ember's "loading" route is very limited. It doesn't work with back button and in components. And I want to show this "loading" indicator always if there is a single active promise. Doesn't matter what it's doing, I don't care, just want to show the indicator.

Is there a way to do this? Or is this bad idea?




how to filter model to get data in realtime in emberfire

so i have quota model like this :

 export default DS.model.extend({
 quota : DS.attr('number'),
 sellerId: DS.attr('string'),
 buyerId:DS.attr('string') });

and i have assignQuota routes with dynamic segment like this:

 this.route('assignQuota', {path:'/assignQuota/:buyer_id'}

and in assignQuota.js :

    export default Ember.Route.extend({
    model(params) {
    const sellerId = this.get("session").get("uid");
    return this.store.query('quota',{
    orderBy:'buyerId',
    equalTo: params.buyer_id
     }).then(function(quota){
      return quota.filterBy('sellerId',sellerId)    
     }); 
     }
     });

and in my template (simplify) is like this:

      
            

          

it worked but if someone add data or delete data in quota model, the list didn't update automatically in the template.

The template only refresh after i refresh the browser. The funny thing is if I use ember inspector to inspect the data for quota, it shown that the model already changes if someone changes the model but the template didn't reflect the changes.

please help

thanks




How show component only in a specific route?

I have a componente called hero (in application.hbs) and I wish display this componente only in home page.

I researched about how do this but without any success. Thanks!




What is the right way to upload images to server (or S3) in Ember.js?

I have application built on Ember.js (2.13). I have User model and at this moment I work on avatar upload feature. When I modify model and save it then Ember makes PATCH request to my API during it Ember serializer builds nice json-api object and I like it.

When I need to upload image to server I need to make some PUT request to my API with file data I could use jQuery ajax for this. Server will resize and crop image and save it on disk or push it to S3 bucket. But I do not like this way because this request will be created bypassing Ember's serializer and without references to model. So I need to set uploaded filename to User model and save it then I'll have redundant request to server.

I have an idea to transform file to base64 string in Ember.js app and set this string to User model and save it. In this case I'll have one request to server. Is this good way to upload file?

Please advice best practice of uploading files in Ember.js application.




In my ember js application, I have a requirement that

In my ember js application, I have a template sample.hbs and inside that I have a component component1.hbs. I have flag in my model in sample.js and that flag should be available in the component1.js. Value of model is set by making an ajax call(calling a webservice) in sample.js aftreModel() function. Since ajax call is happening after component1.hbs is rendered, I was not available with the flag's value when page is loaded. My question is that where I can put the ajax call instead of aftreModel() function so that I can get the flag value in my component1.js ?




Writing a Textfile to a folder using Nodejs

I have to download the data from a Text Box in the UI to downlaod folder in .txt format.The text file needs to have a Time Stamp and should be in this format <filename + <Time Stamp>>.txt. I am using nodejs as the container and emberjs as the web framework. The code used for downloading the file to the download folder is

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="hidden" name="name" value="Output.txt" disabled="disabled">
  <textarea rows=33 cols=85 name="text"></textarea>
  <input type="submit" value="Save">
</form>
</body>
  <button id='button'>Exeute!</button>
   <script src="C:/node/jquery.min.js"></script>
    <script src='clientside.js'></script>
</html>




EmberJS: Pass data between routes

What do you recommend to pass a message between routes? What I would like to get is:

  • Sign up page where you can register yourself in the application.
  • If the register process is ok, the application will redirect you to the login page, but it should display a message with the signup response. I mean, if you reach the login page from the signup page redirection, it should display the signup message. If you reach the page directly, it should not display anything.

I have thought on creating a new path for the login route (signup_confirmation). There, if the path is signup_confirmation, it will display the message.

Thoughts?

Thank you in advance!




ember-cli-mirage in legacy app

We have application that used Pretender to provide fixtures for tests. Now we're trying to migrate to ember-cli-mirage. We cannot migrate all the fixtures at once. So what is basically happening there is that we are starting our own Pretender server and ember-cli-mirage is starting it's own. Whic renders following warning:

You created a second Pretender instance while there was already one running. Running two Pretender servers at once will lead to unexpected results and will be removed entirely in a future major version.Please call .shutdown() on your instances when you no longer need them to respond.

Since it is just a warning, it should not be an issue for the transient period. Problem is that once Mirage is loaded into our application, old Pretender routes stops responding. I guess that's what "... will lead to unexpected results" is referring to.

Any chance to run ember-cli-mirage alongside manually created Pretender routes? Or just to use Mirage server and inject those routes there?




i am new to ember js and i don't know the reason of getting the following error . please

message":"Error: Attempted to handle event didSetProperty on while in state root.deleted.inFlight. Called with {name: processing, oldValue: false, originalValue: false, value: true}.




How to send the file is POST request in Ember ? Now only the filename is being sent

triggerUpload: function() {
  Ember.$.ajax({
    url: '/api/upload_file', 
    type: 'POST',
    data: this.get('uploadedFile'),
    processData: false,
    contentType: false,
  });
};

<button class="btn btn-success" >Upload</button>

This is what I am doing and it sends the file path in the ajax call rather than the file which I want to send to the backend. Am I missing something? Can't I directly send the file through an api ? Want to send a doc file to the backend for processing and saving.




Getting error in Ember Acceptance test

In ember, I'm writing acceptance test for a template using pretender as mock server.

var server = new Pretender();
server.get('/events', JSON.stringify(200, {
  events: [
    {
      event_id: '23456789098765',
      event_time: '2017-02-01',
      event_time_formatted: '01/02/2017 06:24 AM',
      event_type: 'renewed'
    }
  ]
}));

When I run the ember test I'm getting "Unable to connect to server. Please check your network connection." error!

Can anybody tell why this happening?




How to bind an action to a 3rd-party component inside a component's template (hbs)

I am using ember-font-awesome,

http://ift.tt/1W2yFsy

When I try to bind a click action handler on the component (see code below) the action is never get triggered,

Inside my component



How can I bind a action to a component without re-open the component?




lundi 20 février 2017

Why Ember put the data related logic inside route?

I am having a discussion with anther developer. Why Ember put the data retrieve logic inside route but controller?

And the future version Ember will deprecate controller at all?

I think the reason Ember put data retrieve logic inside route is because the data (resources) is represented by using URL in Ember, hence, it is appropriate to put data related logic inside route.

However, the other developer think chaining URL does NOT necessary means the underlying data will change, better to put the logic into the controller and perform the data related task(s) as needed.




Ember Data Not Rendering

I am building a schedule for an upcoming sports season in Ember. The end goal is to have the schedule display all games by default and have the other to filter by specific team.

The schedule data is stored in FireBase and is being received by the application. But it's not being by the template.

Any help is appreciated! Code below:

// templates/schedule/index.hbs

 <div class="row">
    
      <div class="col-md-4">
        
          Venue:  Date: 
        
      </div>
    
      
        
      
        <div class="col-md-12 text-center">
          <div class="alert alert-info">
            Sorry, no result.
          </div>
        </div>
      
    
  </div>

// templates/components/schedule-item.hbs
<div class="panel panel-default schedule-item">
  <div class="panel-heading">
    <h3 class="panel-title"> -  v </h3>
  </div>
  <div class="panel-body">
    <p>Details of the upcoming game</p>
  </div>
  <div class="panel-footer">
    
  </div>
</div>

// controller/schedule.js

import Ember from 'ember';

export default Ember.Controller.extend({

  queryParams: ['filter', 'limit', 'team'],
  filter: '',
  team: '',
  limit: 'all',

  limitAll: Ember.computed.equal('limit', 'all'),

  filteredList: Ember.computed('model.@each.game', 'filter', function() {

    let results = this.get('model');
    const query = this.get('filter');

    if (!!query) {
      const regexString = '(' + query.split(' ').join(')+.*(') + ')+.*';
      const regex = new RegExp(regexString, 'ig');

      results = results.filter((item) => item.get('game').match(regex));
    }

    return results.sortBy('game');
  })

});

// model/schedule.index.js
import Ember from 'ember';

export default Ember.Route.extend({

  queryParams: {
    limit: { refreshModel: true, as: 'schedule' },
    team: { refreshModel: true, as: 'other-team' },
  },

  model(params) {

    if (params.limit === 'all') {
      return this.store.findAll('schedule');
    }

    return this.store.query('schedule', {
      orderBy: 'name',
      startAt: params.team,
      endAt: params.letter+"\uf8ff"
    });
  }

});




Request to specific nested url by DS.store methods

I have following code in route:

  model(params) {
    return this.store.findRecord('user', params.id)
  }

And how expected, it request to:

/users/{somethingId}

But my route in external api is nested and it looks like:

/partners/{somethingId}/users

Because of this, i need make something request like:

/partners/{somethingId}/users or /partners/{somethingId}/users/{userId}

I tried Ember's relationships but it didn't help me. I got url with params:

return this.store.findRecord('partner', params.id, {include:'users'});
// api/partners/5?include=users

I also tried method store.adapterFor and it was changing namespace of my adapter immediately before each request:

this.store.adapterFor('application').set('namespace', '/api/partners/' + params.id);

But making this thing all time before each request would be dirty, so I don't want going this way.

I know i can use something like ajax-ember but i'd like to use DS.store with adapters. Any help will be appreciated.




Creating an Ember CLI in-app Addon: how to install npm dependencies?

I have an "in-app" Ember addon in my project's lib directory. The addon has its own dependencies listed in its own package.json file. My project's top level package.json specifies the addon path:

  "ember-addon": {
    "paths": [
      "lib/my-addon-here"
    ]
  }

However, when I run npm install at the project root, it does not install the addon's dependencies.

Is there a way to configure this so that the addon's dependencies are installed when running npm install from the project root?




Uncaught TypeError: r.buildRenderNodes is not a function

Similar to this issue

Jon I am having the same issue moving from ember 2.9.1 to ember 2.11, i am getting this error

Uncaught TypeError: r.buildRenderNodes is not a function at Function.u.build

dependencies "gulp-htmlbars-compiler": "0.0.2",

Code

const emCompiler = require('./bower_components/ember/ember-template-compiler');

const htmlbars = require('gulp-htmlbars-compiler');

    gulp.task('compiled', ['js'], function() {
  return gulp.src(BASE +'**/*.hbs')
  .pipe(replace(NAME_TOKEN, DRIVER_NAME))
   .pipe(htmlbars({
        compiler: emCompiler,

      }))      
  .pipe(wrapAmd({
    deps: ['exports', 'ember', 'ui/mixins/driver'],
    params: ['exports', '_ember', '_uiMixinsDriver'],
    moduleRoot: 'component/',
    modulePrefix: 'ui/components/machine/driver-' + DRIVER_NAME + '/'
  }))
  .pipe(replace(
    "return Ember.TEMPLATES['template']", 'exports["default"]'
  ))
  .pipe(gulpConcat('template.js'), {newLine: ';\n'})
  .pipe(gulp.dest(TMP));
});

i tried adding the isHTMLBars: true but that does not help any ideas please?

michaeln you mentioned something about the compiler not being correct, maybe you could have an idea?




Ember JS: Mapping 3 input in a component to one value

I am working on a component for entering a date, the component will have 3 separate input fields (date, month, year) but I would like concatenate the value of each fields into a formatted value (ex 2017-01-02) that I would bind to my model.

I am using an observer to this so if any of input change I update the formatted value. I also have an observer that listen to when the formatted changed, I update the 3 fields.

The problem seem to be when I changed the formatted value, one observer kicks in, I set the value for 3 fields, then I another observer kicks in, then formatted value kicks in, etc.

I am wondering is there easier way to accomplish this?




How to change the attributes of a HTML element in emberJS from the afterModel or some similar method

I have a route and a corresponding template in my ember application. On page load itself I want to hide few elements based on URL parameter. I tried doing this in the afterModel method using jquery $.("elementName").hide(); and few other combinations. But nothing works because it seems the DOM Is not yet available. The same can be achieved as a button action in the actions section, but it doesn't help me as I would like to do it on page load. Can someone point out what I am doing wrong .




Ember-simple-auth prevent session invalidation on 401 reponse

I am using Ember: 2.11.0, ember-simple-auth: 1.2.0

I use the ember-simple-auth to authenticate my application via oauth2 to my REST API.

The standard behaviour of ember-simple-auth is to invalidate the users session if the server responds with a 401 status code. I want to handle this different and try to override this:

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.RESTAdapter.extend(DataAdapterMixin, {
  host: 'http://localhost:3000',
  authorizer: 'authorizer:oauth2',

  /*
  * The DataAdapterMixin invalidetes the session automatically if the server
  * returns the status 401. We don't want this behaviour, so we override
  * the handleResponse method.
  */
  handleResponse(status) {
    console.log(status);
    return this._super(...arguments);
  }

});

In my RestAdapter I Use the DataAdapterMixin which triggers the invalidation within the handleResponse method. So I tried to override this method in my adapter. My method is called but after my method finished, the mixins method is called by ember, as you can see here:

enter image description here

The Comments for the Ember superWrapper method state, that it is made to handle calls to methods of the super class and redirect them to it, but somehow it seems to redirect it to the mixin.

I have no idea why this happens or how to prevent this. I'd really appreciate if someone could point me into the right direction.




how to send data from component to route ember?

I am using ember js of version 2.10 And i am trying to send data from component to route.

Here is my component template

<div class="pull-right search-section">
    <form class="form-inline search-box" >
      <button type="submit" class="btn"><i class="glyphicon glyphicon-search"></i></button>
      <div class="form-group">
        
      </div>
    </form>
    <a href="#" class="link-advance-search">Advance Search</a>
</div>

Now I am trying to send data to route from component js file with following code import Ember from 'ember';

export default Ember.Component.extend({
  save: function () {
        var search = this.get('search');
        console.log(this.sendAction('saveAction',search));
  }
});

And trying to get at route js file with following code

import Ember from 'ember';
export default Ember.Route.extend({  
    actions: {
        saveAction: function(search_string){
            alert('fhdishf');
        }
    }
});

But unfortunately did not getting anything.

Thanks in advance.




show hide button depending on time in ember.js

How to hide the button for 5s in ember.js

This is my template activation.hbs


  Resend Code


and this is my controller activation.js

hideResendCode:Ember.run.later((function() {

 }), 5000),

I don't know how to hide this button for 5s please help me.




How do you organize yung acceptance tests in Ember?

I believe in the concept that for every user story, there should be an acceptance tests to indicate that the story is done and it works. However, this won't scale when you already have numerous acceptance tests. Everything will live in the root of tests/acceptance/ directory.

I'm thinking of making it that there should be an acceptance test file for every route and all acceptance test for it should live in that file. I'm curious though of what other possible conventions there are for organizing acceptance tests. Any other suggestions?




How to compile glimmer2 template for Ember 2.8+

Recently we have started a wide scale upgrade of our EmberJS system. And currently we are at 2.11 version of ember. With EmberJS 2.11

Ember.HTMLBars.template

and

Ember.Handlebars.template

all come via a single template function and expect JSON (ie. compiled glimmer2 template)

Currently trying to get a simple "Hello world" message appeared. I have routes working, but Ember.HTMLBars.template expect glimmer2 JSON.

How do I make "Hello world" glimmer template and compile it to JSON?

Ember expects JSON something like

Ember.TEMPLATES["test/fixtures/simple"] = Ember.HTMLBars.template({"id":null,"block":"{\"statements\":[[\"open-element\",\"p\",[]],[\"flush-element\"],[\"text\",\"Hello, my name is \"],[\"append\",[\"unknown\",[\"name\"]],false],[\"text\",\".\"],[\"close-element\"]],\"locals\":[],\"named\":[],\"yields\":[],\"blocks\":[],\"hasPartials\":false}","meta":{}});

I have got http://ift.tt/1X7w6Wp built, but not sure what to do next. At the end, I need to get basic hello_world.hbs to compile into JSON. I am a very new person in this area.

Any help appreciated

Thank you

Dimi




dimanche 19 février 2017

Ember: handling JSON response from ember-network promise in component

I'm trying to implement a simple autosuggest in a component. I'm trying to use fastboot and therefore am using ember-network to communicate with my API. Not using ember-data. Whether or not this is the "ember" way to do it is a different question...I'm just trying to get this to work.

My component JS:

import Ember from 'ember';
import fetch from 'ember-network/fetch';

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

    loadAutoComplete(query) {
        let suggestCall = 'http://ift.tt/2mdbS15' + query;
        return fetch(suggestCall).then(function(response) {
            return response.json();
        });     
    },

    searchResults: Ember.computed('searchText', function() {
        let searchText = this.get('searchText');
        if (!searchText) { return; }
        let searchRes = this.loadAutoComplete(searchText);
        return searchRes;
    })
});

And in the template:





<li> </li>


The template log directive is outputting this in my console:

console

The data is in "suggestions", so I know the fetch is working. I just can't figure out how to get at it. I can't loop over '_result'. What do I need to do to parse this and use it in a template?




multiple relations using same model type in ember data

I have an account model that has the following:

export default Model.extend({
  primaryStaff: belongsTo('staff'),
  secondaryStaff: belongsTo('staff')
});

primaryStaff maps to the primaryStaffId key on the account model and secondaryStaff maps to secondaryStaffId. Is there a way to allow these to both point to the staff model?

Not having any luck. Thanks!




ember/handlebars - How to toggle object class based on boolean?

I have a form styled with bootstrap4 and am using ember-cp-validations to validate it.

  <div class="form-group ">
    <label for="name" class="cols-sm-2 control-label">Full Name</label>
    <div class="cols-sm-10">
      <div class="input-group">
        <span class="input-group-addon"></span>
        
      </div>
    </div>

    
      
        <div class="form-control-feedback container">
          <span></span>
        </div>
      
    
  </div>

Using , I am able to set the class to has-danger when showNameError is true, however when it is false, the class remains there and the has-danger persists.

  1. When the page loads step 1

  2. When I force the error step 2

  3. After I fix the error enter image description here

As you can see, after I fix the error the has-danger class remains. My question is, can I make it so the class toggles based on whether the input is valid or not.




EmberJS: Escape entire template

All, I'm writing an EmberJS addon that produces an application that can be used with JSP.

The problem I'm running into is that I need to escape large chunks of code so ember cli doesn't error out on me.

Is there a way to force ember to ignore error checking on a specific file?

tyia