samedi 30 avril 2016

Ember CLI: Attempting to register an unknown factory: `controller:object`

My ember-cli version is 0.2.3. I am getting the following error when I try to run tests.

TypeError: Attempting to register an unknown factory: `controller:object`
    at Object.Registry.register (http://localhost:7357/assets/vendor.js:12208:15)
    at Object.container.(anonymous function) [as register] (http://localhost:7357/assets/test-support.js:1905:44)
    at Object.isolatedContainer [as default] (http://localhost:7357/assets/test-support.js:1946:15)
    at exports.default.klassy.Klass.extend._setupIsolatedContainer (http://localhost:7357/assets/test-support.js:2406:52)
    at exports.default.klassy.Klass.extend.setupContainer (http://localhost:7357/assets/test-support.js:2312:14)
    at nextStep (http://localhost:7357/assets/test-support.js:2300:53)
    at exports.default.klassy.Klass.extend.invokeSteps (http://localhost:7357/assets/test-support.js:2305:14)
    at exports.default.klassy.Klass.extend.setup (http://localhost:7357/assets/test-support.js:2275:19)
    at Object.qunit.module.setup (http://localhost:7357/assets/test-support.js:1814:16)
    at runHook (http://localhost:7357/assets/test-support.js:3534:20)

Any idea on what might be causing this? Looking like a ember-cli internal issue.




Firebase, Ember and Emberfire create user

Firebase offers some easy ways to create users:

I'm currently using EmberFire (Add-on) with Firebase, and I'm wondering how this would translate to use in Ember:

var ref = new Firebase("http://ift.tt/1Fh4OSN");
ref.createUser({
  email: "bobtony@firebase.com",
  password: "correcthorsebatterystaple"
}, function(error, userData) {
  if (error) {
    switch (error.code) {
      case "EMAIL_TAKEN":
        console.log("The new user account cannot be created because the email is already in use.");
        break;
      case "INVALID_EMAIL":
        console.log("The specified email is not a valid email.");
        break;
      default:
        console.log("Error creating user:", error);
    }
  } else {
    console.log("Successfully created user account with uid:", userData.uid);
  }
});

So you can then create a user, save it to Ember Data and also save it in Firebase? There are also other methods changeEmail(), changePassword() etc... so I'm simply looking for an example to apply this to Emberfire ?




Zurb foundation drop down menu not works

I am starting to learn ember and try to incorporate some navigation bar using zurb foundation framework. I have a problem with dropdown menu. Check this link

 <ul class="title-area">
    <li class="name">
       <h1><a href="#">Home</a></h1>
    </li>
    <!-- Remove the class "menu-icon" to get rid of menu icon. Take out "Menu" to just have icon alone -->
    <li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a></li>
 </ul>

 <section class="top-bar-section">
    <ul class="left">
       <li class="has-dropdown">
          About
          <ul class="vertical dropdown menu" data-dropdown-menu>
             <li click>Team</li>
          </ul>
       </li>
       <li click>About/Team again</li>
       <li>Contact</li>
    </ul>

 </section>

I can not achive to trigger route when clicking on About/Team. When clicking on "About/Team again" then route works.

Any idea why this happens?




Create a computed bool using relationship field Ember

I'm trying figure out how my computed property identify if my relationship was set.

author: BelongsTo('author'),
hasAuthor: Ember.computed.bool('author')

I need change my css based if has a author.


//---------- my-component.js
export default Ember.Component.extend({
  classNameBindings: ['hasAuthor'],
  hasAuthor = Ember.computed( () => get('post').get('hasAuthor') )
});




Ember-cli specify node.js debug port

To use node.js remote debugging, I could set a debug port to 8001 when starting the server with node --debug=8001 app.js. How can I do this using ember-cli? Thanks in advance.




Issue loading records via Ember CLI Mirage in unit test

I get the following error Mirage: Your Ember app tried to GET '/statements', but there was no route defined to handle this request. Define a route that matches this path in your mirage/config.js file. Did you forget to add your namespace?

This is while trying to use mirage in a unit test. My acceptance tests work well and seem to load the records just fine. But that is probably because the whole ember app is booted for the acceptance test ?

I'm really sure my config is correct, I have it set up by exporting testConfig:

export function testConfig() {

  this.urlPrefix = 'http://0.0.0.0:3000'

  this.get('/languages', languages)

  this.get('/statements', statements)

Code currently as follows:

//services/fake.js

import Ember from 'ember'

const { Service, A, inject: { service } } = Ember

export default Service.extend({

  store: service(),

  statements: A(),

  loadFakeStatement(){
    this.get('statements').addObject(Ember.Object.create({
      title: 'Statement 1',
      option: 'A'
    }))
  },

  loadRealStatements(){
    this.get('store')
    .findAll('statement')
    .then(statements => {
      this.get('statements').addObjects(statements)
    })
  }

})

// tests/unit/services/fake-test.js

import { moduleFor, test } from 'ember-qunit'
import startMirage from '../../helpers/setup-mirage-for-integration'

moduleFor('service:fake', 'Unit | Service | fake', {

  needs: ['model:statement'],

  beforeEach() {
    startMirage(this.container)
  },

  afterEach() {
    window.server.shutdown()
  }
})

test('initializes correctly', function(assert) {
  const service = this.subject()
  assert.ok(service)
})

test('loads fake data correctly', function(assert) {

  const service = this.subject()

  assert.equal(service.get('statements.length'), 0, 'statements initially 0')

  service.loadFakeStatement()

  assert.equal(service.get('statements.length'), 1, 'statements populated by load')
})

test('loads mirage data correctly', function(assert) {

  const service = this.subject()

  assert.equal(service.get('statements.length'), 0, 'statements initially 0')

  service.loadRealStatements()

  assert.equal(service.get('statements.length'), 1, 'statements populated by load')
})




Cannot read property 'type' of undefined

I tried setting my app in ember@2.5.0, but every time when I use store and try to use

this.store.findAll("user");

I always get the error saying Cannot read property 'type' of undefined.

Initialized the store, adapter and the model and server too.

adapters/application.js

import JSONAPIAdapter from 'ember-data/adapters/json-api';
export default JSONAPIAdapter.extend({
    defaultSerialiser: "-default"
});

models/user.js

import Model from 'ember-data/model';
import attr from 'ember-data/attr'
export default Model.extend({
    "name": attr()
});

and server side it is like

app.get("/users", function(req, res) {
    res.send({"name": "Surya"});
});

Getting error

TypeError: Cannot read property 'type' of undefined
at _pushInternalModel (store.js:1524)
at push (store.js:1501)
at finders.js:148
at Object.Backburner.run (ember.debug.js:678)
at _adapterRun (store.js:1733)
at finders.js:145
at tryCatch (ember.debug.js:53806)
at invokeCallback (ember.debug.js:53821)
at publish (ember.debug.js:53789)
at ember.debug.js:32054




vendredi 29 avril 2016

Create Child Records in hasMany Relationship with Ember.Js

First time using Ember.

I have two models one is post model and another is comments model

export default DS.Model.extend({
  postName: DS.attr('string'),
  postedDate: DS.attr('string'),
  postcontent: DS.attr('string'),
  comments: DS.hasMany('comment', {async : true})
});

export default DS.Model.extend({
  comments: DS.attr('string'),
  post: DS.belongsTo('post')
});

In the post home page, I will fetch the metaInfo of post like postName and postedDate using this.store.peekAll('post') now ember data is updated with post metaInfo postName and postedDate, I will not load comments.

When the user clicks on the post I have to get the content of the post and display the post content.

when the user clicks on the comment section, I have to get 10 comments among 100 comments.

How could I do this please help me out on this.

Grateful for any assistance!




Ember: hasMany relationship doesn't always load on transitionTo

I think I'm missing something about how Ember Data works. I have a route that updates stats for the players on a team:

    export default Ember.Route.extend({
        stats: Ember.inject.service('constants'),
        actions: {
            submitStats(updates){
                let id = this.get('context').get('id');
                let team = this.store.findRecord('team', id);
                let players = team.then(t => t.get('players'));
                players.then(ps => savePlayers(ps, updates, this.get('stats')))
                       .then(p => {console.log("All saved!");
                                   this.transitionTo('team', team.get('id'))})
            }
        },

        init() {
            // we seemingly need to make sure all the players are loaded
            // before calling the component
            this.store.findAll('player');
        }
    });

The first time I update the stats, I transition to the team route and it all looks like I expect (and I see the stats for all players on the team). If I go submit stats a second time, I only see some of the players. Currently, my team route looks like the following:

export default Ember.Route.extend({
    beforeModel(transition){
        return this.store.findAll('player')
    },
    model(params){
        return this.store.findAll('player').then(p => {console.log("players loaded");
             return this.store.findRecord('team', params.team_id)})
    }
});

I'm assuming I'm missing... something about how models and transitions work together. What is it?




Ember-data ie9 post requests not working

I'm using ember-data 4.2.0 and ember-ajax 2.0.1 and having trouble with ie9. I've read that ie9 uses the old XDomainRequest instead of the newer XHR request, and that it only sends blank or text/plain content-types. I have a rails api that ember-data posts to and it's working fine on Chrome, Firefox, and ie10+, but in ie9 I can see that the payload isn't sending with a json content-type, so the server is just getting a plain text string, which is doesn't recognize as a params hash expecting json data.

Someone suggested I do something like this, but it's not working for me.

export default DS.JSONAPIAdapter.extend({
  host: ENV.apiUrl,

  ajaxOptions(url, type, hash) {
    hash.contentType = 'application/json';
    hash.dataType = 'json';

    return this._super(url, type, hash);
  }
});

All of the store requests are standard this.store.create('whatever', payload) type requests.

Ember's docs say it supports ie9 in ember 2+, so I assumed this would work out of the box. Am I missing something to make this work?




Promise result in Ember Data computed property

I'm trying to make a call to an external API and use the results as a computed property in my Ember Data model. The result is fetched fine, but the computed property returns before the Promise resolves, resulting in undefined. Is this a use case for an Observer?

address = Ember.computed('lat', 'lng', function() {
  var url = `http://ift.tt/1SDrXGA}`;
  var addr;

  var request = new Ember.RSVP.Promise(function(resolve, reject) {             
      Ember.$.ajax(url, {                                                        
        success: function(response) {                                            
          resolve(response);                                                     
        },                                                                       
        error: function(reason) {                                                
          reject(reason);                                                        
        }                                                                        
      });                                                                        
   });                                                                          

   request.then(function(response) {                      
     addr = response.results[0].formatted_address;                              
   }, function(error) {                                                         
     console.log(error);
   })  

   return addr;
})




Emberjs - how to reset a field on a component after saving?

I have an embedded object called Comment, inside a Game. Each game can have many Comments.

When a user (called a Parent) views the game page, they can leave a comment.

The problem I have is that I cannot seem to reset the body of the comment field back to empty after the comment is saved.

This is the component:

MyApp.AddCommentComponent = Ember.Component.extend({

  body: '',
  actions: {
    addComment: function() {

      var comment, failure, success;
      if (!!this.get('body').trim()) {
        comment = this.store.createRecord('comment', {
          body: this.get('body'),
          game: this.get('game'),
          parent_id: this.get('parent_id'),
          parent_name: this.get('parent_name')
        });

        success = (function() {
          this.set('body', '');
        });
        failure = (function() {
          return console.log("Failed to save comment");
        });
        return comment.save().then(success, failure);
      }
    }
  }
});

The error is on the 'this.set' line - this.set is not a function

All the examples I find are about doing this in a controller or by creating a new record upon route change (but the route is not changing in my example, since it is just adding another embedded object to the existing page).




How to override a parent property in ember.js?

I want to write a new component that extends Ember Input as number input. When users of this class binds their values to value property of number-input-component, they should only get a number (or NaN for invalid values). In Ember Input, value has an attribute binding.

I've defined a computed property named "value" on number-input-component as following:

value:Ember.computed({
    get:function(key){
       let htmlValue = this.get('htmlvalue');
       return this.sanitize(htmlValue);
    },
    set:function (key, htmlvalue){
       this.set('htmlvalue', htmlvalue);

       if(this.get('onUpdate')) {
          this.get('onUpdate')(this.sanitize(htmlvalue));
       }
       return this.sanitize(htmlvalue);
    }
}),

It works as expected but it's not working in two-way binding. (Actually it is ok for DDAU. But it should work in two-way bindings.)

Note: I know that I can supply another property such as "numericValue" (shown as here) so that users can bind their values to "numericValue". But I don't want to confuse users with both value and numericValue.




Upgrade emberjs script to support latest version

I am using

Emberjs: v1.8.0

and I have the following simple code

<html>
   <head>
      <title>Important data</title>
      <script src="/handlebars.min.js"></script>
      <script src="/jquery-2.1.3.min.js"></script>
      <script src="/ember.min.js"></script>
      <script src="/ember-template-compiler.js"></script>
      <script src="/ember.debug.js"></script>
      <script src="/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars">
         
      </script>

      <script type="text/x-handlebars" data-template-name="index">
         
Name         : <font color='blue'></font><br>
City         : <font color='blue'></font><br>
State        : <font color='blue'></font><br>
            <button >Edit</button>

          
Name         : <br>
City         : <br>
State        : <br>
            <button >Done</button>
         
      </script>

      <script type="text/javascript">
         App = Ember.Application.create();
         App.ApplicationRoute = Ember.Route.extend({
            model: function() {
               return [{otherdata:''}];

            }
         });

         App.View = Ember.View.extend({
            templateName: 'index',
            isShowVisible: true,
            actions: {
               importantdata: function(){
                  this.toggleProperty('isShowVisible');
               }
            }
        });

      </script>
   </body>
</html>

The emberjs version used in this script seems to be outdated. And also I heard that the latest version of emberjs(v2.4.x) is working in whole different way.

I want to upgrade the script to support the latest version of emberjs.

Any help for me on this?

It would take much time for me to learn entire latest version of emberjs.

Much appreciated, if anyone has quick solution for me on this.

What are the changes I have to done to make the above script to support latest version of emberjs?




Unable to observe an array of objects in Ember.js?

I have an array of objects within a component like this:

checkboxes: [
    {
        label: 'A',
        state: false
    },
    {
        label: 'B',
        state: false
    },
    {
        label: 'C',
        state: false
    }
]

In my Handlebars template, I have a loop to show the list of checkboxes and each checkbox state maps back to the array item like this:


    <li><input type="checkbox" checked=> </li>


I wrote an observer to observe changes to the array but it doesn't seem to work:

observeCheckboxes: function() {
    console.log(this.get('checkboxes').toArray());
}.observes('checkboxes.[]')

How do I observe changes to the checkbox states so I can get a list of checked items?




Ember Engine Uncaught Error: Could not find module ember-views/views/select

Created new app with

ember new app-name

after running

"ember s"

App works proper in browser

As per guide at http://ift.tt/1Narec3 for running ember engine ran below command

ember install ember-engines

rm -rf bower_components

bower install --save ember#canary #Choosed ember#canary from prompt

bower install

And now when i do "ember s" app gets compile properly in CLI but app gets crash in browser and i see nothing in browser.

In console i see below error message

Uncaught Error: Could not find module ember-views/views/select

Tried debugging it, Could not find solution. Is i am missing somthig basic here ?

Note :: I am new to ember. I think this would be small one but could not find solution on web as well.




Validate a part of the form in Ember

I have a component which serves a form in an ember application. The form is split into sections rendered in an accordion format. I use Ember validations to validate the form. The validations for the entire form is defined and this.validate() will help getting the errors for the entire form. But, whenever a section is collapsed, a green tick icon or a red cross icon needs to be shown based on the value of fields in that section alone, which means I need to validate the fields in that particular section (a part of the form). How do I do this?

For context, the properties of the form fields follow these two patterns - accordion item 1 - [model.rship1.*], accordion items 2, 3 and 4 - [model.rship2.*]. I tried using in accordion item 1, but the length value doesn't seem to change even if I edit it. Can you suggest me a proper working way to achieve this, please?




Disable Ember.Logger.log() in production build

I want to disable all the logs while building production build. I am using ember 2.5 latest version.




jeudi 28 avril 2016

Ember js 2 counts related field (hasMany)

I feel confused with the access to ember model in the controller using a compute property.

My issue: I’m trying to create two properties one to count the related objects of hasMany field marcanet, and second limit the size of this property to only display n elements.

First scenery computes property on Model:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';
import Ember from 'ember';

export default Model.extend({
    client: attr('string'),
    figure: attr('string'),
    marcanet: hasMany('marcanet'),
    title: attr('string'),
    tm_type: attr('string'),

    total: Ember.computed('marcanet.length') {
        return this.get('marcanet.length');
    }.property('model')
    // issue i can't render it on my template as 
    // so, I can't understand if it is computed right.
});

Second scenery moving to the Controller.

Here I only can access to the main object Trademark

import Ember from 'ember';

export default Ember.Controller.extend({
    // It works
    sliceTrademarks: function() {
        return this.get('model').slice(0, 5);
    }.property('model'),
    // It works
    totalTrademarks: function() {
        return this.get('model.length');
    }.property('model'),

    // It throws me an error TypeError: this.get(...) is undefined
    sliceMarcanet: function() {
        return this.get('model.marcanet').slice(0, 2);
    }.property('model'),
    // It only give me an empty result
    totalMarcanet: function() {
        return this.get('model.marcanet.length');
    }.property('model')
});




Ember-data: store.query properly returns array but still throws error 'expecting array, found single record'

I have the following express route for 'get all locations':

router.get('/', function(req, res){

    let q = req.query;

    let locations = Location.find({organization: q.organization});

    locations.then(r => res.status(200).send(r))
        .catch(err => res.status(500).send(err));
});

And this ember model hook triggers it correctly:

model(){
    return this.store.findRecord("user", this.get('session.currentUser.id'))
      .then(user => user.get('organization'))
      .then(org => this.store.query("location", {organization: org.id}))
}

Now, this query is sending a get request to the following url with params:

GET /locations?organization=571974742ce868d575b79d6a

And my server is returning a 200 success code but then the model hook is crashing with this error:

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

Creating a postman request to the same address:

localhost:3200/locations?organization=571974742ce868d575b79d6a

I see an array returned, filled with the proper objects, like so:

[{object1}, {object2]

Which seems like the correct response. Why might Ember be telling me that it's only receiving a single record?

It even throws me this warning when the model hook is called:

WARNING: Encountered "0" in payload, but no model was found for model name "0" (resolved model name using lc-dash@serializer:application:.modelNameFromPayloadKey("0"))

Thanks for any wisdom you can lend here Ember folks!




What Component? A property of $SOMEOUTLET was modified inside the didInsertElement hook

I have an app with a number of components on the page. I'd really like to know what component a given deprecation is related to. Is there a way to map an outlet to a component?

In other words if I get:

A property of <frontend@view:-outlet::ember673> was modified inside the didInsertElement hook. You should never change properties on components, services or models during didInsertElement because it causes significant performance degradation.

What component is being used for ember673 ?




How to stub a javascript library like html2canvas

I have to test an ember app that uses html2canvas library, but the test is failing and I believe its because of the promise. I have already wrapped the asynchronous part like this:

/**
 * This method render DOM object (webpage) and generated canvas object using html2canvas library.
 * After getting canvas object it set image property.
 *
 * @method 'captureScreen'
 * @param {DOM}
 * @return {Ember.RSVP.Promise}
 */
captureScreen: function (dom) {
    return new Ember.RSVP.Promise((resolve) => {
        html2canvas(dom).then((canvas) => {
            resolve(canvas);
        });
    });
}

So now I am trying to stub the html2canvas lib itself like this:

stubHtml2Canvas = function () {
    _stubHtml2Canvas = sinon.stub(html2canvas).returns(new Ember.RSVP.Promise(function (resolve) {
        resolve(document.createElement("CANVAS"));
    }));
}

but this throws out following err:

beforeEach failed on should show overlay when clicking on the insight capture button: Attempted to wrap undefined property undefined as function

I had also tried

sinon.createStubInstance(html2canvas).returns(new Ember.RSVP.Promise(function (resolve) {
        resolve(document.createElement("CANVAS"));
    }));

But that didn't work either.




EmberJS - how to restructure embedded models?

Note: Using Ember Rails 0.18.2 and ember-source 1.12.1

I have inherited an Ember app that has a strange function. I am new to Ember so maybe this is normal, but I find it odd.

There are 3 models:

  1. Parents
  2. Games
  3. Comments

When a Parent views a game the url looks like this:

/<parent slug>/games/<game_id>

(the slug is just a unique id for the parent).

At this url there is a template that has this code:

  
  Chat with parents in your pod
  

  

Clicking the above button then changes the url to this:

/<parent slug>/games/<game_id>/comments

Then all the comments appear for that game.

I need to remove that button from the view and have Comments display automatically for each Game.

The API is Rails, and I can already change the API endpoint to return all the Comments at the same time a Game is requested (as an embedded array of objects).

But what do I replace with? Because my understanding is that is delegating to the Comments template due to this route:

App.CommentsRoute = Ember.Route.extend
  model: ->
    return this.store.find('comment', {
      game:   @modelFor('game').get('id')
      parent: @modelFor('parent').get('slug')
    }).then( (models) -> models.toArray() )

I believe I need to remove that route and make the Comments an embedded object inside the Game model. Do I then just replace outlet with something like:



<div class="commentItem">
  <div class="commentItem-author"></div>
  <div class="commentItem-body"></div>
</div>






mercredi 27 avril 2016

Ember cannot trigger controller property second time

I have a multi-step workflow kind of flow,

So I transition from Step1 > Step2 > Step3

While transitioning from Step2 to Step3, I set some property on controller of step3 (in 'then' callback i.e. set post transition complete)

This works the first instance, but if I go back to Step1 and restart the flow, even though I set the property on controller of step3 again, it does not get triggered and I see previous/stale data on Step3.

How do I force the controller property to be triggered each time ? (I have it as computed property)




Ember handlebars concat string and variable always appends white space

var categories = ['item1', 'item2', 'item3']


  


will produce: ,item1 ,item2 ,item3

How do i remove the whitespace before each string?




How to display query parameters in our own specific order

I want my query parameters to be shown like

code=1,id=2,category=3

here is how they are shown

category=3,code=1,id=2

I know i can rename them in my code to be in the right alphabetic order and then i can set "as" for the display names of my query parameters. This way i can get what i want. I was wondering if there is any better way of doing that?




Best way to rollback all changes to an ember-data model

I am using ember-data to edit a user with automatic model resolution

this.route('user', function() {
  this.route('edit', { path: ':user_id'})
});

This works fine and the user can modify all aspects of the model DS.attribute, DS.belongsTo and DS.hasMany.

The user can navigate away in a number of ways, in which case all changes should be removed from the model.

  • Clicking a Cancel button
  • Clicking the Broswer Back button
  • Clicking the Save button but the promise fails.
  • Just Clicking some other link on the page which takes them somewhere else.

The changes should only be applied if the user explicitly wants them to by clicking the Save button which consequently succeeds.

I considered using ember-buffered-proxy but I am not sure how this will cope with DS.belongsTo and DS.hasMany relationships. Regardless, before saving the model I will need to do buffer.applyBufferedChanges(); before saving and if the server fails I am in the save situation as before.

The willTransition hook in the browser seems like the obvious place to do this but how can I ensure all changes are removed from the model given rollbackAttributes() only works for DS.attribute controls.




Error loading belongsTo relationship in Ember 2

I am having issues loading a belongsTo relationship - no errors get displayed, and no requests sent. The UI just remains blank. Given the following models:

project.js import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr(),
    items: DS.hasMany('line-item', {async: true}),  
    customer: DS.belongsTo('customer', {async: false})  
});

customer.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr(),
    email: DS.attr(),
    projects: DS.hasMany('project', {async: true})  
});

The relationship between project and customer exists. When accessing the projects endpoint, the project gets correctly returned:

{  
   "data":{  
      "type":"projects",
      "id":"3861b834-e270-4296-b7be-9aca55676874",
      "attributes":{  
         "created":"2016-04-27T22:36:01.061349Z",
         "modified":"2016-04-27T22:36:01.061477Z",
         "name":"Sample name",
      },
      "relationships":{  
         "customer":{  
            "data":{  
               "type":"customers",
               "id":"9242bd41-6bb0-41ed-b5f3-21df26486d9e"
            }
         },
         "items":{  
            "meta":{  
               "count":0
            },
            "data":[  

            ]
         }
      }
   }
}

However when trying to access the customer, nothing happens (with nothing I mean: no console output, no request to the customers endpoint etc. The UI just fails to load):

this.get('project').get('customer');

Accessing other attributes works (including the project's items).

Any idea as to where I am going wrong?




Handlebars bind a dynamic object property

When using Ember and Handlebars, is it possible to bind (two-way) a dynamically determined property of an object.

instead of the statically determined style

I have tried:

but that only results in a one way binding.




ember model -making a table of items click for detail

I am just learning emberjs and have been given a barebones task.

I have a table of users displayed from my model. To the side of the table, I have an area where it will display details of a selected user. Thus:

ID FNAME LNAME         | DETAIL: User 2
1  Andy  Ashford       | First: Betty
2  Betty Beckett       | Last: Beckett
                       | Phone: 222-222-2222

I've got the LEFT side working, but not the RIGHT side.

(I'm using Mirage to load data. I could not seem to get http-mocks to work).

Two questions:

  1. Should I

    • route this directly within script or
    • should I use the path? i.e. When just the users table is displayed, my path is /users/, but when I click on user 1, I could set the path to /user/1, then do all my logic from there.
  2. With either method, how do I deliver the specific user data to the user-detail component? How do I point the model at the view?

Here is my Mirage/config.js (don't know why Mirage keeps data in a config file, but...)

this.get('/users', function() {
    return {
        data: [{
            type: 'users',
            id: 1,
            attributes: {
                fname: 'Andy',
                lname: 'Ashford',
                phone: '111-111-1111',
            }
        }, {
            type: 'users',
            id: 2,
            attributes: {
                fname: 'Betty',
                lname: 'Beckett',
                phone: '222-222-2222',
            }
        }]
    };
});

My models/user.js just looks like this:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({
    fname: attr(),
    lname: attr(),
    phone: attr()
});

My main templates/components/user-list.hbs (this is working - table on left, though detail on right has no data):

<table class="with-detail"><tr>
        <td class="table-overview">
            <table class="user-table">
                
                <tr>
                    <td> </td>
                    <td></td>
                    <td></td>
                </tr>
              
            </table>
        </td>
        <td class="table-detail">
            <!-- Show all data of user X -->
            <!---->

        </td>
    </tr>
</table>

My templates/components/user-detail.hbs (I can see the labels in the detail, so I'm calling the template, but no data):

First name:  //these don't work of course
Last name: 
Phone: 

This is what I've been trying to do with the router.js:

Router.map(function() {
  this.route('users', { 
      path: 'users', 
  });
  this.route('user', { 
      path: 'user/:id' 
  });
});

And for good measure, there are additionally some routes. routes/users.js:

import Ember from 'ember';
export default Ember.Route.extend({
    model() {
        return this.store.findAll('user');
    }
});

routes/user.js:

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return this.store.query('user', { id: 1 });    
    }
});

(and why so many route files?)

If I hit user/1 directly, I see nothing - no table, no detail (presumably because /users/ and its model have gone away).

I'm sort of stumped.




Servers needed for Ember.js

What is the server needed to launch an

ember.js

sample application in windows? What is the exact procedure for the same?




Ember.run.bind is not working

I am trying to get ember.run.bind to work but it just doesn't seem to work, any idea? I have tried all combinations

_didInsertElement: Ember.on('didInsertElement', function () {
    Ember.run.bind(this, this.doSomething);
  })

or

_didInsertElement: Ember.on('didInsertElement', function () {
    Ember.run.bind(this, function() {
      this.doSomething();
    });
  })

or

_didInsertElement: Ember.on('didInsertElement', function () {
    var _this = this;
    Ember.run.bind(this, function() {
      _this.doSomething();
    });
  })




Chrome HTML5 file input type memory leak (Ember.js)

In a mobile web application that heavily uses chrome's local storage I noticed I ran out on space too quickly after a while while taking pictures and storing them. I set up a barebone Ember application with a single file input type to narrow the problem:

index.hbs

<form>
  <input id="file" type="file" accept="image//*" capture="camera">
</form>

<button id="clear" >
  Clear File input
</button>

index.js (controller)

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    reset: function(){
      Ember.$('#file').wrap('<form>').closest('form').get(0).reset();
      Ember.$('#file').unwrap();
    }
  }
});

When accessed from a tablet it will display three options to upload a file: Documents, Camcorder and Camera. When files are uploaded from the first two the Data of Chrome app won't increase as it is temporarily stored until further operations (e.g. storing it locally via the Local Storage API).

enter image description here

However, when pictures are uploaded using the Camera, the Data memory will increase and will never be released, even if for example we take another picture or upload another file. Each picture taken increases memory that will never be freed, not even refreshing or closing & reopening the browser, the only way is to Clear Data.

Logic in the controller was in hope of when clearing the input field memory would be released but it is not the case.

Chrome version is 49.0.2623.105 (Official Build) (32-bit)




Fade In / Fade out in liquid-fire

I have a ember template with 2 sections, where one section is visible by default and other one is hidden until I hit a button.

I am using liquid-fire, most specifically the liquid-if helper to do a simple fade in / fade out of the 2 sections. This works however there is a slide up / slide down that occurs between toggling the 2. As anyone seen this behavior before? I would to prevent this slide effect from happening

Here's sample how template looks like:


    <h1 class="text-center"></h1>
    <p class="text-center">
        <br/>
        
        <i class="fa fa-envelope-o email-icon"></i>
    </p>



    <h1 class="text-center"></h1>
    <p class="text-center">
        <br/>
        
    </p>
    


Here's a sample of my transition

this.transition(
    this.hasClass('lf-fade'),
    this.toValue(true),
    this.use('fade', {
        duration: 600
    })
);




Data not showing - Ember js - Rest Api

So I've had a look around and can't really find a solid answer.

I have a model for page and I have a route to get the data from an Api and the data comes though into the ember inspector but when I try to call it on the page it doesn't show.

http://ift.tt/1SJV25q

I've tried , nothing shows.

I've read I need a controller but I've seen examples without a controller do the same thing.

What an I missing?

http://ift.tt/1VOXnQG




Ember.js serializer TypeError: payload.map is not a function

I am new to Ember and I am using a JSONSerializer to change my JSON. This is my code

import JSONSerializer from 'ember-data/serializers/json';

export default JSONSerializer.extend({
 normalizeResponse(store, primaryModelClass, payload, id, requestType) {

 var listOptions = payload.clients;


 for(i = 0; i < listOptions.length; i++) {
  //we do some operations and we end up with foo
 }

 newData = foo;

 for(i = 0; i < payload.clients.length; i++) {
    payload.clients[i].NAME = newData[i].text; 
    payload.clients[i].id = newData[i].value; 
 }

 return this._super(...arguments);

}

And in the return I get this error:

ember.debug.js:27431 Error while processing route: index payload.map is not a function TypeError: payload.map is not a function

My version of Ember is 2.4.3 .

So gurus of Ember what is going wrong with my code?, my return is exactly like the ones from the documentation and I am getting a bit desperate. http://ift.tt/1VRZQKi .

Thank you very much.




Has Ember.js fallen idle? [on hold]

I'm currently using Ember for a startup project and the changelog during the past year really isn't reassuring.

Indeed, as the list shows, the vast majority of changes during the past year are prefixed with [BUGFIX], [CLEANUP] and other similar tags, but almost no [FEATURE] ones. We've been waiting for angle bracket components for a very long time already and there aren't any news on the subject. It's totally fine to dedicate some time to refactoring and cleanup, but doing that almost exclusively for 1 year is, to me, a big problem.

Another worrying fact is that nobody seems to care about this situation, based on the absence of discussions about that on the web. All of the excitement seem to be around the React ecosystem, which I'm more and more considering. Not for the hype reasons, but more as a business decision: as a CTO, I don't want my code to be locked in a framework that could potentially be blocking or slowing us down and I'm thus more and more leaning towards the libraries approach. Furthermore, React Native looks super promising and is pushing me even more to reconsider using Ember.

What are your reactions (no pun intended) on this ?




mardi 26 avril 2016

How do I set up roles in firebase auth?

I am currently logging in with email and password. But I would like to be able to assign a role to each user: admin or user. I have read that this is done by using the custom auth method, but I find the docs not clear to implement with email/password authentication.

How would I go to set that up?

I am currently using firebase for ember emberfire

Update:

Docs reference: http://ift.tt/1DsuwVN




Passing parameters to ember components naming convetion

Which of the following is better practice?

or

Is there an advantage one way over the other or does it not really matter?




Passing template html as attribute to Ember component

Right now I have an Ember component that generates markup for a modal popup. I'd like to pass some HTML to the component (in the form of component attributes) that will be assigned as the modal's content body. Something like this would be ideal:

Route Template: app/templates/section1.hbs

<div class="content">

    <h1>Section 1</h1>

    

</div>

Modal Template: app/components/my-modal/template.hbs

<div id="my-modal">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-body">

                

            </div>

        </div>

    </div>

</div>

The content I want to display in the modal's body is static and specific to the current template.

I don't want to have this myContent html set in a controller, if possible, or in the route's model hook. Ideally, I could just set this html in the route's template. Currently this is my workaround that requires appending a javascript template to the desired element after didInsertElement.

Is there a better way to accomplish this, like setting a local handlbars template variable to some html (inside app/templates/section1.hbs)?

Current Solution/Workaround:

Route Template: app/templates/section1.hbs

<script type="text/template" id="my-content">

    <h1>Hello Ember!</h1>
    <p> Welcome to components </p>

</script>

<div class="content">

    <h1>Section 1</h1>

    

</div>

Component JS: app/components/my-modal/component.js

import Ember from 'ember';

export default Ember.Component.extend({

    tagName:    'div',
    classNames: 'modals',

    didInsertElement: function() {

        this.$('#my-modal').append($('#my-content').html());

    };
});

Modal Template: app/components/my-modal/template.hbs

<div id="my-modal">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-body">

                //jQuery will append template content here

            </div>

        </div>

    </div>

</div>




How to open a route in a modal dialog in ember.js?

We have a requirement of opening a modal dialog containing a route or a component. We are looking for some modal components, and saw ember-bootstrap's modal is useful.

So,

  1. How can we open a route as a modal dialog ?
  2. Can we create a service, to pop up a modal dialog? Such as: ModalDialogService.popup(title, bodyComponent, commitHandler, cancelHandler); And how can we do this without violating the Data Down Action Up principle?
  3. Is there any guide, document, tutorial or npm package for implementing modals in ember.js?



Ember Updating route to pull from store (Mirage)

I am trying to follow the ember tutorial to set up mock data in development. This is where I am reading from: http://ift.tt/1MLtopy

The tutorial is supposed to be showing me how to convert hard-coded data to mirage/config.js

I've gotten all the way to the bottom of the page, but it seems like it's missing a step. The .hbs, typed out on the previous page, has not been changed:


  <h2></h2>
  <p>Owner: </p>
  <p>Type: </p>
  <p>Location: </p>
  <p>Number of bedrooms: </p>


Which would be great except there's nothing in .

I see in the console that I have received the json:

Successful request: GET /rentals
server.js:255 Object {data: Array[3]}

And all my routes and stuff are pointing correctly, as I can see in Ember inspector:

  • Route Name: rentals
  • Route: rentals
  • Controller: rentals
  • Template: rentals
  • URL: /rentals

But how do I access that data? What am I missing?




How to transit from a component to a route in ember

I have a popup component in which i have a button and on click of that if im in my target route (mainRoute) i just want to pass the query parameters to my current route, but if i'm in another route i just want to transit with new query parameters. I know neither transitionTo or transitionToroute work. Is there any way to do that?




EmberJs - Bubble up action from modal

I have a couple of nested routes. In one of them it's possible to open a modal (which is attached to another outlet called modal).

When the user enters the text and clicks Ok, it's sent an action ('valueUpdated') to the MyrouteChildController. However, I also need to bubble this event up to MyrouteController, but it's not working. I tried returning true in the action handler and also manually calling @send.

If I call the MyrouteChildController's action from its own template it works.

http://ift.tt/26s5YMj

Any help would be appreciated.




How to change the text displayed of Ember/Handlebars link-to?

I am new to Ember (and Handlebars.js). The following code displays the word "Preferences" and it is a link:

<li></li>

I realize that it is that is displaying the text I want to change because I can remove it and insert plain text and it will display what I want. However, I want to understand where the text is coming from: a model, route, controller? This code is found in a user.hbs template.




undefined is not an object (evaluating 'env.hooks')

I am upgrading from Ember 1.11.4 to 1.13.10. Some of my acceptance tests are throwing this error

undefined is not an object (evaluating 'env.hooks')

When calling application.destroy() in my afterEach hook in the test.




EmberJS all websocket communication

So I'm fairly confused on how to go about this. I'm developing an somewhat complex ember app thats similar to a forum and I'm simply am not using ajax at all, all communications are going through websockets powered by socket.io.

The easy part was getting socket.io up and running, the hard part is how to go about with communication. I've seen loads of stuff all over the web with all different kinds of answers but while they answer some questions theres a lot they don't answer.

In short, I can somewhat grasp loading general content data, I say somewhat because I'm not using a relational database but instead a graph database so find methods like findAll are generally useless since on the backend I'm going about things completely different but I can keep it somewhat manageable and just load in the response in a way that makes ember and ember data happy.

But what I'm loading is more than content data like posts and stuff. I'm also loading in error messages for different actions like invalid login or 404 messages for posts, jwt tokens for successful logins, possibly vector images or special content. This is where things get complicated because it seems ember is designed to mainly store and load content data, stuff with an id that can be fetched individually, in a range, filtered out, etc... but I'm really torn on how to bring in the other stuff as ember seems to only load stuff into handlebars from a model.

So, from what I can gather, the best solution is to create a model for each and every page in my site to hold page data like error messages, special content, or other non-content stuff. Request the data, and then load the data to that page model. It seems like a really whacky way of doing things and I'm almost tempted to say that ember just isnt the solution for me but I figured I'd ask the community and see what they say.




Duplicate uploads for pictures taken from the Camera ember-uploader

I am using ember-uploader to implement a simple file uploading service. By following the manual I implemented this function:

changedFiles: Ember.observer('files', function() {
  var files;
  files = this.get('files');
  if (!Ember.isEmpty(files)) {
    this.sendAction('filesChanged', files);
    return this.rerender();
  }
})

When I upload images from Documents or I take a video from the Camcorder I see chrome's Data memory in android settings not to increase until I afterwards save them via the Local Storage API.

However, when I take a picture from the Camera and I place breakpoint even before sending the action the Data memory already has increased the size of the picture uploaded. Subsequently the image is saved via Local Storage API and then removed, but that spurious added memory is never released from Data memory and it eventually leads to full storage.

My chrome version is 50.0.2661.86 (Official Build) (64-bit)




Structure emberjs application as different modular apps

We are new to emberjs and are looking to replace our existing project client side with a SinglePage Framework like EmberJs. We have an issue with the way Ember is structured at first glance.

Our structure at the moment is like so:

  • /web
    • core
    • apps
      • app1
      • app2

We would like to keep that sort of structure but looking at ember you can only have 1 app and then each up would have to spread its files in the different directories (i.e routes, controllers, models, etc) Is there a way to have emberjs apps running next to each other and talking to each other?




Ember action preventing checkbox value from setting

In my ember application I would like to render a set of checkboxes dynamically via a loop and disable any unselected checkboxes if 2 of the checkboxes have been checked.

I am having problems with setting a value to 'true' when a checkbox is selected that has a change action. For the following example checkbox.value does not get set when the checkbox is selected.

 

However when I remove the action it does get set:

 

Full example on JSFiddle

How can I set the value while still running the action? Or is the a better way to disable the unchecked checkbox when 2 have already been selected?




lundi 25 avril 2016

How to pass parameters/attributes to a component in EmberJs when using "as" operator

I have a structure to invoke my component in this way, in a .hbs file


  

    this is the content for the first section <br>  

  

    Some content for section two <br>
    More content for second section <br>

  


I want to be able to pass some parameters along, like this



It is resulting in a parse error while build.

How can i still pass parameters to be accessed by the component in this scenario?

Thanks in advance!!




Unexpected generated emberjs code

I'm trying to go through an ember cli tutorial. When I generate a model with:

ember generate model user

, the tutorial says I should get a user.js class like:

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

but I get:

import Model from 'ember-data/model';

export default Model.extend({

});

I'm not sure what I may have done to cause this. Do I have different version of Ember CLI, have I perhaps missed something in my setup, or something else? I'm not sure if I can ignore it and continue or if I should resolve this issue first.

Thanks,

Bob




Recreate an Ember.js Component view element

The documentation for Ember.Component's tagName property says: "The tag name is only used when an element is first created. If you change the tagName for an element, you must destroy and recreate the view element."

How do I do that ? Here's my code :


  


I want the view element of the brick-block component to change if the value of brick.tagName changes.




Ember-i18n location fallback

I am trying to introduce ember-i18n into my current project to manage translations across different varieties of english. Specifically, aiming to handle en-US & general en words. The issue I am having is that even if I specify the i18n.locale to be en-US it still uses the translations form the en/translations.js file. This is happening even if the defaultLocale is set to en-US in the config/environment.js

I have specified two translation files:

locales/
├── en
│   └── translations.js
└── en-US
    └── translations.js

with the following contents:

app/locales/en/translations.js

export default {                                                                                                                                                                                                                                                                                                              
  app_name: 'Jobber',                                                                                                                                                                                                                                                                                                         

  cheque: 'Cheque',                                                                                                                                                                                                                                                                                                           
  province: 'Province',                                                                                                                                                                                                                                                                                                       
  postalCode: 'Postal Code',                                                                                                                                                                                                                                                                                                  

  // LINKS                                                                                                                                                                                                                                                                                                                    
  terms_of_service_link: 'http://ift.tt/23X3nLv',                                                                                                                                                                                                                                                           
  privacy_policy_link: 'http://ift.tt/1T0OgW4',                                                                                                                                                                                                                                                               
  reset_password_link: 'http://ift.tt/1RHEcTq',                                                                                                                                                                                                                                                    
};

app/locales/en-US/translations.js

export default {                                                                                                                                                                                                                                                                                                              
  cheque: 'Check',                                                                                                                                                                                                                                                                                                            
  province: 'State',                                                                                                                                                                                                                                                                                                          
  postalCode: 'Zip Code',                                                                                                                                                                                                                                                                                                     
};    

Any ideas why the I can't get the location fallback to work as intended?

references:

Ember-i18n Wiki - Location Fallback




Ember JS - Component vs. Factory

I am very new to Ember JS, and I even have to admit that it is my very first framework I use.

Well. I am facing a design problem. I want to make an audio webapplication which will at all time need to be able to play audio, and therefore I want to make an AudioPlayer singleton that will be available in the app's entire lifespan.

According to Ember's documentation on Dependency Injection I could just register a factory, which by default is registered as singleton, and I could access it by all time via:

applicationInstance.lookup('audio:player'); // For example

This seems like an idea, but I also need an interface for the audio player, with knobs like play, pause and stop; HTML that is. Is that possible? To make a "view" for the factory?

The second possibility I see is making an audio-player component, but with the component I have to give up the singleton, and I really only want just one audioplayer on the site, which will also be the owner of the AudioContext, which is only needed once per site.

So. What should I do? Should I go with the factory or with the model?


PS: I want to think that I need a controller, but I have read in the Ember JS guide that it is soon to be deprecated.




Ember: Reuse nested route in different parents

I wanted to know how to reuse a nested route in different parent route. For example:

Template routeA: -> routeX

Template routeB: -> routeX

Router.map(function() {

  this.route('routeA', function(){
    this.route('routeX', {resetNamespace:true});
  });

  this.route('routeB', function(){
    this.route('routeX', {resetNamespace:true});
  });

})

I need to use to show routeX inside the current parent. In the example always shows the routeB when I use

I have 2 aproax to solution:

1) Put 1 child route in routeA and other in routeB:

Router.map(function() {

      this.route('routeA', function(){
        this.route('routeX');
      });

      this.route('routeB', function(){
        this.route('routeX');
      });

})

and use and but in this aproax I have a duplicate code.

2)

router.map(function() {
    this.route('*wildcard', function(){
       this.route('routeX', {resetNamespace:true});
    });
})

this option works but in the url appear "undefined" http://...undefined/routeX

Any idea? Thanks




Error wile loading data using EmberJS

I try to show all data loaded from server using EmberJS. I have model "node"

import DS from 'ember-data';

export default DS.Model.extend({
  id: DS.attr(),
  nodeName: DS.attr(),
  address: DS.attr(),
  listeningPort: DS.attr(),
  approved: DS.attr()

});

Adapter is

import JSONAPIAdapter from 'ember-data/adapters/json-api';

export default JSONAPIAdapter.extend({
  namespace: 'api/v1'
});

Also I have index route

import Ember from 'ember';

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

When index rote is opened a request is sent to http://localhost:8080/api/v1/nodes which returns JSON

{
    "nodes": [
        {
            "address": "127.0.0.1",
            "approved": true,
            "id": 24,
            "listeningPort": 54879,
            "nodeName": "Узел оборудования"
        }
    ]
}

Error appears while parsing this JSON

vendor-c5c8d3d….js:11 Error while processing route: index Cannot read property 'type' of undefined TypeError: Cannot read property 'type' of undefined

How can I fix this problem?




Switch stylesheets in an Ember CLI application

I'm creating an application using Ember CLI. The user should have the option to switch the theme.

There are two Less files (theme-one.less and theme-two.less), one for every theme.

I'm looking for the Ember-way to conditionally load either the 'theme one' or 'theme two' file. Is there an Ember-way, or should I manually update the href attribute of the CSS <link> element?




Ember Data: Best practice creating new record

I was wondering what the best practices when a creating a new record in a ember data application.

Witch following strategy is considered best practices?

Strategy 1

  • Model hook returns the promise from this.store.createRecord();
  • Each template fields is mapped to the model return by the model hook.
  • Action saves the model.

Strategy 2

  • Each template field is mapped to a controller property.
  • Action calls this.store.createdRecord() and save the model.



Is current-when got deprecated in Ember 2.x.x?

We are trying to keep the current route active when a child route is accessed from an another child route of same parent.

this.route('example', {path: '/example'}, function () {
    this.route('user', {path: '/:user1'});
    this.route('article', {path: '/:user1/:article'});
  });

When I navigate from 'user' route to 'article' route, the 'example' route is not keeping the 'user' route selected button active.




Sorting an async relationship

I have an ember app which shows 'competitions', each 'competition' object has many 'competitor' objects:

app/models/competition.js

import DS from "ember-data";

export default DS.Model.extend({
  name: DS.attr('string'),
  competitors: DS.hasMany('competitor', {async: true}),
});

I have a league-table component which is passed a 'competition' object as its main data.

app/components/league-table.js

import Ember from "ember";

export default Ember.Component.extend({
  classNames: ['league-table'],
  competition: null,
  visibleCompetitors: Ember.computed.filterBy('competition.competitors', 'hidden', false),
  sortProperties: ['score:desc'],
  sortedCompetitors: Ember.computed.sort('visibleCompetitors', 'sortProperties'),
});

I would like to present the competitors in the correct order as a simple list. The sort order is determined by a complicated 'score' property of the competitor which is calculated based on a significant amount of data which is embedded in the competitor object when it is loaded.

app/templates/components/league-table.hbs

<header>
  <h2></h2>
</header>
<ul>
  
      
  
    <li class="centered">competition has no competitors</li>
  
</ul>

The server takes a long time to load the 'competition.competitors' list so I was hoping to have the league table populate gradually and have competitors slot into the correct positions as they are loaded.

My problem is that competitor objects are not correctly ordered. I can see this is something to do with the promise but I can't realistically wait for all the competitors to load before rendering something.

Is there a way to restructure this so the competitors are slotted into the correct positions as they are loaded or do I need to think about the problem in a different way?




Ember.JS do an operation every time the JSON is loaded

I am new to Ember and in my APP I need to add some operations depending on the JSON I get from the server.

This is currently my logic:

In the component.js

var foo;

didInsertElement() {
 var data  = this.get('content');
 //then I do some transformations with data to obtain what I want and assign it to foo

  foo = someTransformationFromData;
}

So now the question is, I need to move this logic from didInsertElement to somewhere else so it gets executed every time I get my JSON no just the first time when the component is rendered. I have tried to use a serializer or a transform but I don't know if I can use any of them. Can you please give me any pointers about how to do this task?.

Thank you.




Ember 2.4.3 registration form using account and user model

I am right now facing the signup form in Ember2.4.3. The problem is I have two model account and user, where account belongs to user and user belongs to account.

in my signup.js route,

model() {
  model: this.store.createRecord('account');
}

where as in form I have added like







model for account is

user: DS.belongsTo('user'),
kind: DS.attr('string')

where user has firstname, lastname, email and username.

When I use account as a model for signup form, the user: { data: null } in the jsonapi response.

Can anyone help me here, that would be great.




dimanche 24 avril 2016

Ember-data 'get' relationship promise returns null (identifier, not subdocument)

I am working with express/MongoDB and having trouble getting Ember-data to work with the relationships between these three collections: Org, User, and Location.

The Organization schema exists on it's own in mongoDB:

const organizationSchema = new Schema({
    creationDate: {
        type: Date, 
        default: Date.now
    }
});

The User and Location schemas both have identifiers pointing to Organization to define the relationship.

const userSchema = new Schema({
    organization: {
        type: Schema.ObjectId,
        ref: 'Organization',
        index: true,
        required: true
    },

    ...

In my Ember 'location' route, I am trying to get the information for the async relationship between user and organization. I want to get the organization ID with this model hook:

return this.store.findRecord("user", this.get("session.currentUser.id"))
  .then(user => user.get('organization')).then(data => console.log("Show me the org:", data));

If I can find the ID associated with the current user, I figure, I can find/create a location for that ID using this.store.findRecord()

Problem is, the console.log(data) is returning null -- and what's more, I can't view any of the relationship data for my models in the Ember inspector. I just see content: null

Is it that I am falsely representing the data in my Mongo schemas or Ember-data models? The Ember-data models:

Organization.js:

export default DS.Model.extend({

  location: DS.hasMany('location', {async: true}),
  user: DS.belongsTo('user', {async: true})

});

User.js:

export default DS.Model.extend({
  organization: DS.belongsTo('organization', {async: true}),
    email: DS.attr('string'),
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    registrationDate: DS.attr('date'),

    fullName: Ember.computed('firstName', 'lastName', function() {
        return `${this.get('firstName')} ${this.get('lastName')}`;
    })
});

location.js:

export default DS.Model.extend(Validations, {
  organization: DS.belongsTo('organization', {async: true})
});

Currently, my requests to the GET user route on my backend return the following relationship key in their JSON payload:

{"organization":{"type":"organizations","id":"571974742ce868d575b79d6a"}}

What am I doing wrong to not be able to access this information in Ember data? Sorry for the potential over-information / general noobery. Been stuck on this for quite a while.

Thanks so much for any help! <3 <3




samedi 23 avril 2016

EmberJS RESTSerializer with embedded hasMay relationship

I have simple api that returns channels, and each channel contains a number of stories. The API returns the following structure for a channel:

{
    "id": 1,
    "name": "The Awesome Channel",
    "stories": [
        {
            "icon": null,
            "id": 3,
            "pub_date": "2015-08-08T17:32:00.000Z",
            "title": "First Cool Story"
        },
        {
            "icon": null,
            "id": 4,
            "pub_date": "2015-10-20T12:24:00.000Z",
            "title": "Another Cool Story"
        }
    ]
}

I have the two following models defined, channel.js:

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    bgurl: DS.attr('string'),
    stories: DS.hasMany('story')
});

and story.js:

import DS from 'ember-data';

export default DS.Model.extend({
    channelId: DS.attr('number'),
    title: DS.attr('string'),
    pubDate: DS.attr('string'),
    icon: DS.attr('string'),
});

I also have this RESTSerializer to deserialize a channel:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    normalizeArrayResponse(store, primaryModelClass, hash, id, requestType) {
        var newHash = {
            channels: hash
        };
        return this._super(store, primaryModelClass, newHash, id, requestType);
    },

     normalizeSingleResponse(store, primaryModelClass, hash, id, requestType) {
        // Convert embedded data into a lost of story ids
        var stories = hash.stories.map(function(story) {
            return story.id;
        });
        delete hash.stories;
        hash.stories = stories;
        var newHash = {
            channel: hash,
        };
        return this._super(store, primaryModelClass, newHash, id, requestType);
    }
});

The code above works but it will make a new request to the server for each story in the channel, but since the data is already included in the response there is no need for those extra requests. If I leave the story data as-in then normalizing the data will fail.

Is there a way to indicated that the data for related models is embedded in the response?




Broccoli Plugin permission error, nodejs

I am getting a build error when trying to run a node.js app on Ubuntu (run as Guest OS on Windows 10). How do I solve the permission error below?

Build error

The Broccoli Plugin: [BroccoliMergeTrees] failed with:

Error: EACCES: permission denied, mkdir '/<PROJECT_FOLDER>/tmp'
    at Error (native)
    at Object.fs.mkdirSync (fs.js:842:18)
    at findBaseDir (/<PROJECT_FOLDER>/node_modules/quick-temp/index.js:62:8)
    at makeTmpDir (/<PROJECT_FOLDER>/node_modules/quick-temp/index.js:45:41)
    at Object.makeOrReuse (/<PROJECT_FOLDER>/node_modules/quick-temp/index.js:21:22)
    at new ReadCompat (/<PROJECT_FOLDER>/node_modules/broccoli-plugin/read_compat.js:17:13)
    at BroccoliMergeTrees.Plugin._initializeReadCompat (/<PROJECT_FOLDER>/node_modules/broccoli-plugin/index.js:130:22)
    at BroccoliMergeTrees.Plugin.read (/<PROJECT_FOLDER>/node_modules/broccoli-plugin/index.js:110:12)
    at /<PROJECT_FOLDER>/node_modules/ember-cli-broccoli/lib/builder.js:107:23
    at lib$rsvp$$internal$$tryCatch (/<PROJECT_FOLDER>/node_modules/rsvp/dist/rsvp.js:1036:16)

The broccoli plugin was instantiated at: 
    at BroccoliMergeTrees.Plugin (/<PROJECT_FOLDER>/node_modules/broccoli-plugin/index.js:7:31)
    at new BroccoliMergeTrees (/<PROJECT_FOLDER>/node_modules/broccoli-merge-trees/index.js:29:10)
    at BroccoliMergeTrees (/<PROJECT_FOLDER>/node_modules/broccoli-merge-trees/index.js:23:53)
    at Class.module.exports.postprocessTree (/<PROJECT_FOLDER>/node_modules/broccoli-serviceworker/lib/ember-addon.js:62:14)
    at /<PROJECT_FOLDER>/node_modules/ember-cli/lib/broccoli/ember-app.js:506:27
    at Array.forEach (native)
    at EmberApp.addonPostprocessTree (/<PROJECT_FOLDER>/node_modules/ember-cli/lib/broccoli/ember-app.js:504:23)
    at EmberApp.toTree (/<PROJECT_FOLDER>/node_modules/ember-cli/lib/broccoli/ember-app.js:1591:15)
    at module.exports (/<PROJECT_FOLDER>/ember-cli-build.js:36:16)
    at Class.module.exports.Task.extend.setupBroccoliBuilder (/<PROJECT_FOLDER>/node_modules/ember-cli/lib/models/builder.js:55:19)




Ember Data usage without a Backend API and converting Models to JSON (Ember 2.5.0)

I am using Ember v2.5.0 without an external datastore.

After creating a record at the route using the createRecord method it cannot be queried for in other parts of the app (controller or components).

My understanding is that I need to use store.push to save the record locally so that it may be accessed by the controller. However the store.push method requires the arguments to be in json format.

I could just do away with the models however I was wondering if there a quick way to convert the models into json format using Ember version 2.5.0? I would also like to know if my assumptions on using store.push to persist the data locally is a recommended way to go when using Ember Data without an external backend.

There are other references on "Ember models to json" on stack overflow however they are outdated and I particularly would like to know if my approach/assumptions are correct and if not, what the alternatives are. Im very new to Ember.

Problem

//Route
import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        let shape, square;

        square = this.store.createRecord('square');

        shape = this.store.createRecord('shape', {
            shared: 'shared-value',
            square: square
        });

        return shape;
    }
});

//Controller
import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        someActionName() {
            console.log(this.store.peekRecord('shape', 1)); //undefined!
        }
    }
});

