vendredi 31 juillet 2015

Why is "id" null in updateRecord() of my custom Ember Data adapter?

I'm trying to learn more about creating custom adapters in Ember so I started one where I want to create and update records in sessionStorage. I have the createRecord method working, but in the updateRecord method, the id is always null. Any idea why? For the id of models, I am just using a timestamp.

export default DS.Adapter.extend({
  createRecord(store, type, snapshot) {
    var data = this.serialize(snapshot, { includeId: true });

    return new Ember.RSVP.Promise((resolve, reject) => {
      var comments = {}, id = Date.now();

      if (window.sessionStorage.getItem('comment')) {
        comments = JSON.parse(window.sessionStorage.getItem('comment'));
      }

      data.id = id;
      comments[id] = data;
      window.sessionStorage.setItem('comment', JSON.stringify(comments));
      resolve(data);
    });
  },

  updateRecord(store, type, snapshot) {
    var data = this.serialize(snapshot, { includeId: true });
    var id = snapshot.id;

    console.log('updating', id); // id is null. Why???

    return new Ember.RSVP.Promise((resolve, reject) => {
      resolve(data);
    });
  }
});

I am aware that I need to create a few other methods like findAll(), findRecord() etc, but would not having those cause this issue? I'm not sure what I am missing. Thanks in advance!




Simple boolean conditonal from AJAX (ember.js)

I'm trying to do something which must be really simple to accomplish in Ember.

I want to show a button in my template based on the boolean state of a property:

