lundi 29 février 2016

Ember passing multiple list items in template

Is it possible to pass multiple list of items in template using {{each}}

Can someone guide me on what I am doing, in my sales-orders.hbs below is my currenet code.

    {{#each model as |detail|}}
        <li>{{sales-orders-grid detail=detail}}</li>
    {{else}}
      Blank
    {{/each}}
    </ul>

Then calling the sales-orders-grid component

Shipping Method
      <div class="col-xs-12 col-md-12 col-sm-12 products-item-products border-left padding10">
        <ul>
            {{#each shippingMethod as |sm|}}
                {{sales-orders-grid-shipping-method sm=sm}}
            {{/each}}
        </ul>
      </div>

In my sales-orders-grid-shipping-method component calling is this:

sm.shippingMethodName

What I'm trying to achieve here is to pass list of items in {{each}} in my main template. Is it possible?




Ember bind with controller instead of model

I am currently fetching my model into a list of input helpers and binding their value attributes with the field id(from the model). Like

{{input value=field.id  type=field.type 
  class="form-control" placeholder=field.placeholder}}

My aim is to have a mathematical operation carried out on this field and displayed on another input field(like a formula). I also have properties dynamically created in the controller in the afterRender hook(with the same ids of the model contents).

However, when I update my value in the input field, the corresponding controller property is not updated. Instead, the model is getting updated.




create drop down list with optgroup in ember

I very new to ember. I want all parent values should be displayed as dropdown label and all child values should displayed as detail value. Both parent and child is refering to same model.

Json Object res.send({ 'data': [{ "id": "1", "type": "category", "attributes": { "created-by": 1, "created-date-time": "2016-01-18T16:36:55", "description": "color", "name": "color", "value": "Color", "order": 1, "updated-by": 1, "updated-date-time": "2016-01-18T00:00:00" }, "relationships": { "children": { "data": [{ "id": "11", "type": "category" }, { "id": "12", "type": "category" }] }, "parent": { "data": null

          },
          "templates": {
              "data": []
          }
      }
  }],
  "included": [{
      "id": "11",
      "type": "category",
      "attributes": {
          "created-by": 1,
          "created-date-time": "2016-01-18T00:00:00",
          "description": "Red",
          "name": "Red",
          "value": "Red",
          "order": 1,
          "updated-by": 1,
          "updated-date-time": "2016-01-18T00:00:00"
      },
      "relationships": {
          "children": {
              "data": []
          },
          "parent": {
              "data": {
                  "id": "1",
                  "type": "category"
              }
          },
          "templates": {
              "data": [{
                  "id": "1",
                  "type": "templates"
              }]
          }
      }
  },
  {
      "id": "12",
      "type": "category",
      "attributes": {
          "created-by": 1,
          "created-date-time": "2016-01-18T00:00:00",
          "description": "Blue",
          "name": "Blue",
          "value": "Blue",
          "order": 1,
          "updated-by": 1,
          "updated-date-time": "2016-01-18T00:00:00"
      },
      "relationships": {
          "children": {
              "data": []
          },
          "parent": {
              "data": {
                  "id": "1",
                  "type": "category"
              }
          },
          "templates": {
              "data": [{
                  "id": "1",
                  "type": "templates"
              }]
          }
      }
  }]
});

});

model.js

export default DS.Model.extend({
type:DS.attr('string'),
key:DS.attr('string'),
order:DS.attr('string'),
value:DS.attr('string'),
childrenCat:DS.hasMany('children')

});

how can i achieve this?? kindly help me..




Ember Data json formatting/serializing

I'm using Ember 2.3 with Ember Data but am having trouble getting data to save to my rails server. It appears that the data isn't formatted properly for what the server is expecting.

The data that works (from a scaffolding app) looks like this:

{name: "Clinic Demo", code: "CLN", position: 4}

This is what Ember Data sends:

{"data":{"attributes":{"name":"Clinic Demo","code":"CLN","position":5},"type":"clinics"}}

Should I look at serializers or change what the server expects? Serializers don't seem to be the answer. The adapter configured does hit the server, but isn't expecting this type of json data. Does the active-model-adapter correct this?

Also ember is returning this very non-descript error:

Error: The adapter rejected the commit because it was invalid




Ember CLI + Mirage: When are objects saved to the store

I'm writing some tests where I create a bunch of objects which rely on each other. My code looks like:

let translations =
        [server.create('translation', { key: 'positive.callRating', value: 'How would you rate your call with %agentFirstName%?' }),
         server.create('translation', { key: 'negative.sorry', value: 'What could %agentFirstName% have done better?' }),
         server.create('translation', { key: 'social.ratingGiven', value: 'I just rated %agentFirstName% %stars%!' })];

let profile = server.create('profile', { first_name: 'Andy' });
let employee = server.create('employee', { profile: profile });
let company = server.create('company', { handle: 'lendingtree', translations: translations });
let bootstrap = server.create('bootstrap', { stars: 5, company: company, employee: employee });

And I have a service which is supposed to know about some of these objects. When I call:

this.get('store').peekAll('translation')

from the service I get no results, but all of my other objects, retrieved the same way, exist in the store; profile ,employee, company and bootstrap.

I'm sure I have to tweak my model or serializer or factory somehow to make this work but it'd be more useful to know about the fundamentals.

What causes an object created via Mirage to enter the store? Are there certain requirements they must meet? Does it depend on their relation to other objects?




hasMany relationship with JSON links

I'm attempting to construct a dynamic REST call in my ember app. I was attempting to use this solution as a starting point but it's not working and I'm not sure if it's because Ember is now using JSON API and I'm structuring it wrong: Dynamic segment in ember data adapter

In the back end the call looks like /posts/{postID}/comments and I want to be able to dynamically get comments from post of ID 1, 2, 3, etc...

Here is my basic structure
Post model:

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

Comment Model:

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

Template:

<ul>
  {{#each model as |post|}}
    {{#each post.comments as |comment|}}
      <li>{{comment.name}}</li>
    {{/each}}
  {{/each}}
</ul>

Json Post Payload:

  "data": [{
    "type": "posts",
    "id": "1",
    "attributes": {
      "id": 1
      "name": "my title"
    },
    "links": {
      "comments": "comments"
    }
  }]

My goal is for the call to comments to construct a namespace that looks like /posts/1/comments using the template above. I'm getting the post model back and have verified that the first {{#each}} loop works, but the call to post.comments does nothing in the template.




Ember App not playing sound in Chrome

I have built an ember music app consuming favorite songs by SoundCloud using the api of this project. You can see the demo here

From a couple of days i have noticed that only in Chrome any song i play, the sound and and the stream do not work, in the other browsers ( Safari and Firefox) it works well as usual.

I thought at the beginning it was violating the content Security Policy directive in environment Ember Cli. See the question here but although i have solved it, the problem is still there, plus there is not console log error

These are all the actions i have taken in Chrome to fix it, none of them was successful

  • Removed any chrome extension
  • Clear cache and deleted cookies
  • Tried in incognito mode
  • Reinstalled Chrome

My chrome is update , the version is 48.0.2564.116 (64-bit)

At the moment the sound and the stream do not work in my app and also in the demo http://ift.tt/1QHaWJI but in all the other browsers yes.

So question is, what other actions can i take? Should i maybe downgrade a Chrome Version as last try? Is it only a browser problem?

I have also followed these instructions with not solution




Data binding broken after putting raw ajax json in models

First I had this code in routes/index.js:

        hotspots:ajax( {
          url: 'url-to-external-api',
          type: 'get'
        } ).then( function( data ) {
          console.log( 'hotspots: ', data );
          return data;
        } )

I changed this to:

hotspots: this.store.findAll( 'hotspot' )

And in models/hotspot.js:

import DS from "ember-data";

export default DS.Model.extend( {
  about: DS.attr( ),
  category: DS.attr( ),
  hide_directions: DS.attr( ),
  image_highres: DS.attr( ),
  image_lowres: DS.attr( ),
  images: DS.attr( ),
  lat: DS.attr( ),
  lng: DS.attr( ),
  name: DS.attr( ),
  order: DS.attr( ),
  timestamp: DS.attr( ),
  x_axis: DS.attr( ),
  y_axis: DS.attr( )
} );

In adapters/hotspot.js:

import DS from 'ember-data';

export default DS.Adapter.extend( {
  findAll: function( store, type, sinceToken ) {
    var url = type;
    var query = {
      since: sinceToken
    };
    return new Ember.RSVP.Promise( function( resolve, reject ) {
      Ember.$.getJSON( "url-to-external-api" ).then( function( data ) {
        console.log( data );
        Ember.run( null, resolve, data );
      }, function( jqXHR ) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        Ember.run( null, reject, jqXHR );
      } );
    } );
  }
} );

When I used the ajax call in routes/index.js, I edited some of the properties of some hotspots in the array. And it would directly be updated in my app through 2-way data-binding. Now that I'm using models, I don't have this data-binding anymore.

At first I used this code in an action to change some of the properties of the hotspots:

  for ( let value of this.currentModel.hotspots ) {
    if ( value.id === hotspotId ) {
      console.log( value );
      Ember.set( value, "x_axis", event.offsetX );
      Ember.set( value, "y_axis", event.offsetY );
    }
  }

Now I'm using this:

  for ( let value of this.currentModel.hotspots.content ) {
    if ( value.id === hotspotId ) {
      console.log( value );
      Ember.set( value._data, "x_axis", event.offsetX );
      Ember.set( value._data, "y_axis", event.offsetY );
    }
  }

Which isn't working anymore.

How can I resolve this? Models are best practice, but for what? They are just a pain and working with raw ajax calls is way more easy and straight-forward...




Javascript: Passing variable into Promise

I am working on an open source EmberJS project that is making an Ajax request for information and then needs to resolve based on a dynamic subpart of the response.

  return new Promise((resolve, reject) => {
    const { resourceName, identificationAttributeName } = this.getProperties('resourceName', 'identificationAttributeName');
    const data         = {};
    data[resourceName] = { password };
    data[resourceName][identificationAttributeName] = identification;

    return this.makeRequest(data).then(
      (response) => run(null, resolve, response),
      (xhr) => run(null, reject, xhr.responseJSON || xhr.responseText)
    );
  });

....

makeRequest(data, options) {
  const serverTokenEndpoint = this.get('serverTokenEndpoint');
  const requestOptions = $.extend({}, {
    url:      serverTokenEndpoint,
    type:     'POST',
    dataType: 'json',
    data,
    beforeSend(xhr, settings) {
      xhr.setRequestHeader('Accept', settings.accepts.json);
    }
  }, options || {});

  return $.ajax(requestOptions);
}

In the end, I need the success response to run something like

(response) => run(null, resolve, response[resourceName]

but inside the response function, I have no access to the resourceName. How would I send this in?




Ember issue with routes and parameters

I am running into an issue setting up routes. I have a route group of

this.route('users', function () {

for

/users

/users/add

as well this.route('users', {path: '/users/:user_id'}, function () {

for routes like

/users/1/edit

/users/1/goals

/users/1/goals/1

The issue I have is that {{#link-to 'users'}}Users{{/link-to}} results in a link to "/users/undefined", which causes other issues, it needs to be "/users". Is there a way to do routes like this or would I be forced to have "users" and "user" route groups?




Filtering an array in ember

Ok so I'm fairly new to programing, I know how to run a filter on a JSON Array but I cant seem to figure it out when I'm pulling the data from firebase and viewing it in an Ember app.

this is my route.js code:

    import Ember from 'ember';

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

This is my template.hbs code the href="#!" is the generic from materialize for the dropdown buttons:

    <div class="list-wrapper col-xs-10 col-xs-offset-1">
        <div class="col-xs-12 button-div">
           {{#md-btn-dropdown text='Filter' class="col-xs-2"            belowOrigin=true}}
               <li><a href="#!">Female</a></li>
               <li><a href="#!">Male</a></li>
               <li><a href="#!">All</a></li>
           {{/md-btn-dropdown}}
        </div>
        {{#each model as |info|}}
        <div class="col-xs-3 user-card">
           <div class="card-info">
               <ul>
                   <li>Last Name- {{info.lastName}}</li>
                   <li>First Name- {{info.firstName}}</li>
                   <li>Gender- {{info.gender}}</li>
                   <li><a href="mailto:{{info.email}}">{{info.email}} </a></li>
               </ul>
           </div>
       </div>
       {{/each}}
    </div>
    {{outlet}}

This is my controller.js code which I no is all wrong:

    import Ember from 'ember';

    export default Ember.Controller.extend({
      customFilter: function(gender) {
         return function(el) {
            var r = el.user;
            return r.gender === gender;
         };
      }
    });

and this is my model:

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

    export default DS.Model.extend({
      lastName: DS.attr('string'),
      firstName: DS.attr('string'),
      gender: DS.attr('string'),
      email: DS.attr('string')
    });

I've searched high and low and I'm sure I'm just missing something basic and stupid. What I want is for the dropdown menu to be able to filter and display only female, male or all. Again I'm new to this stuff so I apologize if this is a pretty basic thing. Thank You




Same Application But different Framework

I was just wondering is there any application currently live having same scope made with angular.js and ember.js i.e. what i mean is application having same scope but made in different framework (One in angular.js and another is ember.js but with same scope)




Access a specific index of Ember.ArrayProxy in Handlebars

I have this code in my handlebars template:

  {{#each maps as |map|}}
    {{map.title}}
  {{/each}}

Which gives me the title of every map.

But if I try to access a specific index, like this:

<p>{{maps.[0].title}}</p>

Or

<p>{{maps.Get.[0].title}}</p>

It gives me nothing (but it compiles).

the 'maps' variable is of type:

Ember.ArrayProxy

So how can I access the map located at index 0?




Form data saving in Ember.JS - using version 2.3

There is this post: "What's the right way of doing manual form data saving with Ember.js?", however, I am at a loss as to how to do this with Ember 2.3.

In the accepted answer to that question, we have this snippet:

App.IndexController = Ember.ObjectController.extend({
  proxy: {},
  setUnknownProperty: function(key, value) {
    console.log("Set the unknown property: " + key + " to: " + value); 
    this.proxy[key] = value;
    console.log(this.proxy);
  },
  flush: function() {
    for(var key in this.proxy) 
      this.set('model.'+key, this.proxy[key]);
  }
}); 

however, I do not have an "ObjectController" in my project. Running

ember generate controller test

gives me something that reads Ember.Controller.extend({ ... });, and not an ObjectController. Searching the 2.3 API, I cannot find ObjectController at all.

Inserting the snippet into the Ember.Controller.extend, where my various action methods are placed seems to not do the trick. The entire model disappears (no data), and adding data does not work either. Nothing happens, no errors, nothing. The methods are probably just not being called at all.

Any advice on "converting" this to 2.3 would be appreciated.




Can ember-cli watch and re-run my server code too?

So I have a simple Ember.js app which communicates with a node.js server using websockets. The stream server doesn't serve the actual ember app - just various bits of data. Can I have ember-cli automatically re-run my server code when a file is changed inside it?

My workflow is currently

ember s

node ./stream_server/index.js -p 4201

Now I can edit frontend stuff and have everything automatically update. Great! However, if I make a change to my server code, I have to manually go in and C-c it, and re-run node ./stream_server/index.js -p 4201. This gets kind of boring when I know that somewhere in Ember, there's a watcher that's already doing this for frontend stuff.

So, any chance of this working? Or do I just use some other watcher tool to do it?

Cheers,

Carl




Use Multiple Dynamic Segment And Ember Model

I found out that to use multiple dynamic segment in route, you need to pass model data to the #link-to helpers

But pass model to #link-to helpers cause model to not reloaded after it enter once, and vice versa, you can always relaod model if you pass the item id to #link-to, but this will cause multiple dynamic segment not work, since it require the model

How to solve this?




How to detect a click outside an element and send the event by ember?

My problem look like: How to detect a click outside an element?

But I want to use ember.js do this. My template code:

<td colspan="2" {{action "changeName" on="doubleClick"}}>
  {{#if isEditName}}
    {{input type="text" value=editName class="form-control"}}
  {{else}}
    {{product.name}}
  {{/if}}
</td>

I want to do when I double click the div, show input and I can change name in input. I think when I change name and click the body will save the name. I think is better. But I don't know how to set the event in body, when I click the body will hide input and save product.name.

Thanks.




dimanche 28 février 2016

Is there a setInterval equivalent in Ember.js?

Is there a method I should be using for this? I couldn't find anything in Ember.run.

I'm thinking of implementing something very simple like this:

runOnInterval(){
  this.set('interval', Ember.run.later(this, function() {
    //Do something
    this.runOnInterval();
  }, 5000));
}

Any better way to do this? Should I just use setInterval?




Intel XDK + Ember - bower_components/jquery/src/intro.js: Unexpected token (45:0)

I'm trying to use Ember + Intel XDK.

I create a brand new Ember app:

ember new cash

Run ember server, and go to localhost:4200 - everything ok - Welcome to Ember page appears.

Then I open Intel XDK and import my Ember HTML project. I just import it, go back to console and run ember server again. Then I get:

cash git:(master) ✗ ember server
version: 2.3.0
Livereload server on http://localhost:49152
Serving on http://localhost:4200/
File: cash/bower_components/jquery/src/intro.js
cash/bower_components/jquery/src/intro.js: Unexpected token (45:0)
SyntaxError: cash/bower_components/jquery/src/intro.js: Unexpected token (45:0)
  43 | // you try to trace through "use strict" call chains. (#13335)
  44 | //"use strict";
> 45 |
     | ^
at Parser.pp.raise (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/location.js:24:13)
at Parser.pp.unexpected (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/util.js:82:8)
at Parser.pp.parseExprAtom (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/expression.js:425:12)
at Parser.pp.parseExprSubscripts (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/expression.js:236:19)
at Parser.pp.parseMaybeUnary (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/expression.js:217:19)
at Parser.pp.parseExprOps (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/expression.js:163:19)
at Parser.pp.parseMaybeConditional (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/expression.js:145:19)
at Parser.pp.parseMaybeAssign (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/expression.js:112:19)
at Parser.pp.parseExpression (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/expression.js:79:19)
at Parser.pp.parseStatement (/Users/Antonio/Code/mbcash/cash/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/node_modules/babylon/lib/parser/statement.js:137:23)

I'm using ember-cli 2.3.0, which leads me to:

DEBUG: -------------------------------
DEBUG: Ember      : 2.3.1
DEBUG: Ember Data : 2.3.3
DEBUG: jQuery     : 2.1.4
DEBUG: -------------------------------

I tried to use the following in ember-cli-build.js:

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

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    babel: {
      compact: false
    }
  });
  return app.toTree();
};

but when I run ember server, I got these two lines:

version: 2.3.0
Livereload server on http://localhost:49152
Serving on http://localhost:4200/

and it stops there.

If I go to the browser and visit localhost:4200, nothing happens, and the browser status bar shows:

Waiting for localhost...

I think I'm trying something new, because I searched a lot, but didn't find discussions about Ember + Intel XDK.

If somebody can help me, thanks in advance.




Ember.js 2.3 implement @each.property observer on a HasMany relationship?

Say I have a hasMany relationShip Procedure => hasMany Steps, with async:true, and I have a Procedure Component (on the procedure route) called procedure-main, which lists the steps as so:

{{each procedure.steps as |step| }}
 {{step.title}}
{{/each}}

I need to observe a property on each step (say, stepStatus) on change to the stepStatus on any of the steps. In Ember 1.7, I had something like this on the procedure controller:

stepsStatusObserver: function(){
...
}.observes('steps.@each.stepStatus')

This was fired on change of stepStatus on any on the steps, and whatever I had in this function was fired whenever the status changed as well. However, in Ember2.3, I cannot implement this. I have tried with

stepsStatusObserver: Ember.observer('steps.[].stepStatus', function(){
...
})

but this only fires once when the steps are being listed on the page. When I change the status of one step to a new value, the function is never fired.

How can I replicate this functionality in Ember 2.3?

Note: In my use case, I cannot rely on manually setting off the function inside the observer on the click of a button as it must automatically fire if the stepStatus property was changed on any step.




Ember Authentication Confusion

I am a little confused about how Ember authentication works with a RESTful API. I am using Sails.js for my API. I setup Google OAuth and when the user goes to http://ift.tt/21BVgzq they are redirected to Google and login. After that, the API works (no access to API unless authenticated). http://ift.tt/14icA3P does exactly what you would expect. This all works great. Now I am working on the client side application. I am using Ember.js. This looks like a helpful addon: http://ift.tt/19DSWMs. Is what I am trying to do considered "Authorization Grant flow"? Ember shouldn't even care if the server is using OAuth or something else so this doesn't seem right to me. Any pointers would be greatly appreciated, I am very new to OAuth and Ember. Thanks!




How to query last record with Emberfire

Using Ember.js and Emberfire, how do you query the latest record in a collection?

You can use post.get('comments.lastObject') but it queries the entire collection, meaning it's not very efficient.

I believe I need to go with something along these lines but I can't find the right combination. Any ideas?

// post return this.store.query('comment', { orderBy: 'post', equalTo: post.get('id'), limitToLast: 1 });




Ember component, how to wait for random jQuery plugin initialization?

I have an Ember component wrapping a random jQuery plugin.

setUp: on('didInsertElement', function() {
  scheduleOnce('afterRender', () => {
    this.$().datetimepicker();
  });
})

The plugin takes about 250ms to show up on screen, which causes me to write acceptance tests like so:

test('clicking toggles visibility', function(assert) {
  let done = assert.async();

  visit('/');

  andThen(function() {
    assert.strictEqual(find('.xdsoft_datetimepicker:visible', 'body').length, 0);
  });

  click('.xdsoft_datetimepicker');

  setTimeout(() => {
    andThen(function() {
      assert.strictEqual(find('.xdsoft_datetimepicker:visible', 'body').length, 1);
      done();
    });
  }, 500);
});

My goal is to alter the component so I can rely on the click test helper to block until the jQuery element is on screen. Something like didInsertElement or the run loop waiting for a promise that I can resolve once the element is on screen would be perfect. Does anything like this exist?




ember js, trying to use ember-jquery-mobile add-on

I'm trying to import [ember-jquery-mobile][1] to my ember project, so I followed the instructions and simply ran: ember install ember-jquery-mobile.

This got my project no to run any more and I just get the error:

    ENOENT: no such file or directory, stat '/Users/giulio/Documents/rails/project/tmp/source_map_concat-input_base_path-http://ift.tt/2145lDc'
    Error: ENOENT: no such file or directory, stat '/Users/giulio/Documents/rails/project/tmp/source_map_concat-input_base_path-http://ift.tt/2145lDc'
        at Error (native)
        at Object.fs.statSync (fs.js:892:18)
        at ConcatWithMaps.keyForFile (/Users/giulio/Documents/rails/project/node_modules/broccoli-caching-writer/index.js:90:20)
        at Array.map (native)
        at ConcatWithMaps.CachingWriter._conditionalBuild (/Users/giulio/Documents/rails/project/node_modules/broccoli-caching-writer/index.js:112:65)
        at /Users/giulio/Documents/rails/project/node_modules/broccoli-caching-writer/node_modules/broccoli-plugin/read_compat.js:61:34
        at lib$rsvp$$internal$$tryCatch (/Users/giulio/Documents/rails/project/node_modules/rsvp/dist/rsvp.js:493:16)
        at lib$rsvp$$internal$$invokeCallback (/Users/giulio/Documents/rails/project/node_modules/rsvp/dist/rsvp.js:505:17)
        at lib$rsvp$$internal$$publish (/Users/giulio/Documents/rails/project/node_modules/rsvp/dist/rsvp.js:476:11)
        at lib$rsvp$asap$$flush (/Users/giulio/Documents/rails/project/node_modules/rsvp/dist/rsvp.js:1198:9)  

any clues?




Ember intermittent acceptance test failures that pass when run alone

I'm hoping to get some clues about why I have intermittent test failures. I have an acceptance test that fails when I run the entire module, but all of the individual tests pass when they are run alone. The issue seems to have something to do with using a loop around assertions because I have two different tests that fail and both have a forEach loop something like this:

import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from "dwellconnect-app/tests/helpers/start-app";

var things;

module('Acceptance | something', {
  beforeEach: function() {
    this.application = startApp();
    things = [
      Ember.Object({someProperty: '1'}),
      Ember.Object({someProperty: '2'}),
      Ember.Object({someProperty: '3'}),
      Ember.Object({someProperty: '4'}),
    ]

  },

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

test('Something', function(assert) {
  assert.expect(5);

  visit('/something');

  andThen(function() {
    // Check that each thing is on the page
    things.forEach(function(thing) {
      var someSelector = 'span:contains("' + thing.someProperty + '")';
      assert.equal(find(someSelector).length, 1, 'Shows each thing');
    });
  });
});

First of all, is there something wrong with this approach and if so, what is the correct way to build a set of assertions around an array of data. If not, what else could be causing the issue? Even if you can only provide possible scenarios for intermittent failures, it might lead me in the right direction. Right now there are no errors and this is making me crazy. I'm not sure Sherlock Holmes could find this one.




Violating Content Security Policy directive in environment Ember Cli

I have a built a Music Player Component with ember consuming the SoundCloud Api

Suddenly in Chrome i start getting this error notification in my console anytime i play a song in my application plus the songs does not play.

See the error

enter image description here

Report Only] Refused to connect to 'http://ift.tt/1XT3u3Y…fe493d321fb2a6a96186dcb97beab08f3cea5ad8b42d543c3edc7371f0eb5b2b00ba96395e' because it violates the following Content Security Policy directive: "connect-src 'self' data: cf-media.sndcdn.com ws://localhost:35729 ws://0.0.0.0:35729 http://ift.tt/1HbOW6Y".

It is complaining about the "connect-src 'self' data: cf-media.sndcdn.com ws://localhost:35729 ws://0.0.0.0:35729 http://ift.tt/1HbOW6Y".*"

This is because after bit of research i have modified in environment.js the content security policy like this

contentSecurityPolicy: {
  // 'connect-src': "'self' data: http://ift.tt/1XT3u40",
  'connect-src': "'self' data: cf-media.sndcdn.com",
},

Before my change the problem was the same and this was the console log error

enter image description here

So my question is, how can i give these permission in order to not violate the Content Security Policy directive for 'connect-src'? What other action have i to take now?

Again the problem is only in Chrome




What should I consider before I choose a framework to make a mobile web app?

I am planing to develop a single page app on IOS, but I have no idea about what should I do when choosing a framework for mobile developing. There are lots of frameworks to choose.




Ember model attributes in modals

This is my problem:

What I'm trying to do is when I click on a model's name, I get a modal window that shows all it's attributes, like so: enter image description here

However, when I click on another one, it doesn't work, no modals show up, like so: enter image description here

This is my index.hbs:

<div class="row" style="text-align:center;">
   {{#each model as |event|}} 

    <div class="col-xs-3 col-md-3">
        <div class="centerBlock">
            <a href="#" class="thumbnail" style="height:180px; width:171px;"></a>
        </div>
      <button type="button" class="btn btn-link" data-toggle="modal" data-target="#{{event.name}}">{{event.name}}</button>
    </div>

       <!-- Modal -->
  <div class="modal fade" id="{{event.name}}" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">

        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">{{event.name}}</h4>
        </div>

        <div class="modal-body">
          <p>{{event.location}}</p>
          <p>{{event.roomNumber}}</p>
          <p>{{event.eventDay}}</p>
          <p>{{event.eventTime}}</p>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>

      </div>

    </div>

  </div>
  <!-- End Modal-->
  {{/each}}
</div>

And this is my index.js:

import Ember from 'ember';

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

    }


});

I suppose that I'm doing my {{#each}} wrong, but I've spent about an hour on it and I can't figure it out.

Sorry this is such a dumb problem, and thanks for any direction!




samedi 27 février 2016

How to extract a "ComputedProperty" to it's real value?

I'm trying to implement amCharts into a project, and it looks like when I pass it the EmberData model as it's dataProvider, it can't understand the promises.

I've tried to fix this by creating a computed property in my controller that looks like:

dataProvider: computed('users', function () {
    return get(this, 'users')
        .map(function (user) {
            return {
                calls_out:    user.calls_out,
                calls_in:     user.calls_in,
            }
        });
}),

However, when I log this I get the following:

0: Object +
    calls_in: ComputedProperty
    calls_out: ComputedProperty
    __proto__: Object
1: Object
2: Object

which means the object that amCharts needs to work with is still not the raw data. Is there a way to extract the data out into numbers rather than a Promise or a ComputedProperty?

Thanks!




ember action 'Nothing handled the action' within block component

If I have component in block form:

//some-component.hbs
{{#some-component}}
    <button {{action "someAction"}}>test</button>
     <!-- assume you have multiple buttons here with multiple actions -->
{{/some-component}}

//some-component.js
Ember.Component.extend({
    actions: {
        someAction() {
            alert('NOT BEING CALLED');
        }
    }
});

using Ember > v2.0. The action is not being called. If I call it:

{{some-component}}

and put:

<button {{action "someAction"}}>test</button>

inside the some-component.hbs template. then it works. but this way has some drawbacks which I want to avoid.

I've looked at the docs and everywhere it doesn't seem to have this sort of case.




Workflow with ember-data and ajax api call

I have this code in routes/index.js:

model( ) { return 

Ember.RSVP.hash( { maps: ajax( { url: '*********************', type: 'get' } ).then( function( data ) { console.log( 'maps: ', data ); return data; } ) } ); }

which returns json data. Now I want to work with ember-data and a model, i have this code in models/map.js:

import DS from "ember-data"; export default DS.Model.extend( { gmap_lat_center: DS.attr( 'string' ), gmap_long_center: DS.attr( 'string' ), hotspots: DS.attr( 'array' ), id: DS.attr( 'string' ), image: DS.attr( 'array' ), image_highres: DS.attr( 'string' ), image_lowres: DS.attr( 'string' ), map_background: DS.attr( 'string' ), ne_lat: DS.attr( 'string' ), ne_long: DS.attr( 'string' ), order: DS.attr( 'string' ), sw_lat: DS.attr( 'string' ), sw_long: DS.attr( 'string' ), timestmap: DS.attr( 'string' ), title: DS.attr( 'string' ), track_geojson: DS.attr( 'string' ), type: DS.attr( 'string' ), zoom: DS.attr( 'string' ) } );

Now what is supposed to be the workflow with ajax and ember-data? Where do I need to put the ajax call and where do I store it in the models?




Problems retrieving data from controller using Ember.js

I am trying to learn ember following this course and I have the follwoing controller

import Ember from 'ember';

export default Ember.Controller.extend({
  title:'My Blog Post',
  body:'Body of the post',
  authors:['Author1', 'Author2', 'Author3'],
  comments:[
    {
      name:'name 1',
      comment:'comment 1'
    },
    {
      name:'name 2',
      comment:'comment 2'
    },
    {
      name:'name 3',
      comment:'comment 3'
    }
  ]
});

And Template:

<h1>{{title}}</h1>
<p>{{body}}</p>
<p>
  <strong>Authors:</strong>
  {{#each authors}}
    {{this}},
  {{/each}}
</p>
<h4>Comments</h4>
<ul>
{{#each comments as c}}
  <li><strong>{{name}}</strong> - {{comment}}</li>
{{/each}}
</ul>

And it has been generating this output:

My Blog Post

Body of the post

Authors: <my-app@controller:post::ember424>, <my-app@controller:post::ember424>, <my-app@controller:post::ember424>,

Comments

 -
 -
 -

I double check everything and it is identical to the demo I am seem, I also try to use {{each authors as author}} {{this.author}}, try to use {{c.name}}, also try {{this.name}}, {{this.c.name}}

Any ideas where I am going wrong?

Thanks in advance




Not able to reload the ember page app

I have an Instagram login in ember app.I am making the request from "http://example.com" and the Instagram is redirecting the access_token to the same Url "http://ift.tt/1XQYi0v".The Problem I am facing that the same URL is serving the feed of user If authenticated.How should I authenticate or do something after it gets redirected from Instagram with access_token.




EmberJS pushing new record to top of list

In my EmberJS application, I sort my records from the backend itself, in descending order of a property createdAt. But when I create a new record, it appears at the bottom of the list instead of the top, until I reload the page.

This answer seems to use a deprecated API and I'm unable to accomplish this functionality using computed properties.




vendredi 26 février 2016

Ember return length of a model created today

I am trying to do this: I have a model called 'trip', and inside trip, an attribute called 'createdToday', which returns the date when a trip is created. What I want is to return a list of trips that were made today.

Here is my trip model:

import DS from 'ember-data';

export default DS.Model.extend({
    driver: DS.belongsTo('driver', {
        async: true,
        inverse: 'trip'
    }),


    ..... etc .......


    createdAt: DS.attr('string', {
        defaultValue() {
            return new Date();
        }
    }),
    isBookedToday: function(trip) {
        var today = new Date().toDateString();
        return (today === trip.get('createdAt').toDateString);
    },
    getTripsToday: Ember.computed('trip.@each.createdAt', function() {
        var tripsToday = this.get('trip');
        return tripsToday.filterBy('isBookedToday', true).get('length');
    })

});

In my isBookedToday, I'm trying to see if an individual trip's created time is the same as todays time, and in getTripsToday, I am trying to loop through all the trips and filtering by isBookedToday.

And in my .hbs file, I'm saying: {{trips.getTripsToday}}, which won't render anything, so something's wrong.

I guess I am most confused at Ember's @each and exactly how it works.

Thanks for any feedback.




Advice on Ruby on Rails, Laravel, Angular and Ember js

I have a new application to build but the choice of frameworks to use has become my stumbling block.

I am very fluent in laravel and angularjs and built app with them. The last time i tried ruby on rails was four years back and i would like to go back to it. I tried ruby on rails 5 and it was awesome. Been doing ember-cli also lately and it seems promising.

I would like to have all four frameworks in my toolbox because i love all of them.

Now my confusion is do i work on this new projects with

  1. Laravel and angular since am already good at it.

  2. Ruby on rails and ember js since i want to try something new or master them.

  3. Laravel and emberjs. Bite it one at a time since am already good in laravel

  4. Ruby on rails and angularjs. As i said in point 3 bite it one at a time since am already good in angularjs

Please advice.

Since its going to be a big app should i take the risk or go with what i already know. Thank you.




Ember Date get Month, Year, and Day

I've searched around but I couldn't find any help.

I want to know if I can get the Day, Month, and Year, and maybe other attributes, from Ember's Date attribute.

For example, in one of my models, I have something like this:

createdAt: DS.attr('string', {
    defaultValue() {
        return new Date();
    }
})

which returns me this format: Tue Feb 23 2016 10:27:10 GMT-0800 (PST)

Is there a way which I can get the "Feb" portion from the whole Date?

I know in pure JS, you can do something like var today = new Date.getMonth(), but that doesn't work, of course, for Ember's date.

Thank you.




Debugging Ember JS -- Identifying line in code that causes an error

So I'm getting the following error:

Uncaught Error: Assertion Failed: The key provided to get must be a string, you passed undefined

Should be easy enough to fix, if there was any indication of the line in my code that causes that error.

Using the chrome console, I click on ember.debug.js:6254 next to the error, which just shows me the ember code that throws the error. I can expand the error, but I just get a bunch of functions that can't be clicked on and no indication where they come from.

Can someone please help me figure out how to identify the line in my Ember code that is causing the error.




Ember template helper get-value-with-key

Does Ember have any template helper "get-value-with-key" I found the below usage, but not sure what it does exactly ?

{{get-value-with-key item optionValuePath}}




Instagram authentication not working.Throwing error

I have Instagram login in my ember app.I am using Server-side (Explicit) Flow.I am making an ajax request to Instagram for user authentization for app.But I am receiving an error "Allow-origin-access-control" (cors).

My request

      var CLIENT_ID = "hasdgfasdfghsdfghsadgafsdgf";
      var CALLBACK_URL = "http://ift.tt/1Uodu5l";
      var AUTH_BASE = "http://ift.tt/1hv1BmR";
      var AUTH_URL = AUTH_BASE + "?client_id=" + CLIENT_ID + "&redirect_uri=" + CALLBACK_URL + "&response_type=code";
      raw({
        url:AUTH_URL,
        crossDomain: true,
      }).then(function(response){
      console.log(response)
      });

In the Instagram manage app.I have given the website's URL as http://example.com and redirect uri same as above.If I open the AUTH_URL (request url ) in another tab it works fine and gives access_token.But when I make the same request through my app it throws an error.

error

XMLHttpRequest cannot load http://ift.tt/1Uodu5n…http://ift.tt/1Q7viPh. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.




Trigger observer when new property added to Ember Object

I want to fire an observer that will set a value to a property when another Ember Object has a new property set. So far this is how I've got it:

  relationTotalCountObserver: Ember.observer('item.relationships.attachments', ->
  totalCount = @get 'item.relationships.attachments.totalCount'
  if totalCount isnt undefined
    @set 'relationTotalCount', totalCount
  ).on 'init'

The item does not have any totalCount property before, it will be added eventually using a merge patch and I need to detect that addition somehow.




Putting an order in the web app stack technology chaos

I am trying to understand things going on in the web app environment and I came across various technologies that I would like your input to set things into order.

So a web app has: 1) A front end 2) A back end 3) A database

Keep in mind that my main focus is simplicity and business users, i.e. not thousands and millions of users at the same time.

Let me start with the "simple".

A database is irrespective of the front end and as long as your back end is supporting it, right?

Top databases at the moment: MySQL, MongoDB, Oracle, PostgreSQL

(I ignore Microsoft products by the way)

Let's go to the Back ends. This is basically a programming language along with a framework sitting on a server and handling the comms between the front end and the database, correct? From what I saw so far the most popular ones are: Ruby on Rails, NodeJS, Django (Python) and Zend (PHP).

Another question on the back ends is that you can only have 1 framework for you backend per server or you can have Rails and Zend together?

Moving to the front now and the most complicated one. From what I understand everything is HTML5 (HTML+CSS+JS) but it's extended using various frameworks, correct? Several frameworks that I have found as pretty popular are AngularJS, ReactJS, EmberJS, JQueryUI and many more. Are all these frameworks interoperable? That is can you have more than one for your web app?

I also found a few hybrid frameworks such as Meteor and Ionic. From what I understand they provide the same codebase for a web or mobile app. Are these frameworks as good as they claim to be?

Thanks in advance!




How to add reveal.js in an ember app

I want to use reveal-js in my ember app, but everything I've tried goes in vein. There's an ember addon but my ember server doesn't run after installing it. I've tried installing the ember.js npm package and also the ember-js bower package. It installs properly, but Reveal.initialize() fails with an exception

Cannot read property 'classList' of null

in reveal.js at this line

dom.slides.classList.add( 'no-transition' );

Has anyone ever tried to create a reveal presentation in ember? Any pointers would be very helpful.




ember-cli 0.0.40 version installation

 npm install ember-cli@0.0.40

returns E404. I know that it is too old version, but i should work any way. Should I install anything else? (0.0.44 works fine) Any solution?

here is full output :

npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\ node_modules\npm\bin\npm-cli.js" "install" "ember-cli@0.0.40" npm ERR! node v4.3.1 npm ERR! npm v2.14.12 npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on http://ift.tt/1iluc3i s npm ERR! 404 npm ERR! 404 'expresss' is not in the npm registry. npm ERR! 404 You should bug the author to publish it (or use the name yourself!)

npm ERR! 404 It was specified as a dependency of 'ember-cli' npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request: npm ERR! C:\Windows\system32\npm-debug.log

here is npm version output:

{ npm: '2.14.12', ares: '1.10.1-DEV', http_parser: '2.5.2', icu: '56.1', modules: '46', node: '4.3.1', openssl: '1.0.2f', uv: '1.8.0', v8: '4.5.103.35', zlib: '1.2.8' }




EmberJS, how to monitoring pending AJAX requests

I would like to inform to the User when there is a pending request on going.

The first idea is to display a spinner when there is some pending request, but also would be a nice idea to have the total number of pending requests so I can get to the User a more accurate information.

Is there any place in Ember where I can find this information?, I was checking into the Models but this took me to a nightmare. Also I don't find any thing in the DS.Store.




jeudi 25 février 2016

embed object id is null after successful post request to backend

I'm building an ember app with a Rails API backend. These are two separate apps running on two separate servers. The problem I'm having is this:

A user can successfully fill out the form with a new album with new songs and new artists. It posts the the Rails API, create action of the album's controller. New album, songs and artists are successfully created and associated. Yet, the album record that gets sent back to Ember has songs and artists, all with ids of null.

Here is the payload that gets sent back to Ember on successful insertion of new album (with associated songs and artists) record into database:

{
  album: {
  id: 1,
  name: "Purpose (Deluxe)",
  image_url: "http://ift.tt/1MCiKyF",
  artist_ids: [
    23,
    14,
    1,
    57,
    27
   ],
  song_ids: [
    1,
    3,
    4,
  ]
 }
}

And here is the save action of my albums/new controller:

save(){
  let album = this.get('model');
  album.save().then((newAlbum)=>{
      this.transitionToRoute('albums.album', newAlbum);
  });

}

Note that I am using a callback function transition routes only when Ember receives the response from the Rails API.

Some background:

The app has three models: artists, albums and songs. An album has many songs and songs belong to an album. Songs have many artists and artists have many songs. Albums have many artists through songs.

API is up and running and serving data as expected. I'm not side loading associated data.

Similarly, songs serializer serves album_id and collection of artist_ids with a given song.

Here are my Rails serializers:

Album serializer:

class AlbumSerializer < ActiveModel::Serializer
  attributes :id, :name, :image_url, :artist_ids, :song_ids
end

Artist Serializer

class ArtistSerializer < ActiveModel::Serializer
  embed :ids, include: true
  attributes :id, :name
  has_many :albums
  has_many :songs
end

Song Serializer

class SongSerializer < ActiveModel::Serializer
   attributes :id, :name, :artist_ids, :album_id
end

I'm using async: true on my Ember model definitions. Here are my ember models:

Album Model:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  imageUrl: DS.attr('string'),
  songs: DS.hasMany('song', {asnyc: true}),
  artists: DS.hasMany('artist', { async: true })
});

Artist Model

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  songs: DS.hasMany('song', { async: true }),
  albums: DS.hasMany('album', { async: true })
});

Song Model

import DS from 'ember-data';
export default DS.Model.extend({
  name: DS.attr('string'),
  artists: DS.hasMany('artist', { async: true }),
  album: DS.belongsTo('album', {async: true})
});

I'm using Ember's embedded record mixin to serialize associated data back to Rails. I have a song serializer and an album serializer.

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
     artists: {serialize: 'records'},
     album: {serialize: 'record'}
  }
});

Here is my Album Serializer

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    songs: {serialize: 'records'}
  }
});

So, when album.save() is run, it hits Rails, creates and saves new album and associated songs and artists and that album data is correctly serialized and served back to Ember. But Ember perceives those associated songs and artists to have ids of null. Also, any records that have been seeded on the backend behave as expected in Ember--I can visit an album's show page and see a list of songs for example. But, if I manually visit localhost:4200/albums/<some album that was created via the form>, associated songs and artists don't show up.

Any help would be greatly appreciated! I'm really stuck on this.




How to display nested related model data in Ember

To preface this, I'm new to Ember and using Mirage to mock a JSON-API compliant backend, but I've hit a snag on what I think would be a common scenario. Ideally, I'm looking to create a single view that lists posts and the comments for each post underneath. The trouble comes when I want to display the author associated with each comment. So, I must clearly be doing something wrong here, since Ember knows how to fetch the direct associations for the Post model, but anything deeper than that is undefined.

In my route, I fetch all posts and that knows to then request the relationship data from the proper Mirage routes.

// app/routes/index.js

import Ember from 'ember';

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

This is the response that Ember receives from Mirage when requesting all posts.

{
  "data": [
    {
      "type": "posts",
      "id": "1",
      "attributes": {
        "title": "Vero quas non inventore eos vel rerum nesciunt nemo molestiae.",
        "body": "Eum minima beatae ullam nam id ut quia.\nPorro quidem blanditiis provident qui ex voluptas temporibus officia quos.\nDeleniti aut soluta placeat illo.\nId aut dolorem illo fugit corrupti commodi.\nPorro nesciunt enim debitis.\nMinima architecto velit corporis excepturi eos qui.",
      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "10"
          }
        },
        "comments": {
          "data": []
        }
      }
    },
    {
      "type": "posts",
      "id": "2",
      "attributes": {
        "title": "Id quae est omnis dolorum quaerat aut sed corrupti voluptatem.",
        "body": "Est ipsa voluptas quia quae nihil ipsum assumenda itaque nihil.\nTotam aut quia.\nRerum maxime cum distinctio harum dolorem dolores dicta.\nNesciunt id et minima velit omnis eius itaque ad.",

      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "1"
          }
        },
        "comments": {
          "data": []
        }
      }
    },
    {
      "type": "posts",
      "id": "3",
      "attributes": {
        "title": "Provident et eius est.",
        "body": "Neque autem deserunt.\nAb repellendus nemo et aut sunt veritatis facere asperiores soluta.\nEt placeat id dicta sint.\nHarum temporibus eos labore.",

      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "8"
          }
        },
        "comments": {
          "data": []
        }
      }
    },
    {
      "type": "posts",
      "id": "4",
      "attributes": {
        "title": "A similique explicabo itaque dolor vel possimus aut praesentium veritatis.",
        "body": "Inventore et ipsum ut porro.\nUt sed est unde illo nulla id doloribus accusamus voluptatum.\nTempora officiis ut enim porro et est qui.\nSit qui minima iste eaque cupiditate molestiae ut omnis magni.",
      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "4"
          }
        },
        "comments": {
          "data": []
        }
      }
    },
    {
      "type": "posts",
      "id": "5",
      "attributes": {
        "title": "Et in consequatur ut autem et.",
        "body": "Qui voluptatem harum aut amet possimus architecto eos commodi.\nNumquam cupiditate fugit.\nQuod consequatur minima aspernatur nobis qui eligendi qui corporis necessitatibus.\nIste velit perferendis non dolore ipsum perspiciatis quia.\nAut delectus et porro cupiditate laboriosam dolorem.\nEaque ipsa rerum ipsam placeat voluptatem enim.",

      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "1"
          }
        },
        "comments": {
          "data": [
            {
              "type": "comments",
              "id": "4"
            }
          ]
        }
      }
    },
    {
      "type": "posts",
      "id": "6",
      "attributes": {
        "title": "Exercitationem quo perferendis.",
        "body": "Dolor ut voluptates placeat ullam.\nOmnis aut et.\nIste est tenetur deleniti ea incidunt eos voluptas veniam iusto.",

      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "3"
          }
        },
        "comments": {
          "data": [
            {
              "type": "comments",
              "id": "1"
            },
            {
              "type": "comments",
              "id": "5"
            },
            {
              "type": "comments",
              "id": "9"
            }
          ]
        }
      }
    },
    {
      "type": "posts",
      "id": "7",
      "attributes": {
        "title": "Officia ea quod natus corrupti.",
        "body": "Et quia qui occaecati aspernatur voluptatem error in.\nDoloremque rerum sed autem minima quidem reiciendis.\nPossimus dolores voluptas voluptate rerum veniam dicta.\nNemo dolore perspiciatis harum dolorem soluta ab consectetur animi sed.",

      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "1"
          }
        },
        "comments": {
          "data": [
            {
              "type": "comments",
              "id": "3"
            }
          ]
        }
      }
    },
    {
      "type": "posts",
      "id": "8",
      "attributes": {
        "title": "Quia ea cum vel repudiandae.",
        "body": "Excepturi dolores sed modi est asperiores deleniti.\nTempore architecto recusandae nostrum culpa expedita iure voluptatibus accusantium nemo.\nQuia est voluptatum nulla earum culpa.",

      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "7"
          }
        },
        "comments": {
          "data": [
            {
              "type": "comments",
              "id": "2"
            },
            {
              "type": "comments",
              "id": "7"
            },
            {
              "type": "comments",
              "id": "8"
            }
          ]
        }
      }
    },
    {
      "type": "posts",
      "id": "9",
      "attributes": {
        "title": "Nam fugit in voluptatibus et.",
        "body": "Aut nihil atque tempore beatae voluptas.\nOptio voluptatum qui debitis omnis dolor maiores cumque.\nUt dolorem est magnam eveniet.\nMagni porro occaecati ex autem.\nPorro et alias beatae nemo laboriosam ut sint magnam quis.\nMollitia deserunt culpa non.",
      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "9"
          }
        },
        "comments": {
          "data": [
            {
              "type": "comments",
              "id": "10"
            }
          ]
        }
      }
    },
    {
      "type": "posts",
      "id": "10",
      "attributes": {
        "title": "Aut delectus nobis voluptate.",
        "body": "Alias impedit itaque at rerum enim.\nVoluptas itaque quaerat qui optio quo.\nNihil voluptatem quos nihil pariatur sapiente tempore necessitatibus quia et.\nSed consectetur modi dolorum sunt ex odit at.\nVoluptas numquam totam dolores ipsam rerum.\nEt hic eum sunt et.",
      },
      "relationships": {
        "author": {
          "data": {
            "type": "users",
            "id": "1"
          }
        },
        "comments": {
          "data": [
            {
              "type": "comments",
              "id": "6"
            }
          ]
        }
      }
    }
  ]
}