//Shape Model
import DS from 'ember-data';

export default DS.Model.extend({
    shared: DS.attr('string', { defaultValue: '' }),
    square: DS.belongsTo('square')
});

//Square Model
import DS from 'ember-data';

export default DS.Model.extend({
    sides: DS.attr('string', { defaultValue: '4' }),
    whereIbelong: DS.belongsTo('shape')
});



Using the es6 spread operator in htmlbars

Is is possible to use the equivalent of the spread operator in htmlbars?

let items = ['hello', 'world'];
someFunction(...items); // equivalent to someFunction('hello', 'world');

I need this in htmlbars






Passing unknown number of arguments to a link-to inside a component

In a component I am using the link-to helper. The trouble is that I don't know how many items the link will need. For example, a route such as admin.school.user might need two items passed, the school and the user.

Go

In the component, I want the programmer to be able to pass as many url models as necessary



Inside my component, among other things I have the following



Obviously I can't hard code attrs.item1 attrs.item2 because I don't know how many models they will be passing.

How can I do this?




vendredi 22 avril 2016

ember-cli-mirage redirects socket.io client which is injected in mirage

the issue that occurs here, is that, when i connect between sample socekt.io client with this socket.io server by node.js ( just running two terminals and opening socket connection between client and server) I have no problems.