{{#if canFavoriteTag}}
  {{d-button action="favoriteTag" label="tagging.favorite" icon="star-o" class="admin-tag favorite-tag"}}
{{else}}
  {{d-button action="unFavoriteTag" label="tagging.unfavorite" icon="star-o" class="admin-tag favorite-tag tag-unfavorite"}}
{{/if}}

I have created a property called canFavoriteTag with a function which I want to return true or false to the template based on whether the user can favorite the tag or not:

export default Ember.Controller.extend(BulkTopicSelection, {

  canFavoriteTag: function() {

    const self = this;
    var ticker = this.get('tag.id');
    console.log('checking can fav stock:' + ticker);

    Discourse.ajax("/stock/get_users_favorite_stocks", {
          type: "GET",
        }).then(function(data) {

          var favable = true;

          for (var i = data.stock.length - 1; i >= 0; i--) {
            var stock = jQuery.parseJSON(data.stock[i]);
            if(ticker.toLowerCase() == stock.symbol.toLowerCase()) { console.log(ticker + ' is a favorite stock: ' + stock.symbol.toLowerCase()); favable = false; }
          }

          console.log(favable);
          return favable;

    });

  }.property('canFavoriteTag') <-- unsure about this?

...

When the page loads, the wrong button shows (always the "false" one).. I see in the console that the favable variable gets set to false when the ajax call completes, but the button never changes. How do I get it to show the right button based on the function? Do I need to use a promise? If so, how?

Appreciate any help or hints :) Thanks!




Error installing ember-cli-mocha

I'm trying to setup an EmberJS project using ember-cli. I want to be able to use Mocha/Chai instead of the default qunit, but I am getting an error at the first step on installing ember-cli-mocha.

I create the new ember project with ember new my-project and then from within the project folder I run ember install ember-cli-mocha, selecting Yes to overwrite the tests/test-helper.js.

In the output, immediately following the Installed browser packages via Bower. message I see:

Package ember-cli/ember-cli-test-loader=ember-cli/ember-cli-test-loader not found

I can't find any information on this directly. I've tried installing the various packages themselves, before the ember-cli-mocha package via npm and bower, but I always get that message when installing ember-cli-mocha through ember-cli.

Anyone else have experience with this? Thanks in advance!




Ember-cli with cordova : Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode

I'm using Ember-cli with cordova. I can launch my app fine in the browser with the ember server command. when I build project and try to install it on a device using cordova, I get this error:

Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode




Ember js - correct syntax in template when sorting and filtering through each loop

I have an each loop which outputs a table of data. Each row includes created_date, title, publisher and category. In order to use sortProperties in the relevant controller (To sort the posts by created_date), I have set it to loop over the controller:

<button {{action 'reverseOrder' 'created_date'}}>Reverse Date Order</button>
{{#each controller as |post|}} 
  ...
{{/each}}

I would also like to have buttons which filter this list by other columns (For example publisher). I've looked at this jsbin example, which passes filteredContent to the each helper in the template, and then uses that in the controller to do the filtering:

{{#each filteredContent}}
...
{{/each}}
App.IndexController = Em.ArrayController.extend({

  filteredContent: [],

  actions: {
    filterByPublisher: function(filterFn) {
      this.set('filteredContent', this.get('model').filter(filterFn));
    }
  }
});

What is the correct way to pass the filteredContent to the each helper which already specifies the controller?

I've tried various things-

{{#each controller as |post| filteredContent}}
{{#each filteredContent controller as |post|}} 

However I get errors like the following:

Uncaught Error: Assertion Failed: If you pass more than one argument to the each helper, it must be in the form {{#each foo in bar}}




How do you retrieve where a property/queryParams changes with ember?

Following this post : Ember-data resets queryParam to default value,

I got another question. Can I retrieve the place where a property/queryParam changes with some kind of wizardry? I set up an observer, it effectively changes but I want to know where it is triggered. Any suggestions?




Error when rendering 2 models for a template in Ember.js

I have a template in wish I have 2 components that represents different Models. I need to create a model that contains both datas, for each component. If I have only one model everything works fine, but when I add other one, then this error happens in the console.

Error while processing route: events record is undefined ember$data$lib$system$store$finders$$_find/</<@http://localhost:1361/test/frontend/bower_components/ember-data/ember-data.prod.js:7475:11
Backburner.prototype.run@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:222:18
ember$data$lib$system$store$$Store<._adapterRun@http://localhost:1361/test/frontend/bower_components/ember-data/ember-data.prod.js:13133:16
ember$data$lib$system$store$finders$$_find/<@http://localhost:1361/test/frontend/bower_components/ember-data/ember-data.prod.js:7470:1
tryCatch@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:53070:14
invokeCallback@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:53085:15
publish@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:53053:9
@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:31253:7
Queue.prototype.invoke@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:901:9
Queue.prototype.flush@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:965:11
DeferredActionQueues.prototype.flush@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:765:11
Backburner.prototype.end@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:158:9
Backburner.prototype.run@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:226:13
run@http://localhost:1361/test/frontend/bower_components/ember/ember.prod.js:19151:12
ember$data$lib$adapters$rest$adapter$$RestAdapter<.ajax/</hash.success@http://localhost:1361/test/frontend/bower_components/ember-data/ember-data.prod.js:1728:15
n.Callbacks/j@http://localhost:1361/test/frontend/bower_components/jquery/dist/jquery.min.js:2:26920
n.Callbacks/k.fireWith@http://localhost:1361/test/frontend/bower_components/jquery/dist/jquery.min.js:2:27738
x@http://localhost:1361/test/frontend/bower_components/jquery/dist/jquery.min.js:4:11251
.send/b/<@http://localhost:1361/test/frontend/bower_components/jquery/dist/jquery.min.js:4:14765

The route of the template that contains the components is:

App.EventsRoute = Ember.Route.extend({
    model: function()
    {
        return Ember.RSVP.hash({
            event:  this.store.find('event'),
            featured: this.store.find('event', 'featured')
        });
    }

});

Does anyone knows why this error happens and what can I do to solve it?




Ember Data - Unable to add one way belongsTo relation

I have created 2 models a video model and a subtitle model:

Video Model

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  file: DS.attr(),
  hotspots: DS.hasMany('hotspot', {
    inverse: 'toVideo'
  })
});

Hotspot Model

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  onVideo: DS.belongsTo('video'),
  toVideo: DS.belongsTo('video')
});

So basically a hotspot is present on a video and links to another video. So I'm able to link the onVideo using the following code:

this.store.find('video', this.get('ActiveCanvas')).then(function(onVideo) {
    onVideo.get('hotspots').pushObject(newHotspot);
});

But now I want to add the toVideo relation but it's not working for some reason. This is what I tried.

var newHotspot = this.store.createRecord('hotspot', {
    title: this.get('HotspotName'),
    toVideo: this.store.find('video', HotspotVideo.value)
});

I'm not getting any error in my console. Can you please tell me what's going wrong.




How to create and save a new model in Ember Data 1.13.7 and update the UI

I am using Ember 1.13.5 and Ember Data 1.13.7 and the default JSONAPIAdapter/Serializer and I have a problem saving a new model.

My route looks like this:

import Ember from 'ember';

export default Ember.Route.extend({

    model: function(params) {

        return Ember.RSVP.hash({
            auditLog: this.store.query('log', {filter: {object: 'IsoApplication', object_id: params.id}}),

        });
    },
});

This successfully returns a collection of "log" models in the "auditLog" key of the controller, e.g. this.get('model.auditLog').

In the controller I create a new "log" model and save it successfully like this:

self = this;

var log = this.store.createRecord('log', {
    logLevelId: 2
    logTypeId: 2
    object: 'IsoApplication',
    objectId: 23
    message: 'A message',
    logData: '',
});

log.save().then(function(log) {
    self.get('model.auditLog').pushObject(log);
});

I use this line:

self.get('model.auditLog').pushObject(log);

To update the model so that my new log entry is displayed in the UI but I get the following error:

TypeError: internalModel.getRecord is not a function

and the "log" parameter in the "save" callback is of type "InternalModel". I was led to believe that InternalModels were only used by the Ember Data core code so presumably the "save" callback should return a DS.Model instance instead. Is something wrong here?

Also, am I doing the correct thing by using "pushObject" to update the "model.auditLog" collection of "log" models in order that the UI updates with the newly added model or should it be an automatic process?

Any help that anyone could offer would be appreciated.

Thanks.




Ember.js checkbox and Promise

I have an issue when trying to use a checkbox to work out if a one-to-many relationship exists.

I have a userPrivilege table with userId, modelId, privilegeId and scopeId.

I am trying to display checkboxes which show whether the user has privileges. To do this, I need to check multiple conditions, not just a simple boolean field.

I can use asynchronous functions to determine whether the user has privileges, but I just don't know how to assign this to the checkbox 'selected'. Returning the promise means the checkbox is always checked. Returning the value from within the promise always leaves it unchecked.

See below a snippet of something I was attempting...

Checkbox Component:

    export default Ember.Component.extend({
          user: null,
          model: null,
          privilege: null,
          scope: null,
          selected: function() {
            return this.get('authorization').hasAuthorization(
              this.get('user.id'), 
              this.get('model'), 
              this.get('privilege'), 
              this.get('scope')).then(function(result) {
              return result;
            });
          }.property()
        })

Service:

export default Ember.Service.extend({
  hasAuthorization: function(userId, model, privilege, scope) {
    var store = this.get('store');

    return new Ember.RSVP.Promise(function (resolve, reject) {
      store.find('user', userId).then(function (user) {
        user.get('userPrivileges').then(function (userPrivileges) {
          userPrivileges.find(function (userPrivilege, index, userPrivileges) {
            userPrivilege.get('model').then(function (_model) {
              if (_model.get('name') === model) {
                userPrivilege.get('privilege').then(function (_privilege) {
                  if (_privilege.get('name') === privilege) {
                    userPrivilege.get('scope').then(function (_scope) {
                      if (_scope.get('name') === scope) {
                        resolve(true);
                      }
                    });
                  }
                });
              }
            });
          });
        });
      });
    });
  }
});




Ember disabled button

I'm having an issue with embers bind-attr on the 'disabled' attribute on a button. Basically I can't get it to not disable my button.

isCancelled is a boolean in my model, according to this it should make 'disabled' appear and disappear inside the rendered tag.

Button looks like:

<button {{action "cancel" provisioning}} {{bind-attr disabled="isCancelled"}}>

It always renders the 'disabled' attribute.

I made a simple check to debug it. It looks like this:

isCancelled: {{isCancelled}}

It renders like: isCancelled: false

I'm using Ember 1.12.0




Ember: Cannot read property 'modelName' of undefined

We are using ember 1.13.5, ember-data 1.13.7 and sails 0.11 for the backend.

The full error is: Cannot read property 'modelName' of undefined at ember$data$lib$system$store$$Service.extend.serializerFor

I followed the code through dev-tools and came to the code shown in the image below. It shows that modelName is defined.

enter image description here

This is the actually code that is being called in my setup.js controller:

_this.store.query('business-account', {user: user.get('id')})
      .then(function(businessAccount) {
        debugger;
      }, function(err) {
        debugger;
      });

The above throws the following error:

TypeError: Cannot read property 'modelName' of undefined
at ember$data$lib$system$store$$Service.extend.serializerFor (http://ift.tt/1haAyVr)
at http://ift.tt/1haAvZC
at http://ift.tt/1OF57x1
at Map.forEach.cb (http://ift.tt/1OF55Fl)
at OrderedSet.forEach (http://ift.tt/1OF55Fn)
at Map.forEach (http://ift.tt/1haAyVu)
at Function.ember$data$lib$system$model$$default.reopenClass.eachRelationship (http://ift.tt/1OF55Fp)
at DS.default.RESTSerializer.extend._extractEmbeddedRecords (http://ift.tt/1haAyVy)
at DS.default.RESTSerializer.extend.normalize (http://ift.tt/1OF55Fr)
at apply (http://ift.tt/1haAvZL)




Ember (Handlebars) nested each on one level

For example, I've got following object:

var obj=[
{
    subitems:[
        "string_one",
        "string_two"
    ]
},
{
    subitems:[
        "string_three",
        "string_four"
    ]
}]

and I want to output it like this:

<div>string_one</div>
<div>string_two</div>
<div>string_three</div>
<div>string_four</div>

In the AngularJS I can achieve this by using ng-repeat-start and ng-repeat-end. It's ok to have extra elements, I can hide them in css. The main goal is to have divs on one level.

How can I do the same in Ember (Handlebars)? Thanks in advance!




Ember change view on controller's action

I want to change my view on click, click would trigger the action in controller and there I want to change the view.

The other work around I was trying is to set a value of variable as True at route level like this,

  setupController: (controller, model) ->
    controller.set('model', model)
    controller.set('dashboardView', true)

and then using this dashboardView on template show the Dashboard, otherwise show Google Map.

Emblem template

if dashboardView
  render 'dashboard' dashboardData
else
  render 'map' MapData

The action that triggers on click sets the 'dashboardView' to false but does not change the view.

Please let me know which way is the better one, or if there is another right way to do this.




Ember component: A property of X was modified inside the didInsertElement hook deprecation, where should the set go?

The full deprecation message is DEPRECATION: A property of <orders-app@view:test-holder::ember3010> was modified inside the didInsertElement hook. You should never change properties on components, services or models during didInsertElement because it causes significant performance degradation.

To simplify the scenario lets say we have a component with an input box and we want to set the textbox date to today plus a number of days numberOfDays. So if today is January 3rd 2015 and numberOfDays=2 then the textbox value should be 05-01-2015 (assuming we want DD-MM-YYYY formatting). So our setup could be:

date-shower.hbs

{{input type="text" value=dateInput}}

components/date-shower.js

export default Ember.Component.extend({
  didInsertElement: function() {
    var numberOfDays = this.get('numberOfDays');
    var dayToUse = new Date(); // today
    dayToUse.setDate(dayToUse.getDate() + numberOfDays);

    this.set('dateInput', moment(nextDay).format('DD-MM-YYYY'));
  }
});

We then might use this with something like

{{date-shower numberOfDays=2}}

When it makes sense for a component to calculate the default for one it's properties itself, based off a property passed to it, what hook should I use instead of didInsertElement to prevent the deprecation message?




Ember CLI Array Controller not sorting through each loop

I can't get sortAttribute to work from an ArrayController. I think it's because the ArrayController can't access the model.

The posts resource defined in app/router.js:

export default Router.map(function() {
  this.resource('posts', function() { 
    this.route('index', {path: '/'});
    this.route('new');
    this.route('full', {path: '/:id'});
});
 

My model for a single post (models/post.js)

export default DS.Model.extend({
  title: DS.attr('string'),     
  category: DS.attr('string'),          
  created_at: DS.attr('date'),  
  
)}

My template displays the list of posts using an {{#each}} helper
(templates/posts/index.hbs):

The inner contents of the each helper is contained in a component named 'blog-list'.

{{#each model as |post|}}
  {{blog-list model=post}}
{{/each}}

The list of posts displays fine.

I have added code to sort the list by the title property (controllers/posts/index.js):

export default Ember.ArrayController.extend({
  sortProperties: ['title'],
  sortAscending: true,
});

I'm not sure why, but the title column is not being sorted.




Ember: Adding input fields dynamically on click and reading the new data

I have a page where i show user couple of questions and provide input field for answers. Also i have a button add a question.

On clicking this, he can enter a question in the new input field and click save. so what i need is that, when he save, the newly entered question should also show up near the already shown questions.

So i have the questions in the model

import DS from 'ember-data';

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

Then i alias this in my controller and show the two questions from the template.

import Ember from "ember";

export default Ember.Controller.extend({

   addQuestion : false,

   questions : Ember.computed.alias('model.challengeQuestions'),

   actions : {
     postAnswer: function(){
        alert('prepare post data');
     },

     addQuestion: function(){
       this.set('addQuestion', true);
     },

     saveQuestion: function() {
       var que = this.get('newQuestion');
       this.get('questions').push(que);
       this.send('cancel');
     },

     cancel: function(){
       this.set('addQuestion', false);
     }
   }
});

And below goes my template..

{{log questions}}
{{#each question in questions}}
    <div>
        <span>{{question}} : </span>
        {{input placeholder="your answer"}}
    </div>
{{/each}}


<br><br>
{{#if addQuestion}}
    {{input placeholder="Enter your question" value=newQuestion}}
    <br>
    <button {{action "saveQuestion"}}>Save</button> <button {{action      "cancel"}}>cancel</button>
{{else}}
    <button {{action 'addQuestion'}}>Add manual Question</button>
{{/if}}

<br><br>
<button {{action 'postAnswer'}}>Submit</button>

So what i am trying to do here is that, when i add a new question and click on save button, i push the entered question string to the questions array in my controller. And i was expecting that the template would re-render since it is modified.

I can see that the new string is being successfully added but it doesnt show up on the UI. Any idea why?

Am using latest ember(1.13) and ember-cli.

Thanks




Should Ember addons also follow Ember 2.x project version numbers?

Referring to the The Ember project blog post

Starting with Ember 2.0, we will coordinate every release of Ember with releases of the main ecosystem tools maintained by the core team

Should community addons follow the same versioning conventions?

I haven't read any recommandation anywhere from core team, and I started to use the same versioning for addons I developed, though I'm wondering if it is a good practice or not.




Design models in EmberJS

I have stuck with architectural problem in EmberJS. I already have backend and I need to implement frontend part. So, I have "builder" route:

import Ember from 'ember';

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

Builder model:

import DS from 'ember-data';

export default DS.Model.extend({
    cocktailsTypes: DS.attr(), //must be array
    cocktailsOptions: DS.attr(), //must be array
    selectedIngredients: DS.attr(), //must be array
    ingredients: Ember.computed({
        get() {
            return this.store.findAll('ingredient');
        }
    })
});

"Ingredient" model:

import DS from 'ember-data';

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

And I want to add some action in "builder" route to create custom request and send data from "builder" model.

Will it work? Is it right way in EmberJS and ember data? Maybe I need to use some alternatives of ember data or change model's design?

My goal is build working app in "ember way" as best as possible.

P.S. I'm using the last version of EmberJS.




jeudi 30 juillet 2015

More Django static 404 issues - paired with ember

I've seen lots of different posts regarding the Django static file issues. Unfortunately, none of them seem to help me. My django admin css is fine, however static files are giving my a 404 error. Here is a description of what my problem:

In settings.py:

STATIC_URL = '/static/'
STATIC_ROOT = '/Users/me/develop/ember/myproj/static/'

In urls.py:

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

My project directory:

> static
  > myproj
    > app
      > templates
        > ember.hbs
    > img
      > test.jpg

Inside my ember.hbs I reference the test.jpg, but I get a 404 error. It's weird because I can actually pull up the image using:
file:///Users/me/develop/ember/proj/static/myproj/img/test.jpg

I have no idea what to do to fix this, I've tried using the STATICFILES_DIRS method mentioned here: http://ift.tt/1EF8GkR but nothing seems to be working.

Thanks in advance!




Testing Ember.js files with JUnit

Mainly asking if this is possible, since I have always thought that JS files would be tested with a JS unit test framework, just like Java files would be tested with Java unit test frameworks. From quite a bit of Google searches I've only found results for plugins and this example: http://ift.tt/1NFYQCG

  1. Is unit testing something like Ember files possible in a Java-based framework like JUnit?

  2. Is there a way to convert QUnit tests to JUnit tests?




Polymer With Ember CLI

I am trying to access a paper-button inside a polymer component which is in a handlebars template in EMBER.

This is the Polymer component

    <link href="../polymer/polymer.html" rel="import">
<link rel="import" href="../paper-button/paper-button.html">
<polymer-element name="my-new" noscript>
  <template>
    <paper-input></paper-input>
    <paper-button>BUTTON1</paper-button>
  </template>
</polymer-element>

This is my application.hbs

<my-new></my-new>

How to handle click event of the paper-button in the controllers.




ember-cli ember build generates incomplete index.html?

I am trying to build an ember app with ember-cli. I created the app with ember new HelloWorld and built it with ember build. Inside the "dist"-Folder is a index.html with this Markup:

<!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>HelloWorld</title>
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <base href="/" />
      <meta name="hello-world/config/environment" content="..." />
      <link rel="stylesheet" href="assets/vendor.css">
      <link rel="stylesheet" href="assets/hello-world.css">    
    </head>
    <body>
      <script src="assets/vendor.js"></script>
      <script src="assets/hello-world.js"></script>    
    </body>
  </html>

In older Ember-Versions we wrote our templates inside this index.html. I know ember "precompiles" the templates now, but where are they? When I open the index.html with a Browser I get an empty page. How does this work now? Do we need to run a node server for the ember-app? I just want to copy the output of ember build inside a Asp.Net project and include the files into my index.cshtml.




Ember-data resets queryParam to default value

In my model, I have a queryParam status which is set to refreshModel true in my route.

queryParams: {
    status: {
        refreshModel: true
    }
}

In my controller, this param is set to 'opened' by default :

App.ConversationsController = Ember.ArrayController.extend({
    status: 'opened'
});

Everytime I set this param to something else, for example 'all', Ember-data resets it to 'opened' and makes two calls instead of one to my model hook, and this behavior has been observed with breakpoints on my model hook (I don't know where it resets), one with param:opened and one with param:all. I even put an observer on it and it effectively does that.

Note that I already searched my code and there is litteraly nowhere where I set this param back to original value.

Any hints?




Incorrect JSON format for Ember Data

I'm using the latest version of EmberJS and Ember Data. I have the next JSON data:

[{
    "id": 6,
    "name": "First object",
    "vol": 40,
    "description": "bla bla bla",
    "category": "first"
}, {
    "id": 7,
    "name": "Second object",
    "vol": 17,
    "description": "Some description",
    "category": "second"
}]

And the next model:

import DS from 'ember-data';

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

And I don't understand how to make Ember data works. I have suspicious that ember data expects something like next:

[{ 
    model-name {
        "id": 6,
        "name": "First object",
        "vol": 40,
        "description": "bla bla bla",
        "category": "first"
    }
}, { 
    model-name {
        "id": 7,
        "name": "Second object",
        "vol": 17,
        "description": "Some description",
        "category": "second"
    }
}]

In console I have a bunch of warnings:

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

And more than hundred similar records (that is how many records server returns on request). And no data in store.

How can I fix this problem without changing JSON that I receive from server?




Dynamic segments for nested ember routes not working

I have a nested route structure:

 //router.js

  this.route('maps', { path: '/maps' }, function () {
    this.route('show', { path: '/:id' }, function () {
      this.route('display', { path: '/display' }),
      this.route('layers', function () {
        this.route('create')
      })
    });
  });

my understanding here is that I should have a route maps.show.display that should take a single dynamic segment like maps/1/display

However when I go to transition or link to this ie:

//maps route

afterModel: function (resolvedModel) {
 var newestFlight = resolvedModel.content[0];
 var newestMap = newestFlight.get('map');
 this.transitionTo('maps.show.display', newestMap);
}

or

{{#link-to 'maps.show.display' id}}show map{{/link-to}}

I get an error:

 Error while processing route: maps.index More context objects were passed than there are dynamic segments for the route: maps.show.index

It makes it even weirder that this route accepted the same dynamic segment when it was just maps/display so I don't understand why nesting it further breaks it.

Any ideas as to what I'm doing wrong would be greatly appreciated

edit: interestingly, this awesome tool

also seems to agree that I should have a dynamic segment here if you post my route in there




Ember dynamic query parameters

I have what I believe to be common but complicated problem to model. I've got a product configurator that has a series of buttons. Every time the user clicks on a button (corresponding to a change in the product configuration), the url will change, essentially creating a bookmarkable state to that configuration. The big caveat: I do not get to know what configuration options or values are until after app initialization.

I'm modeling this using EmberCLI. After much research, I don't think it's a wise idea to try to fold these directly into the path component, and I'm looking into using the new Ember query string additions. That should work for allowing bookmarkability, but I still have the problem of not knowing what those query parameters are until after initialization.

What I need is a way to allow my Ember app to query the server initially for a list of parameters it should accept. On the link above, the documentation uses the parameter 'filteredArticles' for a computed property. Within the associated function, they've hard-coded the value that the computed property should filter by. Is it a good idea to try to extend this somehow to be generalizable, with arguments? Can I even add query parameters on the fly? I was hoping for an assessment of the validity of this approach before I get stuck down the rabbit hole with it.




EmberJS generic relations

I am looking for an appropriate solution to support generic relations on my EmberJS front-end. On my backend i have a model, let's name it Shipping. this model have an adapter field which is a generic relation to one of the adapters model. i.e. i have 3 different adapters SelfPickupAdapter, CourierAdapter, ZoneAdapter.

model #1

export default DS.Model.extend({
    name: DS.attr('String'),
    address: DS.attr('String'),
    city: DS.attr('String')
});

model #2

export default DS.Model.extend({
    name: DS.attr('String'),
    email: DS.attr('String')
});

model #3

export default DS.Model.extend({
    name: DS.attr('String'),
    address: DS.attr('String'),
    zone: DS.belongTo('Zone')
});

And each of this adapter models should have a way to be linked to the top level model:

export default DS.Model.extend({
    adapter: DS.genericRelation(['SelfPickupAdapter','CourierAdapter','ZoneAdapter']),
    order: DS.belongsTo('Order'),
});




Ember.js: How to get an array of model IDs from a corresponding array of model attributes

For a Tag model that I have in Ember-Data, I have 4 records in my store:

Tags:

id   tag_name
1    Writing
2    Reading-Comprehension
3    Biology
4    Chemistry

In my code I have an array of tag_names, and I want to get a corresponding array of tag IDs. I'm having 2 problems:

  1. My server is being queried even though I have these tags in my store. When I call store.find('tag', {tag_name: tag_name}), I didn't expect to need a call to the server. Here is all the code I'm using to attempt to create an array of IDs.

    var self = this;
    var tagsArray = ["Writing", "Reading-Comprehension", "Chemistry"];
    var tagIdArr = []
    tagsArray.forEach(function(tag_name) {
        return self.store.find('tag', { tag_name: tag_name }).then(function(tag) {
            tagIdArr.pushObject(tag.get('content').get('0').get('id'));
        })
    })
    return tagIdArr;
    
    
  2. When I console.log the output of the above code gives me an empty array object with length 0. Clicking on the caret next to the empty array shows three key-value pairs with the correct data. But the array is empty. I'm sure there is a simple explanation for this behavior, but I'm not sure why this is. I've used code similar to the above in other places successfully.




Getting Error "Cannot read property 'create' of undefined" in app.js

I've updated my ember 1.8.1 to 1.9.1 and handlebar to 2.0.0. ember-template-compiler is also upgraded to 1.9.0 alpha version.




Run controller event after render in Ember without View

I'm new with Ember and what I want to do is execute some initialization with jQuery like this: Ember.$("select").selectpicker(); to customize default select (it actually inserts div that represents the hidden select). I used to have this code in my Controller:

init() {
   this._super();
   Ember.run.schedule("afterRender", this, function() {
      this.send("initializeJQuery");
   }
});
actions: {
   initializeJQuery() {
      Ember.$("select").selectpicker();
   }
}

It really initializes my select tags, but when I transition to another route and go back – it rerenders and doesn't want to call initializeJQuery method despite the run method (not runOnce). I use Ember v1.13 and Views are deprecated so I'm looking for alternative way to do this.

Hope for your help.




Overriding parent model loading in nested Ember.js route

I'm learning Ember and trying to figure how to do a signup form.

I have a /users route from before and I have created a users/new route. In my users route I load all the users from the store - and now my users/new route will load all the users - which is not really needed.

Should I create a separate users/index.js route for the index or is there another way to override the parent model loading that I should be using?

// app/router.js
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.resource('users', function() {
    this.route('new');
  });

  this.route('users', function() {
    this.route('new');
  });
});

export default Router;


// routes/users.js
import Ember from 'ember';

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


// routes/users/new.js
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(){
    return this.store.createRecord('user');
  }
});




Ember CLI- conditional output within an each loop using a component instead of itemController

In my Ember CLI app, I'm using {{#each}} helpers to output the rows of a table. 'name' 'created_date' and 'type' are all defined in the related model.

{{#each model as |job|}}
<tr>
  <td>{{job.name}}</td>
  <td>{{job.created_date}}</td>
  <td>{{job.type}}</td>
  <td>
  {{#if typeZero}}
     <p>Content that will display if the value of 'type' is 0.</p>
  {{/if}}
  </td>
</tr>
{{/each}}

In the fourth table cell of each row, I'd like to display certain content if that value of 'type' for that record is 0.

I first tried adding an itemController to the each helper:

{{#each job in model itemController="jobrowcontroller"}}
......
{{/each}}

This gave me an error: "Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed ***@controller:array:, but it should have been an ArrayController"

I found that itemController is now deprecated, and components should be used instead.

I created a component named job-table-row, and updated the page template:

  {{#each model as |job|}}
   {{#job-table-row model=job as |jobTableRow|}}
    <tr>
      <td>{{job.name}}</td>
      <td>{{job.created_date}}</td>
      <td>{{job.type}}</td>
      <td>
      {{#if typeZero}}
        <p>Content that will display if the value of 'type' is 0.</p>
      {{/if}}
      </td>
    </tr>
   {{/job-table-row}}
  {{/each}}

In the component handlebars file, I simply use {{yield}} and everything displays fine.

In the component js file, I have:

import Ember from 'ember';

export default Ember.Component.extend({
  tagName: '',
  typeZero: function() {
    var currentStatus = this.get('model.status');
    if (currentStatus === 0) {
      this.set('typeZero', true);
    } else this.set('typeZero', false);
  }.on('didInsertElement'),

});

The problem with this is that the function 'typeZero' only runs after the component has been inserted which is too late. Is it possible to achieve this with a component, or do I need to use a different method altogether?




mercredi 29 juillet 2015

ember model.reload() is not a function?

I want to reload my model in my controller,and I read the document from here

so I defined the action:reload in my controller and route both,such as:

 reload:function(){
     this.get('model').reload();
   }

when I triggered the action use this.send('reload'),it comes out the error this.get(...).reload is not a function,so did I misunderstand the document?




How to get css width afterRender in emberjs

I am trying to instantiate a canvas component with emberjs. I am using EaselJS to draw some text onto it. However, it looks like the CSS is being applied after it draws the text and the text gets stretched out when it applies width/height 100%. The console logs an incorrect value of width.

I want my canvas to fill its parent and I don't know how big it will be until run time which is why height and width are 100%.

I tried using Em.run.next like it says here: Ember.js - afterRender fires before CSS is finished but it did not change anything. Is there another event that fires after CSS has been applied? I need to do some initialization that depends on the width and height of the canvas.

.easelCanvas
{
  height:100%;
  width:100%;
  background-color: white;
}

Here is my EmberJS component:

    export default Ember.Component.extend({
      tagName: 'canvas',
      classNames: ['easelCanvas'],
      canvasModel: null,
      didInsertElement: function () {
        this._super();
        Ember.run.scheduleOnce('afterRender', this, function () {
          console.log(this.$().css('width'));
          var stage = new createjs.Stage(this.element);
          var someText = new createjs.Text("HELLO WORLD!", "40px Arial", "#ff7700");
          stage.addChild(someText);
          stage.update();
        });
      }
});




ember cli (1.13) ember table plugin

Hi i am new to ember cli and i'm using ember table plugin. in previous version of ember cli 0.2 ember table hello world example works well but in new version of ember cli(1.13) its not working, it show many deprecation warnings and one error that

Property set failed: object in path "tableComponent" could not be found or was destroyed

error details

Deprecations were detected, see the Ember Inspector deprecations tab for more details.




Will learning this webstack allow me to eventually make system agnostic apps with cordova?

I've dabbled with rails and django before, but at this point in my life I'm ready to put a lot of time towards learning a webstack that will let me build fast, scalable and maintainable web-apps. My understanding is that it's now possible to make phone apps with a palette of webstack skills using cordova. Before I begin to invest a lot of time learning a full stack, I'd like to know which will carry over and enable me to build phone apps.

Right now, I'm learning Rails, Rspec, Coffeescript, Ember, Mongodb and haml/sass. Will these tools allow me to build apps with cordova (or something similar)? If not, what would you suggest as alternatives?




Ember data Rest adapter error handling not working

I have a basic Ember app and I am trying to handle validation errors on save (model is using the REST Adapter). In my route I am doing:

task.save().then(
                function() {alert("success");},
                function() {alert("fail");}
                ).catch(
                    function() {alert("catch error");}
                    );

When the record is valid I get the "success" alert, but when record is invalid, I do not get the "fail" alert OR "catch error". In the console I get:

POST http://localhost:8080/api/tasks 422 (Unprocessable Entity)
Error: The adapter rejected the commit because it was invalid

The response from the api look like this:

{"errors":{"name":["can't be blank"],"parent_task":[]}}

I am using Ember Data 1.13.




How to bind a controller action to a link that is clicked or hovered?

I have a problem connected with binding an action to a link. When I create a simple link (only a "text" reference), I am able to send the action to the controller and it works like a charm.

On the other hand, I am not able to do this when I want to make my flower element highlighted on hover and active state -> when I have a text (like in previous case) and corresponding part of the picture that gets highlighted on hover and click (pure SASS in this case).

Here is my hbs code:

<div id="flowers-list">
 <ul class="flowers">
  <li class="flower1">
    <a href="#/" {{action "selectFlower" "rose"}}>Rose</a>
  </li>
 </ul>
</div>

Could you please give me a hint how to deal with this problem?

I have already tried adding on=click to my link, but it did not help.




Ember data not getting relationships

I'm using Ember 1.13.3 and ember-data 1.13.5.

I have 2 models with a relationship:

spot:

import DS from 'ember-data';

export default DS.Model.extend({
  user: DS.belongsTo('user'),
  description: DS.attr('string'),
  created_at: DS.attr('date'),
  image_src: DS.attr('string')
});

user:

import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr('string'),
  email: DS.attr('string'),
  avatar: DS.attr('string'),
  spots: DS.hasMany('spot')
});

now I call in all the spots and loop over them. Everything display fine of the spot model; however, when I try to retrieve the user's username spot.user.username it doesn't work. I checked the network and not even a request is being sent out to users/:user_id.

I also tried adding asyn: true:

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

but this also did not work. Is there a new way to do relationships in ember 1.13? I know that the belongsTo call is being reach because it appears as a deprecation in the ember console:

In Ember Data 2.0, relationships will be asynchronous by default. You must set `user: DS.belongsTo('user', { async: false })` if you wish for a relationship remain synchronous.




Can't make Emblem.js work with Rails

I'm trying to use Emblem.js to render Ember templates in a Rails app. Here is a part of my Gemfile:

gem 'ember-rails'
gem 'ember-source', '~> 1.9.0'
gem 'emblem-rails'
gem 'emblem-source', github: 'machty/emblem.js'

This is according to the installation instructions of emblem-rails gem: http://ift.tt/1IKVgY7

I have a very basic app. This is the layout written in slim:

doctype html
html
  head
    title My App Title
    = stylesheet_link_tag    'application', media: 'all'
    = javascript_include_tag 'application'
    = csrf_meta_tags
  body

I also have a basic Ember-Rails app where I have my application template written with emblem /app/assets/javascripts/templates/application.emblem:

h1 Hello World

But I get the following error (even after restarting my puma server):

ArgumentError at /
wrong number of arguments (1 for 2)
  (in /Users/htaidirt/Code/MyApp/app/assets/javascripts/templates/application.emblem)

with a highlight to the layout at = javascript_include_tag 'application' line: http://ift.tt/1I2dBfS

Do you have any idea how can I fix that? Thanks.




Ember action helper

I have a problem with action helper in my ember application. I have a list of items LI in one UL list. List could have various number if items. Items should response on mouse over. The first solution was to add on every item (LI) in the list one mouse enter action like:

<ul>
 {{#each data key="id" as |item|}}
   <li {{action "mouseOverLi" on="mouseEnter"}}>  {{item.description}}</li>
{{/each}}
</ul>

This solution is working but now for every LI tag I have one action, and that is not good solution . So is there any other solution for this. The best will be to add action helper in UL tag with filter on LI children tags.

In other words how one can transform this jQuery code snippet in action helper for Ember:

$("ul").on("mouseover","li",function(){
    // some code.
});




How to handle partially embedded records?

I've been having some trouble using Ember Data with my MongoDB back-end. Let's say I have a User model, which contains a Media (the user picture). Sometimes user.picture is sent embed, sometimes the back-end only sends the Media ID.

How do I handle that with Ember Data? I haven't seen anything like this in the EmbeddedRecordsMixin, even if I think it's kinda easy to do (if it's an object, don't fetch it, if it's a string, fetch the corresponding object).




Ready to use enterpise web application templates

As you know, there are dozens of java web frameworks but AFAIK there is not any ready to use enterprise web application templates to start up with. For instance, most of the web applications have functionality such as login/logout, remember me, forget password, a dashboard, a profile view that you can edit your user settings and an administration view for the authorization settings. I have searched some of them but these, most common functionalities are not ready with such templates. Maybe you can propose some of them. I think, this kind of stuff in java world is missing. Proposals might be also for javascript frameworks such as AngularJS, EmberJS etc. Thanks a lot. Ercan




Ember Data: Uncaught TypeError: Cannot read property 'push' of undefined

I'm new to Ember CLI and I've been trying to push data to hasMany relationship after it has been created, but I'm getting this weird error Uncaught TypeError: Cannot read property 'push' of undefined Everything seems to be fine this.store.createRecord() is working but .findRecord .push .peekRecord is not working.

My controller:

var VideoToAdd = this.store.find('video', this.get('ActiveCanvas'));
console.log(this.get('ActiveCanvas'));
VideoToAdd.get('hotspots').push(newHotspot);

Video Model

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  file: DS.attr(),
  hotspots: DS.hasMany('hotspot')
});

Hotspot Model:

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  onVideo: DS.belongsTo('video'),
  toVideo: DS.attr()
});

Please tell me what's going wrong.




Accessing an aliased computed property from an Ember component

I am passing the value of an "Ember.computed.alias()" to a component via an attribute called "disabled". The alias itself points to a computed property.

Within the controller the alias carries the correct value returned by the computed property. However, when I try to access the "disabled" attribute from within the component like this:

this.getAttr('disabled')

the value is always "undefined".

Should I be able to pass aliases of computed properties to components?

Any help would be appreciated.

Thanks.




Am getting the error "Unknown template object: function" in my ember 1.9.1 app?

I've upgraded my ember version to 1.9.1 and handlebar version to 2.0.0. But now getting the error "Unknown template object: function" in app. The app worked perfectly with ember 1.8.1 and handlebars 1.3.0.




Ember DS.Store.findAll() returns empty collection

Hey I need to modify some records which I get from the DataStore. If I add the following code in my router I can see that the requests get passed to my template, but I can't modify each request of the collection because the collection is empty.

model() {
  return this.store.findAll('user').then(function(users) {
    console.log(users.get('length')); // 0
    return users;
  });
}

I thought that the promise gets resolved when all the records have been fetched from the server but this doesn't seem to be the case. Or did I completely miss something.

I also tried to modify the model in the afterModel callback with the same result.

I'm using Ember 1.13.0 (with Ember-CLI), Ember-Data 1.13.4 and ember-cli-mirage for Mocking my HTTP Requests.




Ember - how to convert this.get('model') to a js object

I am building an Ember component and it's being passed a model

{{ratings-summary-comp model=model}}

So you can call this model inside an action on the component's js file, like this:

this.get('model')

When I log this in the browser console, it outputs some kind of class thing. I want to convert this to a normal JS-object consisting of the model's attributes, so I can call the attributes like this:

model["attribute"]

How?




mardi 28 juillet 2015

Emberjs: _instantiatedStack error using broccoli-funnel

I'm trying to copy my font-awesome fonts to my dist/fonts directory using this:

var fontFiles = funnel('bower_components/font-awesome/', {
    srcDir: 'fonts',
    destDir: 'fonts'
});
console.log(fontFiles);

module.exports = app.toTree(fontFiles);

return app.toTree();

Using the console.log I see this:

version: 1.13.1 { inputTree: 'bower_components/font-awesome/',
_includeFileCache: {}, _destinationPathCache: {}, srcDir: 'fonts', destDir: 'fonts', _instantiatedStack: 'Error\n at new Funnel (/home/.......

I've changed around the src directory with no effect.




Ember clear records between acceptance tests using Local Storage adapter

I am writing some acceptance tests for my Ember app and I don't know the best way to remove records created in localStorage between tests. I also don't want to lose any localStorage records I have created in my development environment.

I am currently setting a namespace in the LSAdapter using an environment variable so that development and test records are stored separately:

export default DS.LSAdapter.extend({
    namespace: ENV.taskLocalStorageKey
});

I can then remove the key in the afterEach hook in my tests: localStorage.removeItem(ENV.taskLocalStorageKey); but I am sure there is much better way to do this? I am also using ember data factory guy which I thought would do this for me automatically?




ember.js vs angular.js performance testing

I am trying to make an intranet based JavaScript App which can receive and submit data via API. However, my issue is the server also accessed remotely and performance is very poor.

Due to processes within the company they will only be accessing my app through a web browser on the server itself via Remote Desktop. Because of this there are constraints on performance which need to be considered, so I am querying as to what is the most suitable low-overhead and high-performing JS framework to use.

I have studied the following finding ( http://ift.tt/1KuGzG6 ), however still I am not sure which JavaScript framework to choose or even use any JavaScript framework at all.

So I am interested to know, what is a proper way to test the performance of angular.js vs ember.js vs raw JS?

What sort of tools are available to use for performance testing? What my test cases should be?




Ember not returing a DSRecordArray on find(model,id)

I am using a REST adapter and serializer to pull in data from this.store.find(modelName, id)

In my serializer, I am successfully attaining an array from my REST api and extracting it into the store.

Why does does Ember think that if you gave it an ID in the find() parameters, that it must be a singular object?

Giving it query parameters returns collections of records however my REST API does not support that. Is there a way to set the result returned to become a record array? --- while not losing ember data cache functionality?

I would like the record array to be cached with the key id i've given in the find()




How to deploy Play on Amazon Beanstalk keeping /public editable for a single page application?

I am looking for alternative methods of deploying a Play application to Elastic Beanstalk. It is a single page app that relies on Ember.js. It would be nice to be able to edit the the contents of the /public folder so I don't need to rebuild the docker image every time something is fixed on the Ember side that doesn't affect the Play app itself.

I am currently using sbt's docker:stage command and zipping the generated docker folder along with this Dockerfile and Dockerrun.

Dockerfile

FROM java:latest
WORKDIR /opt/docker
ADD stage /
RUN ["chown", "-R", "daemon:daemon", "."]
EXPOSE 9000
USER daemon
ENTRYPOINT ["bin/myapp", "-Dconfig.resource=application-prod.conf"]
CMD []

Dockerrun

{
    "AWSEBDockerrunVersion": "1",
    "Ports": [{ "ContainerPort": "9000" }],
    "Volumes": []
}

Once I zip the file I upload it using Beanstalk console. But this involves rebuilding the app every time a typo is fixed on the front end. It is annoying because it means all the updated front end code has to wait until I get a chance to push it up so the boss can view it and give feedback. It would be nice if there was a way to have the /public folder (Play just serves /public/index.html) accessible so the front end dev could access it directly for his edits.

Ideally I would like some method that can be used for both development and production. I don't know the requirements imposed by Beanstalk so it can properly spin up extra instances of the app when needed. Maybe something where when the instance starts it does git pull on the backend repo and git pull on the front end repo, then runs my custom build script for ember to generate the /dist folder and move into Play's /public folder and create gzips of each file. Then start the play app. Then let the front end Dev ssh into the development instance and do git pull and ember build as needed for his edits.

It would also be nice for the development server for the Play server to be run using run or ~run so I can just do git pull and have it rebuild the backend.

Or maybe I am approaching this in the completely wrong way. I have never done any of this before so I am sort of guessing my way through all of it.

Thanks for any suggestions and pointers in the correct direction.

Adam




Ember 1.13 - Recompute helper when ENV variable change

I got a "get-text" helper which translate my static fields depending on a config variable : ENV.LOCALE.

The thing is, I'd like to recompute my if my ENV.LOCALE gets modified. I tried several things from sending events to Ember.observer, without much success.

// controllers/application.js
locale: function() {
    var locale = this.get('isFrench') === true ? 'fr' : 'en';
    ENV.LOCALE = locale;

    return locale;
}.property('isFrench'),    


//helpers/get-text.js
import Ember from 'ember';
import ENV from '../config/environment';

export default Ember.Helper ( function(key, locale) {
    var lang = {
        save: {
            'fr': 'Enregistrer',
            'en': 'Save',
        },
    }
    return new Ember.Handlebars.SafeString(lang[key][ENV.LOCALE]);
});

Bottom line, how can I recompute my helper when a global property changes?




I Ember, is it possible to access the app directly in an acceptance test?

I have a mixin that handles showing messages to users at various parts of the app, and hooks in the routes can remove or show them, etc.

I'm having trouble testing this mixin directly and in an isolated, because I need a full functioning app, with transistions etc.

I can test it in a "normal" acceptance test, in a specific use case, but that would technically be for a separate workflow that makes use of this mixin.

I'd like to load the app in an acceptance test, and then call some methods on certain controllers (application controller in this case), if possible.

I do have access to an application instance via:

var application;

module('Acceptance: ApplicationMessaging', {
  beforeEach: function() {
    application = startApp();
  },

  afterEach: function() {
    Ember.run(application, 'destroy');
  }
});




Ember Model get is not a function

Why sometimes in setup controller on my product route, model.get('property') works and other times I have to retrieve properties with model.property

It throws an error

model.get( is not a function...

Why is this happening, clues?




Is it possible to know the scope in which my helper is called without passing a parameter

I got the following helper :

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

export default Ember.Handlebars.makeBoundHelper( function(property, object) {
    for (var attribute in object) {
        if (attribute.indexOf("translations") > -1) {
            var translations = object.get(attribute).filterBy('locale', ENV.LOCALE);
            return translations.get('firstObject.' + property);
        }   
    }

    console.log('Trying to find property ' + property + ' on object: ');
    console.log(object);

    return false;
});

Basically I have some models that can be translated (ie name of a product). Depending on the user selected locale it will show the translation of a given property. I think it's super sexy and gives a very good feel to the user.

However, I always end up calling my helper this way :

{{ translate 'name' this }}

Is there a way that I wouldn't need to include "this" each time I call my helper and get the current scope from within my helper?




Ember component not found

I want to make a component to wrap the events from the HTML5 drag & drop API. This is the first component I made in Ember so bear with me. We pre-compile the templates into Templates.js and Components.js. We are using HTMLBars and for the templates. I've looked at the official Ember docs and some tutorials on Ember components but still it says:

Uncaught Error: Assertion Failed: A helper named 'dropzone' could not be found

This is the code Javascript code for the component in JS/Components/dropzone.js:

App.DropzoneComponent = Ember.Component.extend({
    classNames: ['dropzone'],
    classNameBindings: ['dragClass'],
    dragClass: 'deactivated',
    type: null,

    dragLeave(event) {
        if (get(this, 'type') != null) {
            event.preventDefault();
            set(this, 'dragClass', 'deactivated');
        }
    },

    dragOver(event) {
        if (get(this, 'type') != null) {
            event.preventDefault();
            set(this, 'dragClass', 'activated');
        }
    },

    drop(event) {
        if (get(this, 'type') != null) {
            var data = event.dataTransfer.getData('text/data');
            this.sendAction('dropped', type, data);

            set(this, 'dragClass', 'deactivated');
        }
    }
});

This is the Handlebars/Components/dropzone.hbs component template:

{{yield}}

It's very simple because it should only wrap some other html elements. And send for the dropped action on the controller when a file or item has been drop within it's zone.

This is how the template compiler compiled the Handlebars/Components/dropzone.hbs template:

Ember.TEMPLATES["components/dropzone"] = Ember.HTMLBars.template((function () {
  return {
    meta: {
      "revision": "Ember@1.13.5+4eb55108",
      "loc": {
        "source": null,
        "start": {
          "line": 1,
          "column": 0
        },
        "end": {
          "line": 1,
          "column": 9
        }
      }
    },
    arity: 0,
    cachedFragment: null,
    hasRendered: false,
    buildFragment: function buildFragment(dom) {
      var el0 = dom.createDocumentFragment();
      var el1 = dom.createComment("");
      dom.appendChild(el0, el1);
      return el0;
    },
    buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
      var morphs = new Array(1);
      morphs[0] = dom.createMorphAt(fragment,0,0,contextualElement);
      dom.insertBoundary(fragment, 0);
      dom.insertBoundary(fragment, null);
      return morphs;
    },
    statements: [
      ["content","yield",["loc",[null,[1,0],[1,9]]]]
    ],
    locals: [],
    templates: []
  };
}()));

From the things I read in the Ember docs and tutorials I Googled everything should be in order.




Bootstrap Nav-tabs fail for iPhone

I'm using Bootstrap with an Ember project, and following markup produces navigation tabs that work on the desktop, but fail in Chrome & Safari the iPhone 6.

Here is the markup produced:

<nav>
  <ul class="nav nav-tabs">
    <li id="ember611" class="ember-view active">  
      <a>Tab 1</a>
    </li>
    <li id="ember612" class="ember-view">     
      <a>Tab 2</a>
    </li>
  </ul>
</nav>

Tapping on Tab 2 doesn't work. Any suggestions?

I'm using Bootstrap 3.3.4, and Ember 1.3




How to deploy ember-cli app to S3

I have an ember-cli app that is deployed in S3. It works well, and I have Travis set up to deploy changes when there is a merge into the master branch in GitHub.

But sometimes I want to test a change in the deployment environment without a commit -- perhaps because it can only be tested in that environment, like a fix to a mobile-only defect.

So I tried:

ember build --environment=production

followed by:

aws s3 cp dist/ s3://my_bucket/ --recursive

which uploaded things to my bucket. But the page didn't work, my browser told me there was a redirect loop. It wasn't a code issue, because when I pushed the changes to master, Travis successfully deployed them to S3.

Is there something clearly wrong with what I did, copying the dist folder to my bucket?




Set Ember application max width to 100%

I need to set the width of my Ember app to 100%. As is, it seems to be stuck at 1450px wide.

The application level has two classes, an "emberID" and "ember-view", but of course I can't set CSS by these. Can I perhaps add a class to this top level ember element?

Thanks




What are the steps to upgrade my ember 1.8.1 app to ember 1.9.0 app?

I want to know the changes needed to be done in my ember 1.8.1 app to upgrade it to ember 1.9?




lundi 27 juillet 2015

Creating Thumbnail Picture grid in Ember using Picnicss

currently I'm in the state of confusion. I'm working of a project using one of its component in picnicss that card. so Im trying to build picture thumbnails like this :

X X X X X
X X X X X
X X X X X

where x is a picture probably with 200px * 200 px

the problem is when i tried to do like this

<div class="row">
{{#each model}}
<div class="third">
<article class="card">
<img {{bind-attr src="someimage"}}>
</article>
</div>
{{/each}}
</div>

it will not show all my images(let say i have 100 images), how to let {{#each}} know that every 7 data it will need to have new row??

thanks




ember containerview not update

I have defined a container view, and I want to dynamically add child view to property 'childviews' ,then I have the code below:

export default Ember.ContainerView.extend({
  childViews:['testView'],
  testView:InfopanelView.create(),
  testView2:InfopanelView.create(),
  init:function(){
    this._super();
  },
  addSuccessMessage:function(){    
    this.pushObject(this.get('testView2'));
    console.log(this.get('childViews'));
  }
});

when the method addSuccessMessage was called the childViews will have 2 children,but the page seems not updated,so what is the problem




Choosing a JavaScript framework to create SPA for a poor performed endpoint

I am trying to make an intranet based JavaScript App which can receive and submit data via API. However, my issue is the server also accessed remotely and performance is very poor.

I have studied the following finding ( http://ift.tt/1KuGzG6 ), however still I am not sure which JavaScript framework to choose or even use any JavaScript framework at all. Any input is appreciate it.




reopenClass error on nested routes in ember

For some reason im getting this error:

Error while processing route: inductee Cannot read property 'reopenClass' of undefined TypeError: Cannot read property 'reopenClass' of undefined

when trying to access the route I have setup like this:

Router

this.resource('hall-of-fame', function () {
    this.resource('year', {
        path: '/:year_id'
    }, function () {
        this.resource('inductee', {
            path: '/:inductee_id'
        });
    });
});

Route

App.InducteeRoute = Ember.Route.extend({
model: function (params) {
    console.log(params);
    return $.getJSON('/api/hall-of-fame/' + params.year_id + '/' + params.inductee_id);
},
setupController: function (controller, model) {
    controller.set('applicant', model);
}
});

The link-to is passing in the year and the slug correctly but when it tries to transition to the inductee template the route shows the error above. Image of Ember inspector




Ember DRY nested components with same actions

Right now I am building a particular screen within my ember app that has an unknown number of nested components. Because of this I am trying not to change the url based on the component being shown also there is some base info I want to display on every sub screen.

Currently it seems like I have to redefine and pass in all these action names everywhere when the real action logic is only defined on the route. Is there a way to DRY these action references possibly in a controller or one "parent" component.

here is an example ember-twiddle where I am rendering these components into an outlet http://ift.tt/1OLYEko

here is an example of the route

import Ember from 'ember';

export default Ember.Route.extend({
  _fixtureModels: [
    { person: {name: 'bill'}, sideModel: null},
    { person: {name: 'bill'}, sideModel: { postName: 'test post' }},
    { person: {name: 'bill'}, sideModel: { commentName: 'test comment'}}
    ],

  _renderSideModel: function (template, sideModel) {
    this.render();

    this.render(template, {
      outlet: 'side-model',
      into: 'index',
      model: sideModel
    });
  },

  renderTemplate: function () {
    this.render();

   this.render('someComponentWrapper', {
     outlet: 'side-model',
     into: 'index'
   });
  },

  model: function () {
     return this._fixtureModels[0];
  },

  actions: {
    renderTopLevel: function () {
      return this.renderTemplate();
    },
    renderPost: function () {
      return this._renderSideModel('post', this._fixtureModels[1]);
    },
    renderComment: function () {
      return this._renderSideModel('comment', this._fixtureModels[2]);
    }
  }
});

I know URL is supposed to be king in Ember and this is pretty sinful but it would be very hard to reconstruct a potentially nested view.




Ember Route Snapshot is null

I am trying to create a custom buildURL method to hit my server which has a route /blog/1/posts. In my posts route I have:

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params, transition) {
     var blog_id = transition.params['blog.show'].blog_id;
     return this.store.findAll('post', { blog_id: blog_id });
  }
});

and my postAdapter I have:

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({
  buildURL: function(type, id, snapshot, requestType, query) {
    return(
      this.get('namespace') +
        '/blog/' + snapshot.get('blog.id') +
        '/posts'
    )
  }
});

but snapshot is always null. How do I go about creating a snapshot to inject into these methods?

Any help would be appreciated. thanks!




focus-out event in Ember.Select view

I have used Ember.Select view as follows.

{{view "select" content=people
                optionLabelPath="content.fullName"
                optionValuePath="content.id"
                prompt="Pick a person:"
                selection=selectedPerson}}

Now I want to add focus-out="showErrors" event listener to this select view in order to handle some validation. This works perfectly with Ember.TextField and Ember.TextArea. But I noticed the focus-out does not work with Ember.Select view.

It would be really nice if someone can provide a solution to this problem




Not able to delete characters of cc card, expiration and security code of input field in firefox.

Working on a ember app. I have this form that takes in name, cc number, expiration and security number. I am able to backspace on name however I cant delete any of the other content, and this only happens in Firefox.

  <div class="form-group cc-name input-row {{if nameValid 'has-success'}}">
  <label class="label label--sm">Name on Card</label>
  {{input type="text" value=name class="form-control"}}
</div>

<div class="form-group cc-number input-row {{if numberValid 'has-success'}}">
  <label for="cc-number" class="label label--sm">Credit Card Number</label>
  {{input-credit-card-number number=number class="form-control"}}
  <div class="card-type {{if type 'show' 'hide'}}">
    {{#if type}}
      {{inline-svg type class="icon icon--credit-card"}}
    {{/if}}
  </div>

</div>

<div class="input-row input-row--inline">
  <div class="form-group cc-expiration input-col--50 {{if expirationValid 'has-success'}}">
    <label class="control-label label--sm">Expiration</label>
    {{input-credit-card-expiration month=month year=year class="form-control"}}
  </div>

  <div class="form-group cc-cvc input-col--50 {{if cvcValid 'has-success'}}">
    <label class="control-label label--sm">Security Code</label>
    {{input-credit-card-cvc cvc=cvc class="form-control"}}
  </div>
</div>




How do I display specific string instead of model value in template using Ember.js?

I have an Ember route displaying an array of records. The model includes status like so:

status: DS.attr('number'),

The value of status will be returned as either: -1, 0 or 1.

I have no problem displaying that value for each record in the template using handlebars: {{modelName.status}}. This way, the status for each record reflects as either: -1, 0, 1.

I would like to do the following:

If the value of status is -1 display the string "Error".
If the value of status is 0 display the string "Completed".
If the value of status is 1 display the string "Pending".

Is this possible?




is there a way to prevent editing the url manually in Ember-cli

In ember-cli is there a way to prevent the user from modifying or entering the url i.e, the url should change when the path changes (when transition occurs) but when the user tries to refresh/modify it - it should display 'page not found' or should redirect to the index page. with some research i came to know that using location: 'none' in environment.js will not display the changed url. but what i want is that the changed url should be visible but the user shouldn't able to manually modify or refresh the url.




How to trigger JQuery action without breaking separation of concerns

I use SemanticUI and Ember and I would like to make a some content disappear with a transition when clicking a button.

The way to do this with SemanticUI is $('#id').transition('type-of-transition'). Knowing that the controller should not be aware of the view (so I can't use this selector as an action of the controller), and <script> tag does not seem to be the Ember way of doing it, how can I do?

I tried to create a component that has a "transition" action, and to use it like

{{#transition-component shouldHide=shouldHide}}
<!-- Here comes what I want to make disappear -->
{{/transition-component}}

But after hiding, the composent gets refreshed and shows up back.




Access nth item when iterating Ember object array with for rather than forEach

It made more sense in a particular case today to use a standard for (i = 0.. loop rather than a forEach, but I realised I don't know how to access objects of an Ember Array by number.

So lets say we have:

var order = this.get('order');
var orderItems = order.get('orderItems');

orderItems.forEach(function(orderItem) {
  orderItem.set('price', 1000);
});

I thought I could do the equivalent as:

var order = this.get('order');
var orderItems = order.get('orderItems');

for (i = 0; i < orderItems.get('length'); i++) {
  orderItems[i].set('price', 1000);
}

but I get orderItems[0] is undefined etc.

How do I access the nth element in an ember array in js?




Is there a way to specify which variable to use in ember relationship

After specifying the relationship between

App.Post = DS.Model.extend({
  comments: DS.hasMany('comment')
});

App.Comment = DS.Model.extend({
  post: DS.belongsTo('post')
});

But what it does is it accepts integer id in 'post' and an array of integers in 'comments' can anyone please tell me how to use any other variable for the reference like name or title instead of array.




ember simple-auth-oauth2 token recieved but not stored

I'm running into some problems when using Ember-Simple-Auth with Simple-Auth-OAuth2

I have configured it as per docs and am using the authenticator out of the box as we can customize the back end to fit this.

At the moment when logging in the server returns the correct information, a JSON object

{
access_token: "rAnDomToKEn",
token_type: "Bearer",
expires_in: 45000,
refresh_token: ""
}

I think this what I'd expect to see at this point, however, then the login redirects me to root and if i navigate to a resource, my token does not seem to be sent with the next request.

My login controller is as:

import Ember from 'ember';
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';

export default Ember.Controller.extend(LoginControllerMixin, {
    authenticator: 'simple-auth-authenticator:oauth2-password-grant',
});

my config is as:

  ENV['simple-auth-oauth2'] = {
    serverTokenEndpoint: 'http://localhost:3000/token'
  };

  ENV['simple-auth'] = {
    crossOriginWhitelist: ['http://localhost:3000'],
    authorizer: 'simple-auth-authorizer:oauth2-bearer',
    store: 'simple-auth-session-store:local-storage'
  };

I'm sure I'm missing something really obvious here but can't work out what exactly. Any help would be greatly appreciated.

Thanks




Send multiple parameters from ember component

I want to send two parameters to an action in an Ember component. The documentation only suggests how to send one parameter eg as

{{#each todos as |todo|}}
    <p>{{todo.title}} {{confirm-button title="Delete" action="deleteTodo" param=todo}}</p>
{{/each}}

How do I send multiple params? Thanks




Compile templates in the browser

I have a specific use-case where I need to compile a template in the browser. That is because the template is not available at development-time.

import Ember from 'ember';
const myTempRouteList = ['home']; // this is retrieved from the backend

export function initialize(instance) {
  let container = instance.container;
  let Router = container.lookupFactory('router:main');

  myTempRouteList.forEach(function (name) {
    let routeName = name.dasherize();

    Router.map(function(){ // router.map is undefined here
      this.resource(routeName, {path: routeName});
    });
    container.register(`route:${routeName}`, Ember.Route.extend({}));
    container.register(`template:${routeName}`, Ember.HTMLBars.compile(`I am the template of ${routeName}`);

  }, this);
}

export default {
  name: 'register-routes',
  initialize: initialize
};

I run it and it is giving the following error: Uncaught Error: Cannot call 'compile' without the template compiler loaded. Please load 'ember-template-compiler.js' prior to calling 'compile'.

So I added this to my Brocfile.js:

app.import('bower_components/ember/ember-template-compiler.js');

However, the error is still present.

The versions I use: - Ember 1.13.3 - Ember-cli 1.13.1




How to get the Router instance in initializer

I have a use-case where I want to register routes dynamically in an initializer. Because the application is a self-defining app I don't know the routes at development time.

Currently I created an instance-initializer:

import Ember from 'ember';
const myTempRouteList = ['home']; // this is retrieved from the backend

export function initialize(instance) {
  let container = instance.container;
  let router = container.lookup('router:main');

  myTempRouteList.forEach(function (name) {
    let routeName = name.dasherize();

    router.map(function(){ // router.map is undefined here
      this.resource(routeName, {path: routeName});
    });
    container.register(`route:${routeName}`, Ember.Route.extend({
    }));

  }, this);
}

export default {
  name: 'register-routes',
  initialize: initialize
};

The problem is that the router instance is present but is has no method map. In the documentation it is described as a public method. Some other methods I checked are present, f.i. hasRoute.




Getting index counter in nested loop of embers handlebar

I followed http://ift.tt/1JJIfc5 blog post to add index counter through helper. This works perfectly fine with single each loop. But when i use it with nested each loop the value gets repeated. Example :

{{#each item in data}} {{#eachIndexed record in item.innerdata}} {{index_1}} {{/eachIndexed}} {{/each}}

I have two objects in data and two objects in each innerdata. Expected result is

1 2 3 4

but I'm getting

1 2 1 2

How do i get the expected result? My handlebars version is 1.1.2 and ember version is 1.6.1.




dimanche 26 juillet 2015

How do I setup Ember-CLI belongsTo dropdown?

I am having issues saving a belongsTo relationship in Ember-CLI using Ember Data. I have a contact model that belongs to a client model. Here are the models:

// models/contact.js

import DS from 'ember-data';

var Contact = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    title: DS.attr('string'),
    email: DS.attr('string'),
    phone: DS.attr('string'),
    client: DS.belongsTo('client', {async: true}),
});


export default Contact;


// models/client.js
import DS from 'ember-data';

var Client = DS.Model.extend({
    name: DS.attr('string'),
    phone: DS.attr('string'),
    email: DS.attr('string'),
    summary: DS.attr('string'),
    contacts: DS.hasMany('contact', {async: true}), 
});

export default Client;

Here is my template:

<form {{action "save" on="submit"}}>

{{view "select" 
        contentBinding=model.client
        optionLabelPath="content.name"
        optionValuePath="content.id"
        selectionBinding="contact.client.content" }}
  <div>
    <label>
      First name
      {{input type="text" value=model.firstName}}
    </label>
  </div>
  <div>
    <label>
      Last name
      {{input type="text" value=model.lastName}}
    </label>
  </div>
  <div>
    <label>
      Title
      {{input type="text" value=model.title}}
    </label>
  </div>
  <div>
    <label>
      Email
      {{input type="text" value=model.email}}
    </label>
  </div>
  <div>
    <label>
      Phone
      {{input type="text" value=model.phone}}
    </label>
  </div>
  <div>
    <input type="submit" value="Save">
  </div>
</form>

This is the save mixin for this model:

import Ember from 'ember';

export default Ember.Mixin.create({
  actions: {
    save: function() {
      var route = this;
      var client = this.client;
      console.log(client)
      this.currentModel.save('contact', {client: client}).then(function() {
        route.transitionTo('contacts');
      }, function() {
        console.log('Failed to save the model');
      });
    }
  },
  deactivate: function() {
    if (this.currentModel.get('isNew')) {
      this.currentModel.deleteRecord();
    } else {
      this.currentModel.rollback();
    }
  }
});

I'm currently getting undefined from the console.log(client) and an Uncaught TypeError: this.currentModel.save is not a function from the line following.

As best I can tell, I'm having issues passing the selected client from the dropdown to the save mixin...

Any help/ideas would be much appreciated!




Ember Simple Auth Torri custom Provider

I am trying to create a custom OAuth Provider for Ember Simple Auth Torri wrapper for Yahoo OAuth 2.0. I used the built in providers for Facebook and Google without any problems,but since Yahoo OAuth package is not provided by default I am trying to follow the manual and create my own.

//app/torri-provider/yahoo-oauth2.js

export default Ember.Object.extend({
  host: 'http://ift.tt/1HTHuyV',
  // create a new authorization
  open: function(options) {
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log("Hi");
      var authurl="http://ift.tt/1INw4NT";

      return $.ajax(authurl, "GET", {
        // CORS
        crossDomain: true,
        xhrFields: {withCredentials: true}
      }).then(function(json) {
        // Massage this demo API endpoint to look like RESTAdapter expects.
        return { things: [json] };
      });


    });
  }
});

In my controller,I am calling it as -

'yahoo-share':function(){
  var self=this;
  this.get('session').authenticate('simple-auth-authenticator:torii',"yahoo-oauth2");
},

I am however unable to get part the CORS issue and receiving the following error on my console-

userhomeinvitemembers:1 XMLHttpRequest cannot load http://ift.tt/1INw4NT. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I have tried adding the oauth2 endpoint to ember cli whitelist and content security policy whitelist but still getting the same error.

  ENV.contentSecurityPolicy = {
    'default-src': "'none'",
    'script-src': "'self' http://localhost:4200/",
    'font-src': "'self' http://localhost:4200/",
    'connect-src': "'self' http://localhost:4200/ http://localhost:3000/ http://ift.tt/1HTHuyZ http://ift.tt/1INw4NT",
    'img-src': "'self'",
    'style-src': "'self'",
    'media-src': "'self'"
  },


    ENV['simple-auth'] = {
      crossOriginWhitelist: ['http://ift.tt/1INw4NT'],
      authorizer: 'simple-auth-authorizer:oauth2-bearer',
      authenticationRoute: 'index',
      routeIfAlreadyAuthenticated:'userwelcome',

    },

    ENV['torii'] = {
      providers: {
        'facebook-oauth2': {
          apiKey: '799728020115355'
        },
        'google-oauth2': {
          apiKey:'299472944809-sddblocmketamp64sapk51qdrromkj0g.apps.googleusercontent.com',
          scope: 'http://ift.tt/yb7fwm',
          redirectUri:'http://localhost:4200/userhomeinvitemembers'
        },
        'yahoo-oauth2': {
          apiKey:'dj0yJmk9UmpXWG1odlVlenRSJmQ9WVdrOVdFUkxRbVo2TkdVbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD04Zg--',

        }
      }
    };




Returning 1 object/record from my model in Ember

In a test app I running, I have fixture data for employees with name, department, etc. Currently, my model contains all of the employees, and I am able to make an employee list. However, I want to make a side component that lists the information of 1 specific employee (i.e. the one clicked, as a tooltip). How can I pass just 1 employee to my component?

I have an action that updates a property whenever someone clicks a name. I thought to do a computed property to query the model based on that name, but I am not sure how to filter my model to return just the one employee.

actions: {
  updateProfile(person) {
    set(this, 'profile', person);
  }
}

And my computed property:

currentProfile: computed('profile', function(){
  return this.model.find('person', {'name': get(this, 'profile')});
}),

Is there a simple way to return just the 1 object I want from my model?




Adding an image in placeholder of .hbs ember template file

I want to add an image to a .hbs template file in ember. I dont build applications I'm just simply trying to style up the basic todo list app.

<section class='todoapp'>
  <header id='header'>
    <img src="../assets/logo2.png" />
    {{input type='text'
            class='new-todo'
            placeholder='What else is in your wallet?'
            value=newTitle
            enter='createTodo'}}
  </header>

My goal is to add an image next to the placeholder field before someone clicks into the inputer field. I'm assuming I cant add it with the value so do I do something with the .new-todo class in css to drop the image in?




Saving a user to a session as a computed property

I've seen other questions about this (like this one), and I believe this should be working

import Ember from 'ember';
import Session from 'simple-auth/session';

export default {
  name: 'session-with-me',
  before: 'simple-auth',
  initialize: function() {
    Session.reopen({
      me: function() {
        if (this.get('isAuthenticated')) {
          return this.container.lookup('service:store').find('me', { singleton: true });
        }
      }.property('isAuthenticated')
    });
  }
};

the find('me', { singleton: true }) is a working patch of ember-jsonapi-resources. While debugging I can see the request being sent, and the payload comes through. I use the same find call elsewhere in the app, and can confirm a model gets instantiated fine.

On the inspector, under container > simple-auth-session I can see me as a session property, but it shows as { _id: 68, _label: undefined ...}

Has the way to set a session property changed? I may have seen a mention about this somewhere, but I can't find it anymore.

This is in the same domain of another question I asked earlier, but I'm giving up on that approach and trying simply to fetch the user independently of the authentication process.




find and findAll return an empty array

In an ember 1.13.3 app, I have this route :

import Ember from 'ember';

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

And this model :

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  link: DS.attr('string'),
  acquired_skills: DS.hasMany('users', { async: true, inverse: 'acquired_skills' } ),
  searched_skills: DS.hasMany('users', { async: true, inverse: 'searched_skills' } )
});

This is the result returned by the api :

{"skills":[{"id":1,"name":"Ember","description":"JS Framework","link":null}]}

The array is empty. I can check it with this console.log(this.store.find('skill').get('length')); and I have 0.

What's wrong?




Ember.cli acceptance tests Could not find module

I have been trying to figure out why my integration tests aren't working for a few days now. Here is the travis log:

http://ift.tt/1gdZ2Nq

The error is:

Could not find module ember-modal-dialog/initializers/add-modals-container imported from car-mileager-frontend/initializers/add-modals-container

The only reference to add-modals-container that I can find is in a third party package ember-cli-materialise.

I also mock my API using ember-mock.

Kind of new to ember so not sure what further debugging I can do. The source code for the project is:

http://ift.tt/1OuylPc

When I run

$ ember test

From my command line I get the same error...

Thanks for any help!




Using links with Ember Data

I have a model Teacher which has many Students.I want to lazy-load the students association so I use the "links" format. All is ok, when my JSON is:

"links": {
  "students": "/teacher/1/students"
}

But when i try to add "meta" property:

"links": {
  "students": {
     "href": "/teacher/1/students",
     "meta": 20,
  }
}

I'm getting an error:

Error while processing route: teacher Assertion Failed: You have pushed a record of type 'teacher' with 'students' as a link, but the value of that link is not a string. Error: Assertion Failed: You have pushed a record of type 'teacher' with 'students' as a link, but the value of that link is not a string.




ES6 Set setting but "size" not changing

I am using ES6's new Set type/object and I'm running into a very odd problem where when I add an item to the set it shows up as part the <entries> but the size doesn't shift from zero:

console.log

To give a bit more context, here's the code that initially sets up the code:

selectedValues: on('init',computed('group.selected', {
  set: function(param,value) {
    return typeOf(value) === 'array' ? new Set(value) : new Set([value]);
  },
  get: function() {
    return new Set();
  }
}))

Note: this is an Ember computed property for those of you not familiar with the syntax

and here's the code that is adding/deleting elements of the set:

  if(selectedValues.has(elementId)) {
    selectedValues.delete(elementId);
  } else {
    selectedValues.add(elementId);
  }

At any point in execution I can see from the console that the item is being added and removed from the Set but the size property is not effected. At the same time if I run the same set of commands from the browser's console it does work.

For those familiar, I am using Babel via the ember-cli-babel plugin. I have tried this problem both with and without the includePolyfill option (aka, including -- or not -- Babel's browser polyfill).




Ember Simple-Auth empty payload

I just recently started learning Ember and I'm trying to make a login page using Ember Simple-auth and Laravel JWT packages. The problem is that my Ember submit action sends an empty payload. It seems like the getProperties function is not getting the input values, why is that? I've tried using every Google example that I could find with no success.

My controller:

// controllers/auth/login.js
import Ember from 'ember';
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';

export default Ember.Controller.extend(LoginControllerMixin, {
  actions: {
    authenticate: function() {
      var credentials   = this.getProperties('username', 'password'),
          authenticator = 'simple-auth-authenticator:token';

      this.get('session').authenticate(authenticator, credentials);
    }
  }
});

My login template:

// templates/auth/login.hbs
<form {{action "authenticate" on="submit"}}>
  <div class="alerts"></div>
  <div class="form-group">
    <label>
      <div class="title">Username</div>
      {{input value=username type="text" class="form-control" placeholder="Username"}}
    </label>
  </div>
  <div class="form-group">
    <label>
      <div class="title">Password</div>
      {{input value=password type="password" class="form-control" placeholder="Password"}}
    </label>
  </div>
  <button type="submit">Login</button>
</form>

Environment

ENV['simple-auth'] = {
  store: 'simple-auth-session-store:local-storage',
  authorizer: 'simple-auth-authorizer:token'
};
ENV['simple-auth-token'] = {
  refreshAccessTokens: true,
  timeFactor: 1,
  refreshLeeway: 300,
  serverTokenEndpoint: '/api/authenticate/',
};