After getting all posts and the top-level relation models, Ember doesn't go any deeper so I'm left with an undefined comment.author in my template. Is there some way I can tell Ember to fetch the nested models that I need or am I going about this all wrong?




How to connect an EmberJS front-end with an NodeJS Express API?

I'm working on a MEEN-stack (MySQL, EmberJS, Express, and NodeJS) project. I have never worked with Ember at all. My only front-end experience is jQuery.

The project is separated into folders, with the front-end (Ember) in one folder and the Express API in another. Front-end will handling loading in web-pages while sending requests to Express API for database requests / authentication / more.

I am currently able to connect the two servers via an explicit URL with jQuery's Ajax method in a webpage's static javascript file (along with allowing CORS and modifying the Ember environment file in app/config).

My confusion is that there is definitely a more elegant solution for connecting the two, but I'm lost on how to go about it.

From looking at tutorials, I have attempted adding an application.js file in the Ember Front-End app/adapters folder:

import DS from "ember-data";

export default DS.RESTAdapter.extend({
    host: 'http://localhost:9029',
    namespace: 'api'
});

But I don't have the knowledge to fully implement it or test it. What am I missing? How do I take advantage of the adapter file?




Ember masonry not working correctly

I have used ember Masonry addon in my app.Everything is working fine.But when the grid has more photos and the internet is slow it load all the photo one above another till all the photos are downloaded.Once all the photo is downloaded then it form the grid.This should not happen and its not looking good.It should load all the photo for once before showing any photo.Once all are downloaded it should show.Mean while I can show some loading icon