But, when I am trying to inject this socket.io-client into my Ember.js application, precisely to ember-cli-mirage it redirects my client from given address :
( 'http: //localhost:8080')
to something like
http: //localhost:8080/http://ift.tt/248QXgd;.....
also Mirage displays me an error that I cannot handle, even by setting up precise namespace, routing the wsClient.connect() method or calling this.passthrough() , before calling wsClient.connect() .


I also paste the the screenshot of error from inspect console in browser:

error image


Do you have any idea how to resolve this problem? Thank you in advance and I also hope that the topic is not duplicated.

// server.js
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
app.listen(8080);

function handler(req, res) {
  res.writeHead(200);
  res.end('default.index');
}

var rooms = {
  'room1': [

  ],
  'room2': [

  ]
};

io.on('connection', function(socket) {
  console.log('client connected');


  socket.on('join', function(roomName) {
    rooms[roomName].push(socket.id);
    socket.join(roomName);
  });

  socket.on('leave', function(roomName) {
    var toRemove = rooms[roomName].indexOf(socket.id);
    rooms[roomName].splice(toRemove, 1);
    socket.leave('roomName');
  });


  socket.on('eNotification', function(data) {
    console.log(data);
    io.to(socket.id).emit('eNotificationCall', data);
    io.to('room2').emit('eventNotification', data);
  });


  socket.on('gNotification', function(data) {
    console.log(data);
    io.to(socket.id).emit('gNotificationCall', data);
    io.to('room1').emit('diagram1Notification', data);
  });


  socket.on('close', function() {
    console.log('client disconnected');
  });

});


//client.js
var wsClient = {
  socket: null,
  connect: function() {
    this.socket = io.connect('http://localhost:8080');
    this.socket.on('connect', function() {

      console.log('mirage client connected!');
    });

  },
  send: function(eventData, graphData) {
    this.socket.emit('eNotification', eventData);
    this.socket.emit('gNotification', graphData);
  }

};
export default wsClient;



//config.js
import wsClient from './websockets/client';

export default function() {
wsClient.connect();
console.log(wsClient.socket);
var graphData = {X: "2", Y: "3"};
var eventData = {myDAta: 'myDAta', message: 'message'};
setInterval(function() {
    wsClient.send(graphData, eventData);
}, 5000);
}




How to detect if shift key is down on action

In my Ember app, I would like to detect if the shift key is being held down when a photo is clicked

......

As far as I can tell, it is not possible to get an event from an action. Any ideas on how to get around this problem?




ember communication (many clients) with server simultaneously

This question may seem basic in ember terms, but I'm having difficulty implementing a solid solution.

Basically I have a toggle (ember-cli-toggle), which works with a model to determine a boolean state in a firebase database. When one user turns it on, I want every client's toggle switch to turn itself on, and visa-versa for off.

I've implemented a working solution below, however, an astute observer can see that this could create an infinite loop of toggling a switch from state to state. If several clients click a toggle switch at the same time, the / actively pushes updates to the server, which affects the model and the whole loop starts over again.