index.hbs

{{#masonry-grid gutter=10 items=usrPhotos as |photo|}}

I don't how to fix it.Please add sample code to answer.Thanks in advance.




Ember - How to pass a property from Routes file to a Handlebar template with 401 returned

The situation is I have a login screen which works except when there is a failed login (401 not authorized). Basically it is very simple right now, the handlebar (template) is trying to access a property from the route to determine if the call to the back end (rails) failed.

{{#if loginFailed}}
  <div class="alert">Invalid username or password.</div>
{{/if}}

The Route file looks something like this, I have omitted any sensitive code or working code that is not needed:

import Ember from 'ember';
import ajax from 'ic-ajax';

export default Ember.Route.extend({

loginFailed: false,
isProcessing: false,

beforeModel: function(){
    //some stuff 
},

actions: {
login: function() {
    this.setProperties({
      loginFailed: false,
      isProcessing: true
    });
    var _this = this;

    ajax({
        url: //something,
        type: 'post',
        crossDomain: true,
        data: //some stuff,
  }).then(
            function(result) {
                //logging in logic all works
            },
            function(error){
                if (error.jqXHR.status === 401)
                {

                    _this.set('isProcessing', false);
                    _this.set("loginFailed", true);
                }
            }
        );


  },
},

reset: function() {
  this.set('isProcessing', false);
  this.controller.set('password', '');
  this.controller.set('username', '');
}
});

I've done some debugging and it does indeed hit the error block for the ajax promise however it just seems to crap out. I believe it craps out because it's 401, limited resources have led me to this conclusion.

You can see that loginFailed is the property I am trying to change and when 401 error happens, and on the template this is the property I am trying to access.

I am very new to Ember just working on it for little over a week now so any help would be amazing.

Here are the versions I am using when running ember -v on my project:

version: 1.13.8
node: 0.12.7
npm: 2.13.4
os: win32 x64




Set multiple models in render function, with the possibility to observe, reboot and save each separately

i have a problem with Ember.RSVP.hash(). Models does not render in templates, observes not work with promise model, and promise does not function reload().

import Ember from 'ember';

export default Ember.Route.extend({     
  achievementMode: true,
  params:[],
  model(params){
    this.set('params', params);
    return params;
  },
  renderTemplate(controller, model){
    var firstController = this.controllerFor('clients/'+model.first),
        secondController = this.controllerFor('clients/'+model.second),
        firstModel = this.getModel(model.first,model),
        secondModel = this.getModel(model.second,model);

    this.render('clients/'+model.first,{
      outlet:'first',
      controller:firstController,
      model: Ember.RSVP.hash(firstModel)
    });
    this.render('clients/'+model.second,{
      outlet:'second',
      controller:secondController,
      model: Ember.RSVP.hash(secondModel)
    });
  },
  setupController: function(controller, model) {
    this._super(controller, model);
    this.controllerFor('clients').set('firstBlock', model.first);
    this.controllerFor('clients').set('secondBlock', model.second);
  },
  getModel(modelName, params){
    var model = {};
    if(modelName === 'profile'){
      model ['client'] = this.store.findRecord('user', params.user_id, { reload: true }),
      model ['achievements'] = this.store.query('achievement', {'mode':this.get('achievementMode'),'user':params.user_id})
    }
    model ['params'] = params;
    return model;
  }
});

Have a rest adapter, and after request observes('params') not work, and params not render in template.

{{#each achievements as |achievement|}}
test
{{/each}}

and promise not have a function reload(). ember 2.2 any thoughts? how to implement plans?




Ember tests/Mirage not finding DOM elements

I'm trying to do some basic acceptance tests in Ember, using Mirage. I'm using only fixtures at this point to populate the test environment, just to find my feet. When I run ember in the test environment (i.e., with -e test), I can see my app is populating with expected data. And the DOM has some buttons, etc. All is well.

However, when I run a test to visit a page and click a button, the test is telling me it can't find the button. In other words, running -e test and checking localhost shows the app seems to be fine. But then checking localhost/tests has a test failing saying it can't find a button that is definitely there in the -e test screen.

I've confirmed that the button exists in the -e test environment, using both inspector and just issuing a basic jquery select at the console line.

So I assume there's something wrong in the setup or somewhere in a configuration?

In particular:

module('Acceptance | basic tests', {
  beforeEach: function() {
    this.application = startApp();
  },

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

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

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

test('visiting /basic', function(assert) {
  visit('/orders');
  click('top-row-orders-button'); //button.top-row-orders-button fails too
  andThen(function() {
    assert.equal(currentURL(), '/orders');
  });
});

The first test (just visiting the url) passes. The second test is where it says it can't find the button. And again, when I serve -e test, and enter this at the console: $('.top-row-orders-button') it returns the button in question.

Happy to provide any more info anyone needs. Would appreciate any help. I've been banging my head on this for a few days now with no luck.




passing parameters in find of dynamic model

I want to pass two (or more) arguments to this.store.find() ; I have app.router.js like

Router.map(function() 
{ 
      this.route('posts'); 
      this.route('post', { path: '/post/:post_id' }); 
});

and

dynamic route's model

model(params) 
{ 
 return this.store.findRecord('photo', params.photo_id); 
}

this will go to /photo/photo_id

now I tried to pass couple of arguments then it was giving error: no model is defined for some_photo_it (say id) I tried this: model(params) { return this.store.findRecord('photo', params.photo_id,{param1:0, param2:25}); }

please answer.




Ember - How to get route model inside route action

Is it possible to access route model inside route action?

I am passing multiple objects inside a route model to template,

 model: function() {
    return {
        employeeList : this.store.findAll("employee"),
        employee : Ember.Object.create()
    }
}

From the route action I am want to modify the route model.employee. I tried the following, but I am not getting the object.

actions:{
    editAction : function(id) {
        var emp = this.get("model");
        console.log(emp.employee);

    }
}

Can anyone give a solution to get and modify model object(employee)?




Ember.js display table from three models

I have three simple models in Ember.js 2.3:

// app/models/symbol.js
export default DS.Model.extend({
    name: DS.attr()
});

// app/models/group.js
export default DS.Model.extend({
    name: DS.attr()
});

// app/models/group-symbol.js
export default DS.Model.extend({    
    group: DS.belongsTo('group'),
    symbol: DS.belongsTo('symbol'),
    value: DS.attr()
});

Now I want to display a table in which symbols are in rows, groups are columns and inside each cell there is respective group-symbol.value.

My route defines the model as follows:

model() {
    return {
        groups: this.store.peekAll('group'),
        symbols: this.store.peekAll('symbol')
    };
}

And I can display empty table with this template

<table>
<tr>
    {{#each model.groups as |g|}}<th>{{g.name}}</th>{{/each}}
</tr>
{{#each model.symbols as |s|}}
<tr>
    {{#each model.groups as |g|}}<td></td>
</tr>
{{/each}}
</table>

Please advise, how can I obtain specific group-symbol model instance to display its value between <td> and </td>




Ember.js JSONApi, serializers, nested models

How could I serialize just created model with just created related models? Example:

import DS from 'ember-data';

//model "list"
export default DS.Model.extend( {
  contacts: DS.hasMany('contact')
});

//model "contact"
export default DS.Model.extend( {
  numbers: DS.hasMany('phone-number'),
  list: DS.belongsTo('list')
});

//model "phone-number"
export default DS.Model.extend( {
  numbers: DS.belongsTo('contact')
});

When a user creates new list with phone numbers I'd like to get whole information threw the list.serialize() method and next parse it on server side (rails), what is the right way to do that?

Ember 2.3 Ember-data 2.3 JsonApi




Ember build error: Unexpected token

I'm trying to get to grips with Ember 2.3.0 but I'm having trouble with the following piece of code:

route.js:

import Ember from 'ember';

export default Ember.Route.extend({

actions: {
    login: function() {
        this.store.query('user', {
            name: this.controller.get('name')
        }).then((users) => {
            if(users.get('length') === 1 {
                var user = users.objectAt(0);
                this.controllerFor('application').set('user', user);
                this.transitionTo('notebooks');
            } else {
                console.log('unexpected query result');
            }
        });
     }
   }
});

I get the following build error:

File: ember-note/login/route.js
ember-note/login/route.js: Unexpected token (9:33)
SyntaxError: ember-note/login/route.js: Unexpected token (9:33)
   7 |              name: this.controller.get('name')
   8 |          }).then((users) => {
>  9 |              if(users.get('length') === 1 {
     |                      ^

I'm sure an Ember pro will get this straight away. Cheers




Assertion Failed: Using `{{view}}` has been removed in Ember 2.0

I have upgrade ember version in my project and got some exceptions :

Assertion Failed: Using {{view}} or any path based on it ('path/c-text.hbs' @ L1:C0) has been removed in Ember 2.0

how I should change

{{view}}

command?




Use and bind {{input}} inside a component

Sorry if this is a silly question. I am in the middle of the steepest part of the Ember learning curve and trying to get a simple app going as a learning tool for myself, and my google-fu is failing me in understanding how to do this;

I have a component that is basically a list of model objects with some filtering options. The filter option relevant to this discussion is a free-text search. I want to have an {{input}} that is is bound to some value that affects the result list whenever it is updated.

{{input type=text value=filterString}}

In my poor understanding of Ember, I would have bound the value of the input to a string property, and have my filteredMatches computed property depend on that. However, if I define that property as such:

filteredMatches: Ember.computed.filter('matches', 'filterString', function(match, index, array) {

I get an error in the console log:

Uncaught TypeError: callback.call is not a function

If I remove the reference to 'filterString', it works as expected, but of course the filtering is not updated when I type something into the input.

So with my limited knowledge of Ember, I am stuck with this; Is the input actually binding to filterString on the controller, not the component? I do not use explicit controllers as I understand they will be going away. If that is the case, how can I have a computed property in my component depend on a controller property?

If that is not the case (i.e. controllers are not involved), how can I bind the input to a component property and react to value changes accordingly?

ember -v
version: 2.3.0-beta.2
node: 5.6.0
npm: 2.14.10
os: win32 x64

Thanks for any help, and again, sorry if this question is stupid!




Emberjs/Chrome/FFox: numeric Access-Control-Request-Headers in preflight

I'm developing an Emberjs front-end that should use a django rest framework backend. I'm just starting out and working on the authentication using JWT/Javascript Web Tokens.

This is what I've done:

  • On the backend (currently django's development server for obvious reasons) I'm allowing all origins (since ember-cli runs at localhost:4200 and django at :8000). I.e. the origin is being accepted.
  • The serverTokenEndpoint is correctly set in Emberjs
  • I can add manually the numeric headers on django to be accepted, but I don't want to unless I know why I should allow them.

The problem I see now is the following:

  • On chrome, the preflight OPTIONS request to the backend includes a request to allow headers 0 to 9.
  • On Firefox, the preflight OPTIONS request to the backend includes a request to allow headers 0 to 4.

These headers are not allowed by the backend and I could not find a source for this request nor what their meaning should/could be.

Again, this is part of the OPTIONS request from Firefox:

Access-Control-Request-Headers: 0,1,2,3,4,content-type

And this from Chrome:

Access-Control-Request-Headers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, accept, content-type

My question: Why are these headers in the request? Where do they come from and what do they mean? And, ideally, how can I get rid of them?




Ember Validations: Custom Validator Setup

I'm using Ember 2.3 and DockYard's ember-validations version "2.0.0-alpha.4". I'm using POD structure on my project.

No matter with predefined validations but I'm facing with injection problems while using custom validators.

As mentioned in documentation, I've placed my validators at my-app/app/validators/ directory. But they are not loaded. If I manually inject them by using a factory, they work. But ember-validations couldn't load them automatically.

How can I make ember-validations to load my custom validators?




mercredi 24 février 2016

The loader.js addon is missing

I have cloned my ember project, use following commands

npm install
bower install

ember build

and got this message

DEPRECATION: Brocfile.js has been deprecated in favor of ember-cli-build.js. Ple ase see the transition guide: http://ift.tt/1Qzyksy /TRANSITION.md#user-content-brocfile-transition. The loader.js addon is missing from your project, please add it to package.json.

I have searched about this exception and tried to install loader.js manually, but after this another got another exception :

can't find module rsvp

It seems there is some global problem in my project, I can't determine what is it.

And about deprecation - brocfile.js, I haven't changed it, should I?




Registry returned 404 for GET on http://ift.tt/1QfMLpR - ember install

I can't run my ember project any more, I have just cloned it from repository and works fine, with old build, but if I run 'ember build' command again get exceptions, generally it can't find some modules. I used combinations of commands

npm install
bower install
ember buld

but it seems npm install doens't do anything, now I try to run following command:

ember install -- NPM & bower dependencies

and get the 404 exception:

Registry returned 404 for GET on http://ift.tt/1QfMLpR - ember install

Any idea?




In Ember 2, I am unable to get the event object when binding on=keypress event to {{input}}

In Ember 2, I am trying to do probably the most simple thing. When I bind an event to an input element, I expect the event argument to be passed to my action handler but I am unable to get that. Simply I require to check for keyCode 13 which is for "enter" key on keyboard.

 {{input type=text
           value=model.filters.query
           placeholder="Search by title"
           action="search" onEvent="key-press"
 }}

My Function Handler is:

search(newValue){
 // I am only getting newValue and not the event object
}




Ember loading substate and images/css animation rendering

I have a route in my Ember App which returns a promise and it takes some time to do that, so I decided to create a loading substate and it works fine except for the images and the spin loader (css animation) present in the loading substate template:

  • Static Images take a while to render especially on mobile and IE where sometimes they don't show at all
  • The CSS animation spin loader gets stuck while transitioning to the actual route and again on mobile sometimes it doesn't show at all.

What could be a solution to show a loading substate static template that is very smooth and that, once the model has been loaded, it disappears without any lag/freeze of my css animation or slow rendering of my images?

We are talking about 5 very small images...

Thanks guys




stripe jquery function to an ember property?

Having problems converting stripe Jquery function into a ember property. Have try multiple was but looks like I am missing something. Thanks

         var stripeResponseHandler = function(status, response) {
             var $form = $('#contact-form');
             var self = this;
             if (response) {
                 self.set('stripeToken',response);
                console.log(self.get('stripeToken'));
                 // Show the errors on the form
                 $form.find('.payment-errors').text(response.error.message);
                 $form.find('input').prop('disabled', false);
             } else {
                 // token contains id, last4, and card type
                 var token = response.id;
                 // Insert the token into the form so it gets submitted to the server
                 $form.append($('<input type="hidden" name="stripeToken" />').val(token));
                 // and re-submit
                 $form.get(0).submit();
             }
         };

         $('#contact-form').submit(function(e) {
             var $form = $(this);
             // Disable the submit button to prevent repeated clicks
             $form.find('input').prop('disabled', true);
             Stripe.card.createToken($form, stripeResponseHandler);
         });




Ember/ Liquid - Each statement multi-dimentional array

I'm having some difficulty with the ember #each statement. I would like to print the [0]th and [1]th position value from a multi-dimensional array in the below HTML code. i.e., I want to print the value Product X,Y,Z and GROUP A,B,C in a separate HTML code block. this.get(0) isn't working.

var uiTags = [
   ['**Product X**','GROUPA', '350'],
   ['**Product Y**','GROUPB', '150'],
   ['**Product Z**','GROUPC', '575']
];

HTML Code:

<ul class="list-group list-group-menu">
  {% raw %}{{#each uiTags}}{% endraw %}

   <!-- Print product name start (This block should print the product name) -->
    <li class="list-group-item"><a href="#">          
      <div class="checkbox checkbox-primary">
        <input type="checkbox" checked id="map-filter-{% raw %}{{ @index }}{% endraw %}" value="{% raw %}{{ this }}{% endraw %}"/>
        <label for="map-filter-{% raw %}{{ @index }}{% endraw %}">{% raw %}{{ this }}{% endraw %}</label>
      </div></a>
    </li>
   <!-- Print product name end-->

   <!-- Print group name start (This block should print the group name) -->
    <li class="list-group-item"><a href="#">          
      <div class="checkbox checkbox-primary">
        <input type="checkbox" checked id="map-filter-{% raw %}{{ @index }}{% endraw %}" value="{% raw %}{{ this }}{% endraw %}"/>
        <label for="map-filter-{% raw %}{{ @index }}{% endraw %}">{% raw %}{{ this }}{% endraw %}</label>
      </div></a>
    </li>
   <!-- Print group name end-->


  {% raw %}{{/each}}{% endraw %}
</ul>




Emberjs Sort records

I want to sort the records that I'm getting by date in descending order.

//model definition
export default DS.Model.extend({
   name: DS.attr('string'),
   mydate: DS.attr('number')
}

I tried return this.store.findAll('mymodel').sortBy('mydate') but no success. I'm using version 2.3.0.




Accessing the store from model function in routes

I want to be able to set my model dynamically depending on a record in the store - mainly because I want to control whether or not a form submission should be a POST or PUT.

export default Ember.Route.extend({
  model: function() {
    let bankAccount = this.store.get('bankAccount').objectAt(0);

    if (bankAccount.is_connected) {
      bankAccount = this.store.createRecord('bankAccount', { account_label: 'new' });
    }

    return Ember.RSVP.hash({
      appState: this.get('appStates').currentAppState(),
      user: this.store.findAll('user').thenGetFirst(),
      bankAccount: bankAccount,
    });
  },
});

The issue is that let bankAccount = this.store.get('bankAccount').objectAt(0); return null when I refresh the page.

However, if I run App.store.get('bankAccount').objectAt(0) in my browser console, it returns the correct record.

What am I doing incorrectly?




What JS framework to use with JavaEE?

Just thinking about to learn some JavaScript framework (ember/backbone preferred) along with JavaEE while creating a real time chat application (something like git mattermost, but much more easier: http://ift.tt/1Q1qPxs)

I have decided to use JavaEE-7 with it's websockets, the Java already has JSF technology built in, will JSF work well with framework such as ember or backbone? Or is there more suitable JS framework to use for creating app like this?




Send a DELETE request to serverTokenEndpoint using ember-simple-auth

I can set a custom endpoint for ember-simple-auth to obtain tokens. It sends an HTTP POST request to the custom endpoint.

export default OAuth2PasswordGrant.extend({
    serverTokenEndpoint:'/tokens'
});

I'd like to add a custom invalidate method that sends a DELETE to /tokens as well.

import Ember from 'ember';

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

    actions: {
        logout() {  
            this.get('session').invalidate();

            // DELETE to /tokens
        }
    }
});

Is this possible using an ember-simple-auth method? I can't see it working with ember data because there is no token model created in the first place. Or can this only be done with Ember.$.ajax or something like it?




QWebEngineView and Ember.js ES6

Before I begin, I know almost nothing about JavaScript. I'm just a lowly C++ developer being tasked to do something that should be easy.

In essence, I need to configure a QWebEngineView to show a webpage that is being developed for us by an outside UI vendor. Whenever I load the page in my QWebEngineView, I get a ton of errors in the JavaScript Console (http://ift.tt/1WJg18R). However, if I go to the page directly through Chrome, everything looks exactly like it should (http://ift.tt/1p55tGw).

I have checked that other webpages can load correctly within my view, but, for whatever reason, not the page that is being developed for us. I have also scoured the Qt documentation for references to any JavaScripts limitations and have also found none.

For reference, they are using Ember.js with JavaScript version ES6 and I am using the latest version 5.5.1 of the Qt framework, but have also tried 5.3.2. I have also tried using the now deprecated QtWebKit instead of QtWebEngine hoping it was simply a design oversight in the new widget.

Any help either solving this issue or coming up with a strategy to figure out how to debug this would be amazing!

Thanks!




Prevent Javascript actions on ember compoents

I want to prevent Javascript actions on my ember component like hover, click, double click, focus, etc..

Simple way is to define this actions for the component and do event.preventDefault() and return false;

Is there any other way by which I can achieve the same ? I tried using CSS for this pointer-events : none which is fine for UI experience. But when I go to console, I see that I can still invoke click actions on my component div. So, is there any way by which I can prevent these actions all at once maybe during init of the component ?




in Ember.js 2.3, how do I compile a hasMany async call into one call in ember instead of several?

I'm upgrading to ember-cli and ember 2.3. Say I have a model called User and a model called Post , and a user ...

posts: DS.hasMany('post', {async:true})

Now, this works the way I expect it to, lazily loading data and not loading posts unless it is required in either the .js or the template. So when I do

{{#each user.posts as |post|}}
  {{post.title}}
{{/each}}

I get each post to render its title without a problem. However, in my server logs, I see this:

GET /posts/2
GET /posts/7
GET /posts/13

where the numbers are the post ids. This is to be expected, as when I return a user instance from the server, I return a list of the ids as the parameter 'posts'. So the user instance has:

...
'posts': '2,7,13'
...

in its data.

Now my question is this: way back when, when I used ember-data 1.0 (pre ember-cli and pre ember 1.13), I remember this call being made to the database instead for the same use case:

GET /posts?ids=2&7&13

or something along that line. I can't remember the exact format, but then, I could access the list of ids on the server side using this line of code:

var ids = req.query.ids.toString();

which gave me a comma separated list of ids (in string format). I would then convert this into the sql statement

SELECT * from posts where id in (2,7,13)

This SQL call was interpreted as a manyArray, I think, on the Ember Side and easily behaved as you would expect an Ember Array would.

How can I get this to happen again? I am quite confident that I am missing something and that I don't have to 'hack' ember-data; I would very much like to compress these calls into one instead of having an individual call to the database for each 'post'.

I should also mention that I am not looking to make {async:false} for these calls.




How to secure my Firebase App build with EmberFire

I scratch my head for that Firebase security works as i want. My app is build with Ember and so with EmberFire. So structure is determine by EmberFire.

My database structure is as follow :

conversations : {
    $conversation_id {
        messages {
            //message data
        }
        users {
            $user_id1 :true
            $user_id2 :true
        }
    }
}

What i want is that only users that are part of a conversation can see and write message in this conversation. I tried this rule without success :

"conversations" : {
    ".indexOn" : "notify",
    ".read" : "root.child('users').hasChild(auth.uid)", 
    ".write": "root.child('users').hasChild(auth.uid)"
}

It seems that auth.uid can't be passed to hasChild. I also tried the following, because my conversation id is the join of users id that participate to the conversation :

"conversations" : {
   ".indexOn" : "notify",
   "$conversation" : {
       ".read" : "$conversation.beginsWith(auth.uid) || $conversation.endsWith(auth.uid)", 
       ".write": "$conversation.beginsWith(auth.uid) || $conversation.endsWith(auth.uid)"
   }
}

With this rule, no one can see conversation because the "conversations" node does not have .read rule. But if i adds ".read : true" to the "conversations" node, due to top-bottom rules in Firebase, all users can see all conversations.

Edit : The second rule has the same problem that the first. beginsWith() expects a string argument. And auth.uid can't be used Any idea to solve my problem?




Using callbacks in a non-async-context

I have a service with a method called "getGmapsDistance()". Here im using the google maps api to get the distance between an origin an an destination.

export default Ember.Service.extend({

  getShortestDistanceInMeters: function(location) {

    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix({
      ...
    }, this.callback); //<<<<<< !!!

  },

  callback: function(response, status) {
      ....
  }
});

In my controller if got a array with locations and now I want to iterate over it and want check each element if the distance is <= the max destination.

locationsNearby: Ember.computed('locations', function() {
     //...
     var filteredResult = [];

      locations.forEach(function(locat) {
        if (this.get('distanceService').getShortestDistanceInMeters(locat) <= maxDistance) {
          filteredResult.pushObject(locat);
        }
      });

      return filteredResult;
})

Unfortunately the GMaps API for distance calculation uses a callback so the request is async.

How can I solve that problem?




mardi 23 février 2016

Ember unable to copy image to correct path

I am developing a Ember project as addon and am trying to add loading image icon to my project.

My CSS class looks like

.loader {
    background: url("assets/images/loading.gif");
}

Now I am not sure where to place the image. I place the image in "public/assets/images" and it is not getting reflected on page.

In my dist directory, there are 3 folders

- assets/images
- addon-iuse/assets/images
- my-app/assets/images

I see the image only if I "manually" copy it under assets/images (1st path above)

But I do not know how I can get it there, since from the build process, it is copying under my-app/assets/images (3rd path above)

Just to add (not sure if this might be the reason), in my ember-cli-build.js, I have

var addoniuseassets = new Funnel('node_modules/addon-iuse/public', {
       srcDir: '/assets',
       destDir: '/assets'
  });




Ember Data: Prevent encodeURIComponent on Query Params

I am working with an API which requires the use of reserved words, against the recommendation of the specification. I need to override the default behaviour of encoding the URL.

Here are my query params:

export default Ember.Mixin.create({
    keywords: null,
    genre: Ember.computed.alias("applicationController.genre"),
    qualities: ["720p", "1080p", "3d"],
    quality: "720p,1080p,3d",
    queryParams: ["keywords", "page", "perPage", "genre", "sort", "quality"],
    perPage: 50,
    page: 1,
    sort: "asc"
});

Currently, the request goes out with , characters replaced with %2c. How can I keep my query param value for quality?




How can I prevent an action on a parent component from being called when I click on a child component?

I have the following bit of template in a project I'm working on:

<div class="item row" {{action "expandItem"}}>
  {{input type="checkbox" checked=isChecked}}
  {{item.name}}
</div>

The trouble I'm running into is that clicking the checkbox does not change its state. It does, however, fire the expandItem action. I'd like the behavior to be that clicking on the checkbox changes isChecked but clicking anywhere else in the div fires expandItem. How can I accomplish this?




Why does the CP in the controller return undefined?

In setupController (in a route). I have:

setupController(controller, model) {
  this._super(...arguments);

  let params = this.paramsFor(this.routeName);

  controller.set('model', model);

  this.store.query('category', { filter: { 'shop-id': params.shop_id } }).then(categories => {
    console.log(categories); // Class {query: Object, store: Class, manager: Class, isLoaded: true, meta: ember$data$lib$system$empty$object$$EmptyObject…}
    controller.set('categories', categories);
  });
}

In a controller, I have:

availableTags: Ember.computed('categories.[]', {
  get() {
    console.log(this.get('categories')); //returns undefined
  }
})

console.log in the controller returns undefined. Ember inspector Network tab shows some results. What am I missing?




Ember: Adding observers dynamically to a dynamic form

i am new to ember. I have created a dynamic form in which i have to add fields as specified by the data from the server. So in the same template the same form may have different components for different requests. What i need to do next is add observers to these fields. I have written a mixin to do this but its not working. The console doesn't show any errors either. Any help will be appreciated.

//mixin code
import Ember from 'ember';

export default Ember.Mixin.create({
        methodsToDefine: [],
        init: function() {
                this._super();
                var MTD = this.get('methodsToDefine');
                MTD.forEach(function(config) {
                        // add an observer for checkerName - a change should call methodToCall
                        console.log("inside mixin");
                        Ember.addObserver(this, config, this, "changeObserved");
                }, this);
        },

        /*
        willDestroy: function() {
                this._super();
                var MTD = this.get('methodsToDefine');
                // since we are good citizens, we remove the observers when the object is destroyed
                MTD.forEach(function(config) {
                        Ember.removeObserver(this, config, this, "changeObserved");
                }, this);
        }
        */
});



//from th mixin i am simply calling this function from the controller
changeObserved: function() {
      alert("hi");
   }


//from the controller i am also setting an array of field values that have to be //observerd as the array methodsToDefine
               var temp = [];
               temp=self.get('methodsToDefine');
               temp.push(wizardStepFields.wizardStepFieldData.value);
               self.set('methodsToDefine',temp);
               
 {{#bs-form formLayout="horizontal" model=this action="submit"}} 
                    {{#each wizardData.wizardSteps as |wizardSteps|}}
                    <section>
                        <h4>{{wizardSteps.stepLabel}}</h4> 
                        {{#each wizardSteps.wizardStepFieldSets as |wizardStepFieldSets|}}
                        <article>
                            <h5>{{wizardStepFieldSets.fieldSetLabel}}</h5> 
                            {{#each wizardStepFieldSets.wizardStepFields as |wizardStepFields|}} 
                                    {{#component "bs-form-element" controlType=wizardStepFields.fieldType label=wizardStepFields.fieldLabel placeholder=wizardStepFields.fieldLabel name=wizardStepFields.fieldLabel value=wizardStepFields.wizardStepFieldData.value defaultText=wizardStepFields.defaultValue type=wizardStepFields.fieldType property=wizardStepFields.fieldLabel}} 
                                    {{/component}}
                            {{/each}}
                        </article>
                        {{/each}}
                    </section>
                    {{/each}}
                    <footer>
                        <button id="form-wizard-submit" class="btn btn-default" type="submit">Submit</button>
                    </footer>
                {{/bs-form}}