Does anyone know a better Ember way to go about this? I was considering looking more into Observers and adding properties to the controller for isPushed, etc, but I thought the community might be able to point me in the right direction instead.

Controller: device.js

import Ember from 'ember';

export default Ember.Controller.extend({
  model: null,

  actions: {
    toggleSwitch(isToggled, toggleName) {
      switch(toggleName) {
        case 'switchOne': {
          if (isToggled) {
            console.log("Switch one is on!");
            Ember.$.getJSON("http://IP/api/force/io/1/1", function(response) {
              console.log(response);
            });
          }
          else {
            console.log("Switch one is off!");
            Ember.$.getJSON("http://IP/api/force/io/1/0", function(response) {
              console.log(response);
            });          
          }
          break;
        }
        etc (other cases) . . . 
    }
  }
});

Handlebars: device.hbs



<div>
  Switch One
  <br />
  
    
  
    
     
</div>

Model: device.js

import DS from 'ember-data';

export default DS.Model.extend({
  force_mode: DS.attr('number'),
  io_one: DS.attr('number'),
  io_two: DS.attr('number'),
  io_three: DS.attr('number')
});




Ember - import dynamic mixin into the addon

Refer this Ember-twiddle demo :-

http://ift.tt/1VGQ3Xo




Best practice to load external config file in Ember

I'm still quite new for Ember.js and I'm making a search box who need to load a list of types from a product-type-list.json to show some filter selects, the json is like:

data: [
    "id": "1",
    "type": "cars",
    "attributes": {
       "name": "Classical"
    },
    "id": "2",
    "type": "motos",
    "attributes": {
       "name": "Sportive"
    },
    "id": "3",
    "type": "boats",
    "attributes": {
       "name": "Sailing"
    },
    "id": "4",
    "type": "cars",
    "attributes": {
       "name": "4x4"
    },
]

and generate some select like:

<select>
   <option value="1">Classical</option>
   <option value="4">4x4</option>
</select>

<select>
   <option value="3">Sailing boat</option>
</select>

<select>
   <option value="2">Sportive moto</option>
</select>

once user select a filter, it will make a request with queryParams like: /searches?query=blue&filters[car]=4&filters[boat]=3, and get results from server, this list change rarely, so I only need to load it in once, but I'm not sure what is the best practice for this and how to implement it, should I make a service or a mixin? should I create model for it?

and I also have a question of singular/plural, because types from the json are always plural but request wait for a singular type, how can I deal this?

thanks




Ember: Call a component action from a controller

I have a component working pretty well and now I need to call it inside a controller.

Scenario: I have an ember application, and I have an update button controller, I did a component that just display a toast(Materializecss) with some message I pass as parameter to the component and both the button and the toast are working well separately. I need to call inside the button controller this component to display to the user if the update was successfully or not using this component I did. Any sugestion of how can I call this component inside the controller? Thanks




Uncaught Error: Assertion Failed: Ember Views require jQuery between 1.7 and 2.1

I am new to ember and using the following,

Ember: v1.13.3
jquery: v1.12.3

But I am getting the following error
Uncaught Error: Assertion Failed: Ember Views require jQuery between 1.7 and 2.1

I have referred http://ift.tt/1SyiAKA

But in my bower.json file I have the following

{
  "name": "jquery",
  "main": "dist/jquery.js",
  "license": "MIT",
  "ignore": [
    "package.json"
  ],
  "keywords": [
    "jquery",
    "javascript",
    "browser",
    "library"
  ]
}

How can I overcome the error with the ember.js version(v1.13.3)?




Prevent Ember.js application from polluting global namespace

I am building an embeddable web application using Ember.js. Application JS will be hosted on my server, but it will be used by some other third-party websites. Basically, this is an embeddable widget, something like Facebook's comments widget.

The problem is that I don't want my JS to pollute third party's global namespace. All I can afford is only ONE global variable defined by me, for example, MyGadget. So I want this variable to be like a namespace for Ember, all its dependencies, and the actual Ember application. Like this:

window.MyGadget.Ember
window.MyGadget.jQuery
window.MyGadget.Pretender
window.MyGadger.App
... and so on

Can this be done in a relatively easy way?




jeudi 21 avril 2016

Refresh application route after login

I would like to know what the correct way is to refresh my application route after a login, so that my model is loading correctly. At the moment i only get the desired results after hard refreshing the browser.

This is my application.js (app/routes/application.js)

import Ember from 'ember';

export default Ember.Route.extend({

  beforeModel: function() {
     return this.get("session").fetch().catch(function() {});
   },

  model() {
    console.log("Session is:" + this.get("session.uid"));
    if(this.get("session.uid")) {
      return this.store.find('user', this.get('session.uid')).then(function(user){
        return user;
      });
    }
  },

  actions: {
    accessDenied() {
      this.transitionTo('login');
    },
    logout: function() {
      this.get('session').close().then(function() {
        this.transitionTo('index');
      }.bind(this));
    }
  },
});

And my login.js (app/routes/login.js)

import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    if(this.get('session.isAuthenticated')){
      this.transitionTo('dashboard');
    }
  },
  actions: {
    login: function() {
      var controller = this.get('controller');
      var email = controller.get('userEmail');
      var password = controller.get('userPassword');
      this.get('session').open('firebase', {
        provider: 'password',
        email: email,
        password: password
      }).then(function() {

        this.transitionTo('index');
      }.bind(this));
    }
  }
});

The problem takes place in my application.hbs template. In here i'm calling e.t.c.

This is my application.hbs (app/templates/application.js)


  <div class="sidebar-menu">
    <div class="brand">
      <strong>Project</strong>Todo
    </div>
    
  </div>
  <div class="main-content">
    <div class="topbar">
  <div class="current-user">
    <div class="media-object" data-toggle="example-dropdown">
      <div class="media-object-section">
          <div class="current-user-image" style='background-image:url()'>
          &nbsp;
        </div>
      </div>
      <div class="media-object-section middle">
          <svg role="img"><use xlink:href="/assets/icons.svg#icon-angle-down"></use></svg>
      </div>
    </div>
  </div>
  
    <ul class="menu vertical">
      <li>
        My Account
      </li>
      <li>
        View settings
      </li>
    </ul>
     <button >Logout</button>
  
</div>
    
      
        
      
    
      
  </div>


 




CORS Access-Control-Allow-Headers issue with addresspicker GoogleMaps API

I keep getting this error,

XMLHttpRequest cannot load http://ift.tt/1SzC0Sp. Request header field X-Pusher-Socket is not allowed by Access-Control-Allow-Headers in preflight response.

And If I do enable the CORS adon in Chrome, it just works fine. Happening on Production, Staging and development.

Also, the page having this broken has ember in it, any other page just works fine.




Link hasMany/belongsTo associated objects loaded through separate requests?

I'm using Ember/Ember Data 2.4

I have a simple hasMany belongsTo relationship defined as follows:

// models/employee.js
export default DS.Model.extend({
  shifts: DS.hasMany('shift', { async: false })
})

// models/shift.js
export default DS.Model.extend({
  employee: DS.belongsTo('employee', { async: false })
})

I load all employees through an initial request on the homepage of the application. Then, when the use navigates to the calendar page, I fetch shifts for the given week in another requests. The shift JSON includes an employee_id.

After shifts have been loaded, shift.get('employee') returns null.

How can I associate the newly loaded shift records with employee records that already exist in the store?




Ember.js data records shows content: null in relationships inspector

I have the following code in my 'user.js' model in ember-data:

export default DS.Model.extend({
  organization: DS.belongsTo('organization'),
  //other stuff
});

The CRUD for the website is working as expected, and in MongoDB I can see the following for the organization field of User:

"organization" : ObjectId("571974742ce868d575b79d6a"),

BUT, and I'm not sure if this is an error in my code or me not understanding how Ember-data works, I cannot access that ID from a model hook like so:

model(){
        return this.store.findRecord("user", this.get("session.currentUser.id"))
            .then(user => this.store.findRecord("location", {organization: user.organization}));
    }

And if I go to the Ember inspector to observe the belongsTo attribute of the User object, I see:

organization: <(subclass of Ember.ObjectProxy):ember956>

But clicking through I see content: null

What am I doing wrong? Could it be a server-side error?




Performing unit math with SASS and rem/em

I am transitioning our app from LESS to Sass and I can't seem to figure out how to convert this one mixin we have that is computing our font grid.

Here's an excerpt that works in LESS:

@font-size-base: 1em;
@baseline-height: 1.375rem;

@lineHeightMultiplier: unit(ceil(@font-size-base / @baseline-height));
line-height: unit(((@lineHeightMultiplier * @baseline-height) / @font-size-base), em);

In Sass:

$font-size-base: 1em;
$baseline-height: 1.375rem;

$lineHeightMultiplier: unit(ceil($font-size-base / $baseline-height));
line-height: unit((($lineHeightMultiplier * $baseline-height) / $font-size-base));

The Sass code throws the following error on line 5, where we set line-height:

Error: Undefined operation: ""em/rem" times 1.375rem".

I am having a hard time grasping how the Sass unit method and the LESS unit method relate. Do I need to convert my rem before doing the math?

Here's the documentation for the Sass method:

http://ift.tt/1MLMQ5u

And for the LESS:

http://ift.tt/1Qr54UB




Ember Data error while processing route this.store.findALL is not a function

I'm currently going through the ember.js guides, and I'm getting hung up on the Ember Data section. Ember Data Guide

The tutorial shows how to create an Ember Data model and use it in conjunction with mirage to render some basic rentals info on the index page.

My code appears to be the same as the tutorial (see note at bottom), but my index page doesn't display anything, and I get these errors in the chrome console:enter image description here


Any help anyone could offer would be very much appreciated.


This is my app/models/rentals.js

import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({
    title: attr(),
    owner: attr(),
    city: attr(),
    type: attr(),
    image: attr(),
    bedrooms: attr()
});

app/mirage/config.js

export default function() {
  this.get('/rentals', function() {
    return {
      data: [{
        type: 'rentals',
        id: 1,
        attributes: {
          title: 'Grand Old Mansion',
          owner: 'Veruca Salt',
          city: 'San Francisco',
          type: 'Estate',
          bedrooms: 15,
          image: 'http://ift.tt/1Q04rYy'
        }
      }, {
        type: 'rentals',
        id: 2,
        attributes: {
          title: 'Urban Living',
          owner: 'Mike Teavee',
          city: 'Seattle',
          type: 'Condo',
          bedrooms: 1,
          image: 'http://ift.tt/20f2bMx'
        }
      }, {
        type: 'rentals',
        id: 3,
        attributes: {
          title: 'Downtown Charm',
          owner: 'Violet Beauregarde',
          city: 'Portland',
          type: 'Apartment',
          bedrooms: 3,
          image: 'http://ift.tt/1Q04seM'
        }
      }]
    };
  });
}

app/routes/index.js

    import Ember from 'ember';

    export default Ember.Route.extend({
      model() {
        return this.store.findALL('rental');
      }
    });

app/templates/index.hbs

<h3>Welcome to Super Rentals</h3>

<p>
  We are dedicated to helping you!
</p>


  <h2></h2>
  <p>Owner: </p>
  <p>Type: </p>
  <p>Location: </p>
  <p>Number of Bedrooms: </p>


About Us!
Contact Us!




Note-- The ember.js guide is slightly out of date with the current version of ember, so I'm also using these edits to the ember-data.md file.




Ember sendAction from mixin to component without observer. also the mixin import within the component

Imagine that,

A div-component had button tag and child-component named input-component ( input tag ), input-component contains action for validation. A mixin was import only inside the child component. when i trigger a action from mixin, it calls child-component ( input-comp ) action for getting input value.




How do I "stub" a child ember component in an integration test?

Say I have a component A that contains component B. I'm writing an integration test for component A, but component B is an addon which I don't want to include with the tests (mainly because it makes xhr requests that I'd rather keep out of my integration test). Is there any documentation on how to do this? Or does anyone have a best practice?




Empty content from promise?

I'm using ember, I call to my API using

this.store.findAll('environment').then(function(values){
  //1
},function(reason){
  //rejected
});

And my code does go into the //1, problem is I get this object which seems pretty invalid.

enter image description here


Here is what my api sends back.

{
  "data": {
    "environments": [
      {
        "id": 1,
        "localePath": "C:\\XML_DEPOT",
        "name": "Acceptation 1",
        "remotePath": "D:\\XML_DEPOT",
        "databaseServerName": "blabla",
        "databaseName": "blabla",
        "port": 60903
      },
      {
        "id": 2,
        "localePath": "bob",
        "name": "Acceptation 2",
        "remotePath": "bob",
        "databaseServerName": "blabla\\blabla",
        "databaseName": "blabla",
        "port": 60904
      }
    ]
  }
}

Thank you !