dimanche 31 juillet 2016

Initialize cloudinary_js v2 in Ember JS app

I'm trying to upload images to cloudinary from an EmberJS app (v2.6), following the post of Beerlington where it uses cloudinary_js (now with new API v2) and in order to install it :

npm install blueimp-file-upload --save
npm install cloudinary-jquery-file-upload --save

But when I'm trying to initialize the cloudinary the library is not recognized.

#app/initializers/cloudinary.js
export default {
  name: 'cloudinary',
  initialize: function(/* container, app */) {
    jQuery.cloudinary.config({
      cloud_name: ENV.CLOUDINARY_NAME
    });
  }
};

#console
TypeError: Cannot read property 'config' of undefined




Ember Component Template Extend

I want to extend ember component which is easily possible with extends. But I want to also extend the component template and add some extra html around it. Is there a way to do this ?

So basically I want to create a new component by adding some extra wrapping around current component and without losing its exiting functionality.

// component.js
import SuperComponent from 'components/super-component'
export default SuperComponent.extends({
  // some operations
});

// template.hbs
<div id="extra-div"> 
  
</div>

I am using older version of ember 1.10.
I tried referencing super component template as a partial and passing context. But seems way to hacky way to get around.




ember pick-a-date how to pull value?

There is a pick-a-date add-on for Ember found here.



How would I pass a saved date value to the tag? The below (value=date) does not seem to work?



Or what if I wanted to change the value from 'date' to something different... for example dob... so it would 'mimic' this






How Can I Filter an Array from Another Array in Ember?

Goal: I have two arrays: One of vehicles scheduled for a day, and one of all vehicles. If a driver wants to use a vehicle on Monday, my program should check all driver's schedules for Monday and see what vehicles are being used and display a list of available vehicles BEFORE the user can select one (the select dropdown should never show anything that isn't available)

I can't seem to get Ember to filter the data. It's all or nothing. I can't get the filtered data. Are you willing to take a look?

Github Repository: [http://ift.tt/2aofTNh]

routes/schedules/view.js

  model(params) {
    return this.store.findRecord('schedule', params.schedule_id);
  },

  setupController(controller, model) {
    controller.set('schedule', model);

    var self = this;
    this.store.findAll('schedule').then(function(schedules) {
      controller.set('schedules', schedules);
      var scheduledVehicles = schedules.filter(function(day) {
        if (day.get('day_of_week') === model.get('day_of_week') && day.get('vehicle.id')) {
          return self.store.findRecord('vehicle', day.get('vehicle.id'));
        }
      });
      var vehicles = self.store.findAll('vehicle');
      controller.set('vehicles', vehicles.filter(function(vehicle) {
        return scheduledVehicles.indexOf(vehicle) === -1;
      }));
    });
  },




Ember: How to access another model data in a dynamic segment template

In a dynamic segment template, how do you display data from a model using the route ?

so for example I have those two routes with phone_id as dynamic segment

Router.map(function() {
  this.route('phones');
  this.route('phone', {path: 'phones/:phone_id'});
  this.route('numbers');
});

in phones/:phone_id template, I am trying to show all the numbers model. so in phone.js route, I tried to return the number model and output it but it showed nothing.

import Ember from 'ember';

export default Ember.Route.extend({

  numbers(){
    return this.get("store").findAll('number')
  }

});

I tried it also with the params.phone_id as argument but it did not work. (no error was shown also).

the template phone.hbs looks like

<h5> Device Id: </h5>






funny thing is model.device_id returns the correct one even though I did not even set it to return that in phone.js route. But the each loop for numbers which I did implement something for does not return anything.

Is there a workaround to return number model data in phone.hbs dynamic segment template ?




How to obtain an Django Foreign Key object in ember.js?

I have a model called "Summary" and a foreign key object called "TrainStatistics"

class Summary(models.Model):
    train_statistics = models.ForeignKey(
    'TrainStatistics',
    on_delete=models.CASCADE,
    blank=True,
    null=True,
)

Whenever I try to access it as follows in the ember.js code, I notice that the console.log only gets the id (primary key) of TrainStatistics, rather than the whole object.

statistic_trainStatisticsArray.forEach(function(train_statistic) {
    var trainStatistic_typeStatisticsArray = [];
    trainStatistic_typeStatisticsArray.push(train_statistic.type_statistics)

    var keys = Object.keys(train_statistic);
    console.log("keys for train_statistic: " + keys);

Could someone lead me towards the right direction for this problem?




Logging in and adding a note in Ember

In order to learned how to use ember, I am creating an app where someone can log in, write and read notes. I have already figured out how to save a username and password via model but how can I get them to log in and add a note that corresponds to the users account?




Ember.js : Undefined data

I try to build a simple API Express server who return JSON data to my Ember.js App.

Here is my server :

var express = require('express');
var mongoose = require('mongoose');

var app = express();

mongoose.connect('mongodb://localhost/dataTest2');

var noteSchema = new mongoose.Schema({
    _id         : String,
    title       : String,
    content : String,
});

var NoteModel = mongoose.model('note',noteSchema);


app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    next();
});

app.get('/api/notes', (req,res) => {
    NoteModel.find({},(err,data) => {
        if(err) {
            res.send({error:err});
        }
        else {
            res.setHeader('Content-Type', 'application/json');
            res.json({data:data});
        }
    });
});

app.listen('4500');

On the Ember side, this is my model :

import DS from 'ember-data';

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

The adapter :

import DS from 'ember-data';

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

The serializer :

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
    primaryKey: '_id',
});

This is what my server respond when I use this command line : curl http://localhost:4500/api/notes :

{"data":[{"_id":"579e2f68dfd5b298c9a3d732","title":"Eyeris","content":"Quis enim labore","type":"note"},
{"_id":"579e2f68dfd5b298c9a3d733","title":"Mazuda","content":"Voluptate cupidatat irure ,"type":"note"},
{etc.}]}

And finally, this is what Ember respond when I try to get this model : Ember's respond

Why do I get all these 'undefined', and how to solve this problem ?




Error while creating new ember application using ember-cli

I installed ember-cli tools, When i tried to create a new application using ember new book-app i get the following error

installing app
  ......
  create tests/unit/.gitkeep
  create vendor/.gitkeep
Successfully initialized git.
Installed packages for tooling via npm.
Error creating new application. Removing generated directory `./book-app`
Package ember not found
Error: Package ember not found
    at createError (/usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/util/createError.js:4:15)
    at /usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/core/resolverFactory.js:206:23
    at _fulfilled (/usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/node_modules/q/q.js:834:54)
    at self.promiseDispatch.done (/usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/node_modules/q/q.js:863:30)
    at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/node_modules/q/q.js:796:13)
    at /usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/node_modules/q/q.js:604:44
    at runSingle (/usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/node_modules/q/q.js:137:13)
    at flush (/usr/local/lib/node_modules/ember-cli/node_modules/bower/lib/node_modules/q/q.js:125:13)
    at nextTickCallbackWith0Args (node.js:419:9)
    at process._tickCallback (node.js:348:13)

I am not sure what the problem is. I am using ember-cli 2.7.0




samedi 30 juillet 2016

Route without page reload

If I'm on a page in my Ember app, and edit the URL manually or use a bookmark that identifies another route within the same app, by default the page gets reloaded, losing any transient state it had, rather than just transitioning as it would have if I'd followed an Ember-controlled link within the app. Is there a built-in feature of Ember that's well integrated into its routing features which can prevent that and just transition instead?

Details:

With Ember's default routing, the URL itself changes rather than just the fragment identifier ("hash"). E.g., in the Quick Start example, if you're on http://server/scientists and want to look at the list of programmers instead, you go to http://server/programmers.

If you do that by clicking a link handled by Ember, that works within the loaded page just fine (I'm assuming Ember uses the History API under the covers to replace state without page reload). No page reload is caused.

But if you're on http://server/scientists and click a bookmark to take you to http://server/programmers (or edit the URL manually), it reloads the page, losing any transient state the page contained.

In contrast, in an app that uses fragment identifiers for routing (like Gmail), the equivalent change of (say) http://server/#scientists to http://server/#programmers does not cause page reload, even if you manually edit the address bar or use a bookmark. (Of course; it's just a change to the fragment identifier, not the actual URL.)

Is there built-in handling in Ember that's well integrated into its routing features that can make it handle that use case without reloading? Either by using a fragment identifier instead of changing the URL, or with some History API feature? (Although I can't think of a History API feature that could do it.)




vendredi 29 juillet 2016

Deleting items from a store does not give the current state in all the routes

According to emberjs documentation, store is a single source of truth. Deleting items from a store in a specific route should reflect all other routes that talks to store.

For eg: Route 1: Employee
Route 2: Manager
Store: person

Outcome:
The data is cleared after adding few items and clicking delete all. However i am seeing an error Attempted to handle event pushedData on while in state"

Refreshing the browser the error goes away, both ember data and pouch (in memory db) has no items. why deleting the store does not refresh all the routes that used the store (like getAll in model hook).

Here is the source: http://ift.tt/2avsOOr

Hosted here : http://ift.tt/2aiZeZc




redirect to root URL when refreshing with locationType=hash in Ember

Hi I set my locationType in config/environment.js to hash.

Now it won't produce a 404 when I refresh on a non-index route. However, when I refresh, it always directs me to root URL.

Is that the intended design? Thanks in advance.




Ember - Bind a form to new ember object

I have a model A which has many model B. In my show route I return an object of model A like

model: function(params) {
    return this.get('store').find('model-A', params.model_A_id);
}

I am trying to show a form inside an ember-modal-dialog in the above show route's template to create/save an object of model B. Everytime the user presses a button, the modal would show up with the form and on clicking Create the form data would be passed to createModelB() action in my route.

Eveytime the user presses the button to show modal, I need a way to create an empty object of model B which will hold the form data and pass it to my action. If the user closes the modal without creating an object, I need to delete the empty object.

Where/How would I create this empty object for holding the form data?

In short,

<form >
  
</form>

How do I create an emptyModelBObject everytime user presses a button?




Hex characters not rendering after upgrading from Ember 1.7 to Ember/CLI 2.6

Does anyone have any insight into what might be different in Ember/Ember CLI, compared to a Rails delivered global app, to not render hex characters correctly?

I have/had an Ember 1.7 app that I build a Math Editor in. I render very simple buttons with hex chars like ∛ (<div>&#x221b;</div>) but in the new CLI app it gets escaped.

Im just curious if there is a setting or something that I missing in the way CLI handles templates that may be causing this issue.




ember data two records with the same id

i'm new to ember, what i want to is to translate this database to ember models, but the problem is that the ember model don't allow two record with the same id :

    +-------------+---------------+---------------
| routeId(fk) | stationId(fk) | StationOrder |
+-------------+---------------+---------------
|     1       |       1       |       3      |
+-------------+---------------+---------------
|     1       |       3       |       1      |
+-------------+---------------+---------------
|     1       |       4       |       2      |
+-------------+---------------+---------------
|     2       |       1       |       1      |
+-------------+---------------+---------------
|     2       |       4       |       2      |
+-------------+---------------+---------------




How do you select a default radio button in Ember?

<label for="customerFacingYes">Yes</label>

I am trying to set the radio button as selected if a variable, "report.customerFacing", is true or false. Is there something I could write in javascript to set it as selected?

Thank you




FOSRest OPTIONS request return 405 Method Not Allowed

I wrote a REST services with Symfony FOSRestBundle. It work fine with GET request.

Now, I am trying to access with Ember « models" and I get an error message. Indeed, Ember try to access with OPTIONS request (preflight) and It failed with « Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response ». I tried to access the REST service with Postman and I got this error : with OPTIONS http://ift.tt/2ajnz3k : "405 Method Not Allowed »

but it works fine if I call OPTIONS http://myUrl.local/

I use apache under El Capitan (IMac). I tried to append these lines to /private/etc/apache2/extra/httpd-default.conf : Header add Access-Control-Allow-Origin "*" Header add Access-Control-Allow-Headers "origin, content-type" Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

I tried to append these lines in directive in my VirtualHost. Same results in both case.

Is the problem in Symfony or FOSrestBundle.

I need help to understand what is happening. How I can resolve my problem.




Check if the component action gets called in integration test

I have the following simple component:

export default Ember.Component.extend({
  actions:{
    someAction(){
      //...
    }
  }
});

What should I do(in an integration test) if I want to check if this action gets called in the corresponding hbs file?




Ember Data for Non Standard Rest Calls

Very new to ember sorry if any dumbness, I was trying to create a custom adapter and serializer in ember, by extending DS.RESTadapter,and Rest serializer , I was successful in getting the response and massage the data to suit the model needs, but I was not able to get the model values in the template using model property, however i got a way to get the values , request you to kindly help me with the right way

Model

App.Weather = DS.Model.extend({
    name   : DS.attr('string'),
    temperature  : DS.attr('string'),
    humidity : DS.attr('string'),
    description : DS.attr('string'),
});

Adapter

App.ApplicationAdapter = DS.RESTAdapter.extend({

    buildURL: function(item) {
        return "http://website/weather?q=" + item['q']+ "&appid="+item['appid'];
    },

    findQuery: function(store, type, query) {
        return this.ajax(this.buildURL(query), 'GET');
    }
});

Serializer

App.ApplicationSerializer = DS.RESTSerializer.extend({

    extractArray: function(store, type, payload) {
        var weathers = [{
            id: 1 // Id hard coded
        }];


        weathers[0]["name"]=payload["name"];
        weathers[0]["temperature"]=payload["main"]["temp"];
        weathers[0]["humidity"]=payload["main"]["humidity"];
        weathers[0]["description"]=payload["weather"][0]["description"];
        weathers[0]["type"]=payload["weather"][0]["main"];

        payload = { weathers: weathers };

        return this._super(store, type, payload);
    }
});

Route

App.WeatherIndexRoute = Ember.Route.extend({
    model: function(params) { 
        //debugger;
       return this.store.find('weather',{q:"London", `enter code here`appid:"b552aef423b1cf586b62d1ab1d4ef216"});

    },
    renderTemplate: function() {
        this.render('default');
    },
    setupController: function(controller, model) {

        **controller.set('model', model.content[0]);**
    }
})

As Above I am getting all the values under model.Content Array.

Not understanding y i would have to do model.content instead of just model. and why would it nest itself this way.

I am using a older version of ember ember-1.1.2.js




Hello World in EmberJs Error

I am writing first program in EmberJs as "Hello World" printing, but getting errors. Can someone help me out?

HTML

<html>
<head>
    <script src="http://ift.tt/21nXWii"></script>
    <script src="http://ift.tt/2almqJ2"></script>
    <script src="http://ift.tt/2a8Wn4u"></script>
    <script>
      App = Ember.Application.create();
      App.Router.map(function() {
        this.resource('index', { path: '/' }, function() {});
        this.resource('hi', { path: '/hi' }, function() {});
      });
    </script>
    <script type="text/x-handlebars" data-template-name='index'>
      <p>index!</p>
      <p>hi</p>
    </script>
    <script type="text/x-handlebars" data-template-name='hi'>
      hello world!
    </script>
</head>
<body>
</body>
</html> 

ERROR

enter image description here




jeudi 28 juillet 2016

Ember Data; Custom Adapter with hasMany relationship

I have following models

// models/user.js
export default Model.extend({
  name: attr(),
  contacts: hasMany('contact')
});

// models/contact.js
export default Model.extend({
  name: attr(),
  phoneNumber: attr(),
  user: belongsTo('user')
});

Unfortunately, I'm working with highly non-standard API layer that has something like following signatures

endpoint?method=getUsers 
  -> returns list of users

endpoint?method=getContacts&args="{user_id=1}" 
  -> returns list of contacts for user with id=1. (args would be url encoded)

basically I have to write a lot of custom adapters. I wrote an adapter for user and was able to get the list of users.

// adapters/user.js
export default Adapter.extend({
  findAll() {
    return // call getUsers and return the result here
  }
}

But I can't figure out how to get the contacts for the users. I can get all the users by doing following.

// in some route
model() {
  return this.get('store').findAll('user');
}

But I cannot figure out to fetch all the contacts for the users I tried following:

// in some route
model() {
  return this.get('store').findAll('user').then(users => {
    users.forEach(user => {
      user.get('contacts');
    }
  }
}

user.get('contacts') just returns an empty record.

What's the way I can the contacts of the user? I wrote a custom adapter for contact but Ember doesn't call it either.




Ember computed property or observer within a service

I have a service, and declare a property in the service

bucket: []

Later in the service, I add something to bucket.

I'm trying to set up in this same service an Ember computed property or observer to listen/respond to changes in bucket.

Something like:

bucketListener: Ember.computed('bucket', function() {
   //do stuff in response to something being added to or removed from the bucket
}

But I can't get this to work. I've tried a lot of different permutations,using Ember.computed and Ember.observer, but I can never get bucketListener to fire.

I have checks in place and am sure that bucket is getting added to as expected or removed from as expected, but bucketListener still isn't getting called into.

Is there some trick to doing this within a service? Or am I just bungling something more basic?




Example for Model-dependant state ember concept using cache

Below is my route,

this.route('posts',{path: 'posts/:PostId/:PageIndex/:PageSize'});

For the postId=1 user is creating some filter stuff and navigates to postId=2 and comes back to postId=1 then user should be able to view created filters.
Typically, I would like to persist some controller sticky properties to each route user visits. how to do that ?.




Attempting to register an unknown factory in accepence test

I have a acceptance test that is failing to load an initializer during the beforeEach() application creation. Similar post here:“Attempting to register an unknown factory” in model test

Error: Error output

tests/acceptance/home/index-test.js

import { test } from 'qunit';
import moduleForAcceptance from 'app_name/tests/helpers/module-for-acceptance';

moduleForAcceptance('Acceptance | home/index');

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

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

initializers/pendo.js

export function initialize(application) {

    window.pendo_options = {
        apiKey: 'fake api key value',
        usePendoAgentAPI: true
    };

    application.register('pendo:main', window.pendo, {
        instantiate: false
    });
    application.inject('route:home', 'pendo', 'pendo:main');
    application.inject('route:home/network', 'pendo', 'pendo:main');
}

export default {
    name: 'pendo',
    initialize: initialize
};




Ember.js error handling

Server returned error while sending request through ember route(say cricket) model hook.Then I moved to another route(say football) where there was no problem .Again I transitioned back to cricket , this time ember is not sending request to server rather previous error object is thrown from store.How to handle this?




Undefined route error in ember js for transition to same route

In EmberJs am in a route say xyz.abc(#/xyz/abc). There is a tab in this page which points to the same route i.e.

Tab Name

Clicking on this link I get the below error:

**

There is no route named undefined at Object.handlersFor

**

Why an error for that? This happens when we do transitionTo or replaceWith to the current-route, this is needed while doing this.refresh() in application.




What to do with atypical actions in REST?

Let's say that I'm creating a user. I would

POST http://ift.tt/1k2htjI

That user record gets created an email goes out and then I want to use the same API later to do a complete registration for that user. Registration includes, marking their email validated. Creating a blank account for them and a plethora of other setup kind of things. Let's say all that could be put in one controller. Which of these three would be RESTful still? Or acceptable?

A) REGISTER http://ift.tt/1BBzUWQ
B) POST http://ift.tt/2afjfot
C) POST http://ift.tt/2atZN48
D) POST http://ift.tt/2afiUCq

I've been doing a lot of looking into this and haven't been able to find a guiding source yet.




How to convert a path to its matching route name in Ember

Let's say that I have a path like /posts. Is there a module within Ember that I can use to plug in that path and get back routing data?

The ultimate goal is to receive the path and transition to the route that matches the path.

It seems like this should be possible because Ember itself needs to do this when it's reading in the URL.




ember js relationship property

my problem is that i have two models : stations and lines,

  • stations is just a simple model containing name, addess....
  • lines is a model containing a relationship to stations, so line record must contain a list to stations, but what i want to do is to assosiate a number to each station so that i can know the first station, then the second. its easly done with a database table containing a 3 field, one for the line_id one for the stations and one for the station order



EmberJS comments for JSDoc documentation

Here I have an emberJS controller as an example. How to comment it properly to generate documentation using JSDOC?

import Ember from 'ember';

/**
 * ?
 */
export default Ember.Controller.extend({
  queryParams: ['param1', 'param2'],

  /**
   * ?
   */
  param1: '',

  /**
   * ?
   */
  param2: 10,

  /**
  *
  */
  testFunc1(param) {

  },

  /** 
   *
   */
  actions: {
    /**
     * ?
     */
    testFunc2(id) {

    },

    /**
     *  ?
     */
    testFunc3() {
      /**
       * ?
       */
      function testFunc4() {
      }

    }

  }
});

I have interest to know the best practices for emberJS code documentation, so at the end I can get proper doco with complete hirerchy.




Update belongsTo relationship via native select element

I have been trying to incorporate details of Brenna O'Brien's Ember Conf 2016 talk <select>ing Good Ember Patterns into a project and it is working for simple attributes (in the example below names is an array of strings and model.name is an attr( "string" )):

<select onchange=>
  
    <option value= selected=></option>
  
</select>

However, when this is applied to a belongsTo relationship and an array of models:

Controller:

import Ember from 'ember';

export default Ember.Controller.extend({
  titles: null,
  init(){
    this.set( "titles", this.store.peekAll( "title" ) );
  }
});

Template:

<select onchange=>
  
    <option value= selected=>
      
    </option>
  
</select>

This fails; the relationship value is modified but it is not set to a valid title. From some analysis, it appears that the title model is stringified either when it is being handled by HTMLBars or when it is set as the option.value and this is not (cannot?) being converted back when the relationship is set.

I have currently solved it (Ember-Twiddle) by adding an action to the controller:

actions: {
  title( id ){
    this.set( 'model.title', this.store.peekRecord( "title", id ) );
  }
}

and modifying the template to call this:

<select onchange=>
  
    <option value= selected=>
      
    </option>
  
</select>

However, I then need to create a function for each relationship I want to update in this way.

Is there a way to directly set a belongsTo relationship from the template without calling an intermediate function or resorting to add-ons? (If not then is there a DRY method of solving this?)




How building ember addons without ember-cli?

How building ember addons without ember-cli? My project building with grunt.




mercredi 27 juillet 2016

EmberJS many to many model association not being queried

"ember-cli": "0.2.7" "ember": "1.12.0", "ember-data": "1.0.0-beta.18"

I have defined a many to many relationship between my users and teams. Also, I have a relationship from my accounts to my teams (this is a one to many).

// user model js
teams: hasMany('team', {async: true})

// team model js
users: hasMany('user', { async: true }),
account: belongsTo('account', { async: true })

// account model js
teams: hasMany('team', { async: true })

I have a pod for showing an account and its associated teams. This works well but the problem I have is not being able to get my associated users of every team in my teams. It simply does not do anything at all.

// app / pods / teams / index / route.js
export default AuthenticationRoute.extend({
  access: ['admin', 'instructor'],
  model: function() {
    return this.store.find('account', this.auth.get('currentUser.accountId'));
  }
});

// app / pods / teams / index / controller.js
export default Ember.Controller.extend({

});

// snippet from app / pods / teams / index / templabe.hbs

     <tr>
         <td width="25%"></td>
         <td width="20%"></td>
         <td width="15%"></td>
         <td width="40%"></td>    
   </tr>


So the team.users.length are always returning 0 and it does not do a query at all like I am experiencing with teams on account (model.teams).

It has been working previously but after refactorization it has changed and I simply cannot figure out my problem.

Looking forward to your answers and help!




Emberjs is not returning data

Im trying to make a search from my component when the customer select an option. But my component its not loading the data when I use filters on it but without filters it work... This is my code.

My component country-list.js

import Ember from 'ember';

export default Ember.Component.extend({
  store: Ember.inject.service(), 
  iso3: null,
  valuesIso: null,
  actions: {
    countryIso() { 
      this.set("iso3", this.$("#whohow option:selected").val());
      const filcode = this.$("#whohow option:selected").val();
      this.set("valuesIso", this.get('store').findAll('country').then((iso) => {
          return iso.get('ccode') === filcode;
      }));  
    }
  }
});

My index.hbs calling my component

 

my component handlebars country-list.hbs

<select name="whohow" id="whohow" class="form-control" onChange=>
    
        <option value=''></option>
    
</select>




delete multiple records on EmberJS using

I would like to have an action that prints all the selected check-boxes on my table to the console.

in my controller I have

removedSelected: function() { let selected = this.filterBy('isSelected', true); console.log(selected); }

in my template file I have

I have setup my controller to filter all the records that are "isSelected" in the table by using input helper on ember.

I am getting an error on the console which states this.filterBy is not a function

Do i need to setup an array to handle this first?

Below is more of the code for a better picture.

Thanks!

// templates/warranty/index.hbs

<div class="container">
<h4>List</h4>
<div class="row">
    <div class="col-sm-3">
        <div class="control-group">
            New Claim
            <button class="btn btn-primary btn-sm" >Select</button>
            <button class="btn btn-danger btn-sm">Delete Selected</button>
        </div>
    </div>
<div class="container">
    <table class="table table-striped table-hover ">
        <thead>
            <tr>
                <th>Select</th>
                <th>Action</th>
                <th>Claim ID</th>
                <th>Claim Status</th>
                <th>Serial Number</th>
                <th>Issue Description</th>
            </tr>
        </thead>
        <tbody>
            
                <tr>
                    
                    <td>Edit<button class="btn btn-danger btn-xs" >Delete</button></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            
        </tbody>
    </table> 
</div>
</div>

// app/controllers/warranty/index.js

import Ember from 'ember';
export default Ember.Controller.extend({

actions: {
    toggleMultiple() {
        this.toggleProperty('canDeleteMultiple');
    },

    removedSelected: function() {
        let selected = this.filterBy('isSelected', true);
        console.log(selected);
    }
}
});




Ember mirage server is not defined in tests

I am trying to integrate ember-cli-mirage fixtures into some tests. I followed the documentation here: ember fixtures

Problem: The server is not defined. error message: ReferenceError: server is not defined

model-test.js:

import { moduleForModel, test } from 'ember-qunit';

moduleForModel('network', 'Unit | Model | network', {
  needs: []
});

test('it exists', function(assert) {
  server.loadFixtures('networks'); //no defined

andThen(function() {
   let net1 = networks.first();
});
  assert.ok(true);
});

I have also verified that the config is set to true.

ENV['ember-cli-mirage'] = {
        enabled: true
    }




Unit Test for custom validations is giving error

I'm doing some unit tests on Ember-Cli but I'm getting an error. I'm using ember-cp-validations and created a custom validation. After creating the custom validator and running the test this is the error I got: (Error: No model was found for 'userlog'), but I have that model. I can't find what I'm missing here.

Here is my model userlog.js with the validations:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
    username: [ 
        validator('presence', true),
        validator('format', { type: 'email' }),
        validator('corporate-email', { showSuggestions: true})
    ],
  password: [
    validator('presence', true),
    validator('length', {
      min: 6,
      max: 40
    })
  ]
});

export default Model.extend(Validations, {
  username: attr('string'),
  password: attr('string')
});

This is my corporate-email.js validator

import Ember from 'ember';
import BaseValidator from 'ember-cp-validations/validators/base';


const CorporateEmail = BaseValidator.extend({

// To interact with the store within the validator, the service has to be injected.
  store: Ember.inject.service(),
  validate(value) {

    return this.get('store').query('userlog',{username: value}).then(result=>{

      if (result.match("yahoo") || result.match("gmail") || result.match("hotmail")){
        return false;
      } else {
        return true;
      }
    });

  }

});

CorporateEmail.reopenClass({
  /**
   * Define attribute specific dependent keys for your validator
   *
   * @param {String}  attribute   The attribute being evaluated
   * @param {Unknown} options     Options passed into your validator
   * @return {Array}
   */
  getDependentsFor(/* attribute, options */) {
    return [];
  }
});

export default CorporateEmail;

This is my corporate-email-test.js

import { moduleFor, test } from 'ember-qunit';


moduleFor('validator:corporate-email', 'Unit | Validator | corporate-email', {
    needs: ['validator:messages']
});

test('it works', function(assert) {
    var validator =  this.subject();
    assert.ok(validator);
});

test('username email is not corporate', function(assert) {
    let validator =  this.subject();
    let done = assert.async();

    validator.validate('name@yahoo.com').then((message) => {
      assert.equal(message, false);
      done();
    });

});

What could be the problem?.Where can I find more information about unit testing(I read the ember-cli documentation already).

Thanks for your time




Ember.js - Remove Only One instance of Object with removeObject

Explanation

I have a very simple calorie tracking app that uses the Nutritionix API to search for food items based on the user's input. The results are added to a results array, which is then displayed to the user. When a user clicks the "Add" button next to one of these items, the calories are added to a counter, and the food itself is added to a todaysFood array (using Ember's pushObject). This is then used to display which food the user has consumed today in a separate table.

When a user clicks the remove button next to one of the todaysFood items, it triggers an action, removeItem, and passes the index of the item clicked to removeItem. This index is used inside of Ember's removeObject to remove the item from the todaysFood array, and thus update the view (remove that item from the list and its calories from the counter).

Problem

When more than one of the same item are added to todaysFood, clicking remove on just one of those items removes ALL of the instances from todaysFood, and the view. This makes sense to me now, because of the docs' example:

var cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
cities.removeObject('Chicago');  // ['Berlin', 'Lima']
cities.removeObject('Lima');     // ['Berlin']
cities.removeObject('Tokyo')     // ['Berlin']

However, it also only removes the calories of ONE item, not all instances.

So, the question is: How do I remove only ONE instance of that item when remove is clicked? I.e., if two tacos are added, and I click remove on one, I only want that ONE to be removed (from the list and the calories).

Here is my removeItem action:

removeItem(index) {
        var self = this;

        // Store property paths for easy access
        let todaysPath = this.get('healthData').todaysFood;
        let caloriesPath = 'healthData.calories';

        this.set(caloriesPath, this.get(caloriesPath) - Math.round(todaysPath[index].fields.nf_calories));

        todaysPath.removeObject(todaysPath[index]);

    }

Disclaimer

I'm aware that I may not be handling this correctly at all. I'm open to any suggestions to make this better. Thanks!




Why doesn't ember cli generate app bridge for hbs file when generating component from addon?

When I run ember g component foo-bar in an Ember Addon project (let's say addon-project), it generates following:

// addon-project/addon/components/foo-bar.js
import Ember from 'ember';
import layout from '../templates/components/foo-bar';

export default Ember.Component.extend({
  layout
}

// addon-project/addon/templates/components/foo-bar.hbs


// addon-project/app/components/foo-bar.js
export { default } from 'addon-project/components/foo-bar';

I noticed that it does not generate addon-project/app/templates/components/foo-bar.js to export the component template but explicitly link the template using layout.

Why not generate addon-project/app/templates/components/foo-bar.js? Is there a reason for this behavior?

Also why is layout imported using relative path instead of absolute path (i.e. import layout from 'addon-project/templates/components/foo-bar?




What is Utilities (utility function & utility files) in ember dev?

I am new to ember please explain, What is Utilities (utility function & utility files) in ember dev?




Partially render a screen in Ember.js when some data doesn't load

I have an Ember route with a model that loads data from a few different places, using Ember.RSVP.hash. Each of these results in a call to a different API route in the backend:

export default Ember.Route.extend(AuthenticatedRouteMixin, {
    model() {
        return Ember.RSVP.hash({
            profile: this.store.queryRecord('profile', {}),
            subscriptions: this.store.findAll('subscription'),
            packages: this.store.findAll('package'),
        });
    },
});

The problem I'm having is that when any of the data calls throws an error, the entire template fails to load. What I would like to do instead is display as much data as is available even in case of an error, with the portions that couldn't be loaded displayed as an empty model of the appropriate type (with some additional error information). However, I don't seem to be able to do this. I tried adding an error handler to the route, but from the error handler there doesn't seem to be any way to continue the transition despite the error.




Error :While rendering the RSolr::HashWithResponse from rails controller + ember

hi all i am bit new with ember, i am getting this error

Error: Assertion Failed: Encountered a resource object with an undefined type (resolved resource using ui@serializer:application:) at new Error (native)

while rendering my rsolar responce.

Can any one guide us in which format we should render.

ember model:

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


ember controller:


var resu = this.get('store').findAll('search')

data which i have to render in rails controller is like this :

 {"responseHeader"=>{"status"=>0, "QTime"=>0, "params"=>{"q"=>"*:*", "wt"=>"ruby"}},
 "response"=>
  {"numFound"=>6,
   "start"=>0,
   "docs"=>
    [ 
     {"id"=>"1",
      "title_s"=>"java se",
      "title_txt"=>["java se"],
      "company_name_s"=>"cts",
      "company_name_txt"=>["cts"],
      "job_description_s"=>"it",
      "job_description_txt"=>["it"],
      "category_name_s"=>"it",
      "industry_s"=>"it",
      "created_at_s"=>"10-05-16",
      "job_type_s"=>"permenant",
      "city_s"=>"delhi",
      "state_s"=>"delhi",
      "salary_type_s"=>"monthly",
      "salary_s"=>"100000",
      "status_b"=>true,
      "_version_"=>1540288621613940736
     }
    ]
  }
}

please help me out.

thanks in advance




With ember-rapid-forms. how can I store the password securely?

With ember-rapid-forms, one typically uses a model for handling the various input parameters in the form.

However, if the input type is password, then it will be part of the model and the user could retrieve it in plaintext. Rather unfortunate with auto-complete and possible reuse of previous passwords.

How can I avoid that with ember-rapid-forms?




Implementing rest authentication in ember UI with express backend

I am pretty new to nodejs. What i need to know is what is the right way to implement authentication in ember UI and express rest api. Express api runs on a subdomain for the application. Here is the code that i have for authentication

router
    .post('/', function(req, res) {
        response = {}
        if (req.body.username == "") {
            response.status = "error";
            response.message = "Username field cannot be empty";
            res.statusCode = 400;
            return res.json(response);
        };
        if (req.body.password == "") {
            response.status = "error";
            response.message = "Password field cannot be empty";
            res.statusCode = 400;
            return res.json(response);
        };
        const db = req.db;
        const users = db.get('users');
        users.find({
            username: req.body.username
        }, {}, function(e, docs) {
            if (docs.length != 0) {
                response.status = "error";
                response.message = "Same username already exists";
                res.statusCode = 409;
                res.json(response);
            } else {
                bcrypt.hash(req.body.password, 5, function(err, bcryptedPassword) {
                    users.insert({
                        username: req.body.username,
                        password: bcryptedPassword,
                        admin: false
                    });
                    res.statusCode = 200;
                    res.send();
                });
            }

        });
    })
    .post('/authenticate', function(req, res) {
        response = {}
        if (req.body.username == "") {
            response.status = "error";
            response.message = "Username field cannot be empty";
            res.statusCode = 400;
            return res.json(response);
        };
        if (req.body.password == "") {
            response.status = "error";
            response.message = "Password field cannot be empty";
            res.statusCode = 400;
            return res.json(response);
        };
        const db = req.db;
        const users = db.get('users');
        users.find({
            username: req.body.username
        }, {}, function(e, docs) {
            if (docs.length == 1) {
                bcrypt.compare(req.body.password, docs[0].password, function(err, doesMatch) {
                    if (doesMatch) {
                        response.status = "success";
                        res.statusCode = 200;
                        var token = jwt.sign(docs[0], "test key", {
                            // expiresInMinutes: 1440 // expires in 24 hours
                        });
                        response.token = token;
                        res.json(response);
                    } else {
                        response.status = "error";
                        response.message = "Please check your username and password";
                        res.statusCode = 401;
                        res.json(response);
                    }
                });
            } else {
                response.status = "error";
                response.message = "Username not found";
                res.statusCode = 404;
                res.json(response);
            }

        });
    });

Now the question is in two parts. First how can i implement a middleware kind of thing that will open authentication modal wherever the user needs to be signed up.

Secondly i am pretty sure that i am going wrong on the express side of server and if anyone can point me to a node module that provides restfull authentication, that would be much appreciated.




mardi 26 juillet 2016

Ember Data Firebase rules confusion

I'm getting started with my first Ember/Firebase application and having trouble finding documentation that goes beyond public data.

My goal is to have an application where signed in users can create and view their own data. I see that Firebase suggests this rule for such a situation:

{ "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }

But I can't find out any information about how this would work on the Ember end. For example, assuming I have an "entry" model that I am saving:

save(model) { model.save().then( () => { this.transitionToRoute('index'); }, error => { console.error(`error: ${error}`); }) },

Not sure if I need to be storing a uid in the model?

And then if I want the user to get a listing of their own entries:

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

This produces the following error: ember.debug.js:30610 Error while processing route: index permission_denied at /entries: Client doesn't have permission to access the desired data. Error: permission_denied at /entries: Client doesn't have permission to access the desired data.

At this point I'm not sure what I should be doing –– do I need to build a custom URL or add a namespace in my firebase adapter to add a users/xxx prefix? Or etc?

Cannot find any documentation/tutorials/walkthroughs that cover anything beyond public read/write data.

Any advice appreciated.




How to use jquery datatables in ember cli project

I'm working on an ember project where I'm using jQuery plugin data-tables. I've included the plugin in vendor folder and referencing it from ember-cli. So far so good, but I want to change the data in the table dynamically as per the user selection on the list. The way I implemented is

index.hbs

   
        <tr>
            <td></td>
            <td></td>
            <td><button ></button></td>
        </tr>
    


data-table.hbs
 <thead>
    <tr>
       
          <th></th>
       
    </tr>
 </thead>
 <tbody>
       
 </tbody>

data-table.js
import Ember from 'ember';
export default Ember.Component.extend({
   tagName:'table',
   classNames:['table','table-bordered','table-striped','mb-none'],
   uiSetup: function(){
      $('#myTableID').DataTable();
   }.on('didInsertElement').observes('data.[]')
});

Whenever I click on my list (on left side of my page), I'm doing a transitionToRoute to the same route but the model changes since the id of the selected element changes.

When I selected different id on the left side, my model is changing and the datatable is reflecting the new data but with the existing data below to that. Now, when I click sort on the headers the table is resetting to the previous data by removing the latest data.

I've been on this issue since past 3 days but nothing is changing. The other way I approached to this problem is

index.hbs


data-table.hbs
 <thead>
    <tr>
       
          <th></th>
       
    </tr>
 </thead>
 <tbody>
       
 </tbody>

data-table.js
import Ember from 'ember';
export default Ember.Component.extend({
   tagName:'table',
   classNames:['table','table-bordered','table-striped','mb-none'],
   uiSetup: function(){
    this._super(...arguments);
    var table=$('#myTableID').DataTable();
    table.clear();
    var JSON=[];
    for (var i = this.get('data.currentState').length - 1; i >= 0; i--)   {
        var innerJSON=[];
        innerJSON.push("<a }>"+this.get('data.currentState')[i].id+"</a>");
        innerJSON.push(this.get('data.currentState')[i]._data.type);
        innerJSON.push("<button }>"+this.get('data.currentState')[i]._data.config+"</button>");
        if (this.get('data.currentState')[i].id) {
            JSON.push(innerJSON);
        }
    }
    table.rows.add(JSON);
    table.draw();
}.on('didInsertElement').observes('data.[]'),
actions:{
   link1Clicked(){
      console.log('hello');
   }
}
});

For the second approach, everything is working fine but I could not capture action items since those elements were created dynamically and not treated as ember elements instead they are pure HTML elements.

Any idea, where I'm doing wrong or is there any much cleaner approach for using jQuery data tables in ember cli project.

I also tried using ember-cli-jquery-datatables addon which works only for static data but not for dynamic data.

Thanks in advance, any help would be appreciated.




How to update computed property?

I am new to ember. In template, i have

Now, I want By default, labeltext should be, 'Hello' If method A is called, then labeltext = Wow If method B is called, then labeltext = Thanks Is there any way to write the computed property in component which will perform above requirements?




Ember Data: create Model without store

Is there a way to create a DS.Model object without using store.createRecord ?




Ember Addon: writing unit tests for files in my addon folder

I am writing an Ember Addon that provides some services that are not exposed through the app/ folder.

// project Foo
// addon/services/foo.js
import Ember from 'ember';
export default Ember.Service.extend({})

The unit test that gets generated by Ember CLI uses moduleFor helper.

// tests/unit/services/foo.js
import { moduleFor, test } from 'ember-qunit';

moduleFor('service:foo', 'Unit | Service | foo', {
  // Specify the other units that are required for this test.
  // needs: ['service:foo']
});

// Replace this with your real tests.
test('it exists', function(assert) {
  let service = this.subject();
  assert.ok(service);
});

Problem is that since my FooService is not exposed through the app/ folder, moduleFor helper cannot find it using service:foo name.

What would be the best way to unit test my service here? I can see three possibilities: 1) add tests/dummy/app/services/foo.js that exports FooService

// tests/dummy/app/services/foo.js
export { default } from 'foo/services/foo.js';

2) create initializers in the dummy app that registers service:foo

// tests/dummy/app/initializers/account-data.js
import FooService from 'foo/services/foo'
export function initialize(application) {
  application.register('service:foo', FooService);
}

3) don't use moduleFor helper.




What framework or library use

So i'm starting a new project that basically consist on internet of things. I was working with angular 1.x, but in the near feature it will no longer support, so I start wondering what to use. My first option was angular 2, but it still unstable so to use in production is no safe, so i look for other frameworks like ember, backbone, aurelia, and the library reactjs.

Can you suggest, by your experience what would be the appropriate to use for this project.

Thanks.




Ember : toggleProperty is not working inside a jQuery Ajax GET

I'm making an app that if the person is authorized the control panel will show up, and It's almost done but i have a problem with changing the property.
Function this.toggleProperty is working great, but not in an Ember jQuery Ajax Function.
What can I do in that case?

showControls:false,
         someName: function () 
    { 
          {
          Ember.$.ajax
               ({
                   type:"GET",
                   url:"http://localhost:3000/check/",
                   dataType: 'text',
                   success:function(data)
                   {
                     if(data==="true")
                     {
                        this.toggleProperty('showControls');
                     }
                   }
               });
           }
     }.on('init'),

And this is my example back-end in node:

    router.get('/check', function(req, res) 
{
        return res.json(true);
});

And this is my problem:

Uncaught TypeError: this.toggleProperty is not a function

Greetings, Rafał




Express routing with params filter coming from emberJs

I have a problem to make the route for this url:

http://localhost:3000/api/tests?filter%5Bcodeid%5D=eeee

At the moment i tried this:

app.route('/api/tests?filter[codeid:id]')
  .get((req, res) => {
    console.log('It works');
    res.status(200).send({
      msg: 'It works'
    });
  });

But when I test my server with postman I have this result:

Cannot GET /api/tests?filter%5Bcodeid%5D=eeee

Someone has any idea of how manage this ?




ember s - Port 4200 is already in use

I have two ember projects: project1, project 2

project1: ember s , port 4200 is working fine. I closed the project1 terminal and again tried to start ember s inside project2, when i do that, i am getting Port 4200 is already in use.

Port 4200 is already in use.

Why am i getting this error, as other instances where already killed and how to rectify it ?




lundi 25 juillet 2016

Ember.js : Call the route controller from application controller

So I have a toolbar in my application template:

Application.hbs:




Which fires a toolbarButtonClicked action whenever a toolbar button is pressed. For now, I can handle this action from my application controller.

I would like to handle the action in my route controllers (since the buttons have actions specific to routes), however the route controller doesn't receive them since the toolbar is not in the route template.

Is there a way to call a route controller from the application controller, or from a component which is outside the route ?




Sending a HTTP request after an action has occurred

I have a component with an action. After the action has occurred, I'd like to send a PATCH request to an API endpoint. /posts/{id}.

How is this accomplished?

My component code app/components/post.js:

import Ember from 'ember';

export default Ember.Component.extend({
    isLiked: false,
    actions: {
        toggleLiked() { this.toggleProperty('isLiked'); }
    }
});




getting route name from component

I have my problem with link-to help, I want to use it with bootstrap navigation, but I can't manage well active link state, so I'm trying to write a component, but I need to get the current route inside the component, so I can create the html element based on the route. I searched in the api reference, but didn't find nothing.

PS: I know there is an add-on to do that by I'm doing that to learn the framework.

sorry for my bad English.




Angular 2 equivalent of Ember.Computed('Prop1','Prop2'...'prop n')

I am trying to port my Ember Application to Angular 2 , but i failed to see how can I create
Computed Properties--Properties observing other properties for changes and the reacting
in Angular 2.

[(myVar)] &&  onMyVarChange= new EventMitter();

Observes changes to it self and the react.

Any help/directions will be great.




Chunk Ember Model Array

I am trying to split up the model array of controller to make it easier to display but the approach I came up with is not right. How do I access the model array of a controller so that it can be manipulated and still maintain computed properties of the model?

Controller:

export default Ember.Controller.extend({

  queryParams: ['page'],
  page: "",

  playlists: Ember.computed("model", function(){
    var playlistContent = this.get("model.content");
    return _.chunk(playlistContent, 3);
  }),

  actions: {
    setPage(page){
    this.set("page", page);
  }
});

Template:


  <div class="row">
    
        <div class="col-md-4">
            <div class="card playlist-card">
                <img class="card-img-top" src= alt="Card image cap">
                <div class="card-block">
                    <h4 class="card-title"></h4>
                    <p class="card-text"></p>
                </div>
            </div>
        </div>
    
  </div>





Upgrading coupled Ember & Laravel projects (same folder)

I am currently working on a project which is using old software for the front-end and back-end frameworks.

Front-end: Ember 1.8 and back-end: Laravel 4.2.

Ember needs to be 2.5 and Laravel needs to be 5.2.

I have seen Laravelshift website for upgrading the back end which I would prefer to use due to saving time.

Now the web application is setup with Laravel and ember within the same directory.. the ember folders reside in a directory called 'client' and the Laravel files are residing under 'app'.

I have tried to upgrade Ember without completely de-coupling the projects and failed numerous times, getting errors in the terminal complaining about parsing json files - (referring to package.json / bower.json).

What is the proper way this is done? Do you have to search each dependency individually on Github and see if its compatible with the newer Ember version and install it manually?

Up till now I have used: http://ift.tt/1nQpekV and a couple of other guides and haven't made any progress.

I am using gulp as a task runner, when I run it to compile the project it spits out this error:

/Users/JCharnock/Desktop/newatp/pt2/build/js-common.js:27
var emberBuild = path.resolve(pkg.browser.ember);
                                         ^

TypeError: Cannot read property 'ember' of undefined
    at Object.<anonymous> (/Users/JCharnock/Desktop/newatp/pt2/build/js-common.js:27:42)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at /Users/JCharnock/Desktop/newatp/pt2/gulpfile.js:31:11
    at Array.forEach (native)
    at Object.<anonymous> (/Users/JCharnock/Desktop/newatp/pt2/gulpfile.js:25:28)

Does anyone have experience with tedious tasks like this? A point in the right direction would be nice.




Ember.js: Load related multiple models

Since the ember-guides explains how to load mutliple models on a route like that

export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({
      songs: this.get('store').findAll('song'),
      albums: this.get('store').findAll('album')
    });
  }
});

Im wondering how to load only the related model-entries from a second one, like loading ALL songs but only the albums which are indexed in the songs if we assume that the song model containing this

...
albums: hasMany('album'),
...

How can I do that?




ember js custom REST authorization with json web tokens

there have been different kinds of posts about nodejs + emberjs + jwt, but none of them i found helpful, i am really new to SPAs.

This probably is duplicate question, but please, how can you set up authorization in emberjs.

Scenario what i am using is from "http://ift.tt/22XE0pU"

So my backend is nodeJS

var express = require('express');
var app = express();
var fs = require('fs');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var bodyParser=require('body-parser');
var mysql = require('mysql');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    next();
});
var secret='secret key here';
app.use('/api', expressJwt({secret: secret}));
app.use(function(req,res,next){
        console.log(req._parsedUrl._raw);
        next();
})
app.use(cookieParser());
// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json 
app.use(bodyParser.json())

app.get('/', function (req, res) {
    res.send(fs.readFileSync('./dist/index.html','utf-8'));
});
app.use(express.static('./dist'));

app.get('/api/notes',function(req,res){
    res.send('secret code');
});


app.post('/authenticate', function (req, res) {
    //TODO validate req.body.username and req.body.password
    //if is invalid, return 401
    console.log(req.body);

    if (!(req.body.username === 'root' && req.body.password === 'root')) {
            res.send(401, 'Wrong user or password');
            return;
    }

    var profile = {
            first_name: 'John',
            last_name: 'Doe',
            email: 'john@doe.com',
            id: 123
    };

    // We are sending the profile inside the token
    var token = jwt.sign(profile, secret, { 
        expiresIn: 1440 // expires in 24 hours
    });
    res.json({ token: token });
});

app.listen(8989, function () {
    console.log('node port:8989');
});

Ember config:

ENV['ember-simple-auth-token'] = {
    serverTokenEndpoint: server_name+'/authenticate',
    serverTokenRefreshEndpoint: server_name+'/authenticate/refresh',
    identificationField: 'username',
    passwordField: 'password',
    tokenPropertyName: 'token',
    authorizationPrefix: 'Bearer ',
    authorizationHeaderName: 'Authorization',
    headers: {},
};

adapter/application.js

import RESTAdapter from 'ember-data/adapters/json-api';
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';


export default DS.RESTAdapter.extend(DataAdapterMixin,{
namespace: 'api',
host: 'http://localhost:8989',
authorizer:'type:authorize'

});

controllers/login.js

import Ember from 'ember';

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

    actions: {
        authenticate: function(username,password) {
            var credentials =     this.getProperties('identification','password');
            console.log(credentials);
            var authenticator = 'authenticator:token';
            this.get('session').authenticate(authenticator, credentials);
        }
    }
});

What i am getting from ember is

ember.debug.js:31321 TypeError: Cannot read property 'authorize' of undefined
    at Class.authorize (session.js:217)
    at Class.hash.beforeSend (data-adapter-mixin.js:78)
    at Function.ajax (jquery.js:8614)
    at Class._ajaxRequest (rest.js:939)
    at rest.js:929
    at Object.initializePromise (ember.debug.js:51552)
    at new Promise (ember.debug.js:53147)
    at Class.ajax (rest.js:891)
    at Class.findAll (rest.js:413)
    at _findAll (finders.js:136)

So when i want to authorize through nodejs with "'/authenticate'" i get my token back, but next request doesn't seem to use this token propertly or can't find it, that where the error cames in, i guess it requires some store like cookies, but how to implement it?

It would be so great if someone could provide FULL example of authorization, because something doesn't just work and it is hard to tell what is the problem.




Shopify API using ember cli

I am totally new to ember and just need to know if it is possible to use Shopify API with it? any tutorial or example?




Transorfm xml files to json/hdb ember cli broccoli

i am transit my project from ember grunt to ember broccoli and i have problem. In grunt i used handlebars plugin to tranform xml filed to json files and it worked. Do somebody know what plugin is equivalent to it? I read about broccoli-handlebars plugin but still i cant configure it like in my previous version of project. Exactly i need to tranform my xml files from specific path to hbd/js format to specific path.




dimanche 24 juillet 2016

how to output value of object Object in handlebars

I am super green with ember and handlebars and I hit a brick wall, so a little help is appreciated.

I have some json:

[{"_links":{
     "author":[
        {
           "embeddable":true,
           "href":"http:\/\/example.com\/users\/1"
        }
     ],}]

and in handlebars I am trying to get href like this


    


but it returns nothing. author is an array but I don't know how to access it in handlebars, and what I read here on SO, I don't feel fits in context.




Variable inside link-to template in ember js

I have a variable in my controller called appName that i am calling from url. The format for url is /:appName/configure. I am using tag to redirect in the nav. My question is now do i pass the appName inside link-to. The current code that i have is

<a nohref>Dashboard</a>

Here i should be able to change the testApp with the variable in from controller. Also if i am doing this wrong would appreciate the correct way to do the same




samedi 23 juillet 2016

Ember.js: How to load audio-files

Im developing an ember-app which must load an audio file at some point. Since im developing the REST-Server (express.js) in parallel, im wondering how to provide the mp3-file and how to deal with it on the ember-side.

So: How can I load an audio-file as part of my model? (Maybe I should just store an URL in my model?)




Using actions inside of a controller?

I'm new to ember and I would like to use a separate action (shown as shuffle) in one of my actions(assign). I know I'm doing something wrong here, the shuffle method isn't really doing anything. Am I calling it incorrectly or are actions not supposed to be used by other actions? Here is the code:

import Ember from 'ember';

export default Ember.Controller.extend({

taskData: [],
personData: [],
taskIn: ' ',
personIn: ' ',



  actions: {

    saveTask() {

        const task = this.get("taskIn");
        this.taskData.push(task);
    },

    savePerson()
    {
        const person = this.get("personIn");
        this.personData.push(person);
    },

    print(){
        var taskString;

        //this.taskData.remove(0);
        for(var i = 0; i < this.taskData.length; i++)
        {
            taskString = taskString + this.taskData[i];
        }
        alert(taskString);
        //alert(this.personData);
    },

    shuffle(array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    },

    //algorithm to match up tasks with people
    assign(){


        var newTaskD = this.shuffle(this.taskData);
        var newPersonD = this.shuffle(this.personData);
        var taskString = '';
        var peopleString = '';

        for(var i = 0; i<newTaskD.length; i++)
        {
            taskString += " " + newTaskD[i];

        }

        for(var j = 0; j<peopleString.length; j++)
        {
            peopleString += " " + newPersonD[j];

        }

        alert(peopleString);
        alert(taskString);

    }
  }

});




Ember setupController hook in route disconnects model from template

I am trying to set a controller property as soon as my login route is entered. At the moment, I am using method 1, which relies on init in the controller. It works fine, but my understanding is that it is better to use a setupController hook in the route. Ember data shows the record which has been created and the email and password fields update when you type.

I have tried to change the code, to use a setupController hook in the route (Method 2), rather that relying on init in the controller. With this method, the new record is created when entering the route, but email and password are undefined in Ember data, and don't update when typing.

Is there a way that I can still use setupController without disconnecting the model?

Method 1 - Working

routes/login.js

model: function() {
  return this.store.createRecord('authorisation');
},

controllers/login.js

setPreLoginMessage: function() {
  this.set('preLoginMessage', 'Please enter your username and password.'));
}.on('init'),

templates/login.hbs

 

Method 2 - Not working

routes/login.js

model: function() {
    return this.store.createRecord('authorisation');
  },

  setupController: function(controller, model) {
    controller.set('preLoginMessage', 'Enter your username and password'));
},

templates/login.hbs

 




toggle element visibility in ember js based on a boolen

I have created template and controller both called navbar. The code that i have in controller is simply

import Ember from 'ember';

export default Ember.Controller.extend({
    isLogged: true,
});

and that in template is

    
        Login
        Join now
    
        Dashboard
    
<button class="uk-button uk-button-large uk-button-primary uk-width-1-1" disabled=>Test button</button>

The same does not seem to be working. Am i going wrong somewhere ?

The template and controller were generated using ember generator itself and the code above is the only modifications that i made.




vendredi 22 juillet 2016

Cannot GET / Error in EmberJS/Node

When I am working through my application written in EmberJS/BreezeJS served with NodeJS/nginx, occasionally I get the error "Cannot GET /". I have to wait for 10-15 seconds and refresh the page again.

PS: I am not using 'connect'

Any suggestions on the issue please?




Create a "link-to" or "action" in jquery for ember link

I implemented jQuery DataTables in my Ember project by creating a component, which, in it's after render event set up a table to work with an asp.net web api.

All works fine. However for the datatables column definitions (which is basically building up a string for a column's text, I would like to have something that will trigger an ember transition, instead of a browser redirect.

As you can see below I'm currently doing an href in the "template" created for a column:

var columnsDef = [
{
    "data" : "Name",
    "title": "Name",
    "render": function (data, type, row, meta) {
        return  '<a href="/deals/' + row.Id>' +  data + "</a>";
    }
},
{....




Ember Data - how to fetch data without using id

I'm building an app using Ember and trying to talk to a back end API using Ember Data and writing custom adapters.

The API I am using is not RESTful or conform to JSONAPI standard. It has many endpoints that does not take in id but returns data for current user. For instance I have 'getAccountData' api that returns account data of the current user. The returned data has "id" associated with it (user_id of the current user) but you don't pass in "id" when calling the api to get the data.

I tried implementing findRecord method in my custom adapter but "id" parameter is required and it complains if I just call this.get('store').findRecord('account-data'). I can pass in dummy id like this.get('store').findRecord('account-data', 1) but this seems wrong since the 'id' of returned data won't be 1.

Should I be using findAll or query instead? is there a way to do this in clean way?




Where should conditional action logic go?

I am working on a project that uses ember. Conditional logic can be placed in the HTML template, the controller and where the function is define. I have an action that only needs to be fired when a global variable is true.

    <div >...</div>

In the .hbs I can do


   <div >...</div>

   <div>...</div>


or in the function I can

CallThisAction(){
 if(global.x){
    //do something
   }
}

or I could add logic into the controller to prevent the CallThisAction from being called biased off the global.x. Controllers are also depreciated.

I could also pass as param:

CallThisAction(x){
 if(x){
    //do something
   }
}

Is there a cleaner way to do this? Ideally the solution here would be nice:Feature Request




Force Ember component to re-render from within its route

We develop an Ember based framework for internal use of various groups within our organization. Along with this, we maintain a demo page, which displays all the components we've developed along with documentation on how to use the components. I need to modify one of the component demo pages, to allow the user to custom build the component. For example, the component has two properties showCheckboxes and showRadioButtons. By default, showCheckboxes is true, and the component, of course, displays checkboxes. I want to add a select so the user can choose between radio buttons and checkboxes. Everything is wired up correctly and the routes action gets called, but, if I select radioButtons, the component does not refresh and display readio buttons. I've set breakpoints and I see that the route is not called, so the new properties are not read. How can I force Ember to rebuild the component from scratch? I've tried this.refresh() in the route, I've tried setting the model to the new model with the changes, but the component does not redraw with the new properties. I've also tried transitionTo. But if I don't pass a model, nothing happens. But if I pass in the new route, I get this error:

Error: More context objects were passed than there are dynamic segments for the route

I hope this was clear enough for someone to provide some guidance. Thanks




Same object in component and yield block

So I am following the instruction on http://ift.tt/1neM9CH to create a reusable modal. I am trying to make an extensible modal that will be used for simple editing in various places around a gui.

In application.js I have

showModal: function(name, model) {
  this.render(name, {
    into: 'application',
    outlet: 'modal',
    model: model
  });
}

In a template I call this action from a link passing in a contact:

<a class="contact-edit" >Edit contact</a>

contact-edit.hbs:


  <input type="text" name="phone" value="">


my-modal.hbs:

<div class="modal-body">
  
</div>

my-modal.js

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    save: function () {
      this.$('.modal').modal('hide');
      this.sendAction('save', this.get('objectEditing'));
    },
  },
  show: function () {
    this.$('.modal').modal().on('hidden.bs.modal', function () {
      this.sendAction('close');
    }.bind(this));
  }.on('didInsertElement')
});

The problem is edits to theObject in the line <input type="text" name="phone" value=""> are not showing up in the action being called here (which is on the route). What am I doing wrong?




How to add custom javascript file to footer emberjs

I want to add my custom js file to the footer of my ember app. I added my js file to the vendor folder but the file is rendered in the begining of my template.




How to load dependencies in Ember Data

I have an application, with 2 models: Team and User. Each team has many users, and only 1 Team Leader. On the Index view for Teams, I want to display the list of Teams, and the name of the Team leader. I can't get the name of the team leader to be displayed. Not sure what's wrong.

User Model:

export default Model.extend({
  firstName: attr(),
  lastName: attr(),
  team: belongsTo('team', { inverse: 'users' }),
  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
  })
});

Team Model:

export default Model.extend(Validations, {
  name: attr(),
  shortName: attr(),
  description: attr(),
  teamLeader: belongsTo('user', { inverse: null }),
  users: hasMany('user'),
  specialisationArea: attr(),
  sourceEnergyTeam: attr(),
  isEnergyTeam: Ember.computed('specialisationArea', function(){
    return this.get('specialisationArea') == 101;
  })
});

Team Index Route:

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

Team List Template:

  
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>Details</td>
    </tr>
  

And this is the mirage configuration:

this.get('/teams', () => {
  return [{
    id : 11,
    type: 'team',
    name: 'Energy',
    description: 'energy desc',
    shortName: 'short',
    teamLeader: 12,
    users: [12],
    energyTeam: true
  }];
});

this.get('/teams/:team_id', () => {
  return {
    id: 11,
    type: 'team',
    name: 'energy',
    description: 'energy desc',
    shortName: 'eg',
    teamLeader: 12,
    users: [12],
    energyTeam: true
  };
});

this.get('/users', () => {
  return [{
    id: 12,
    type: 'user',
    firstName: 'Pedro',
    lastName: 'Alonso',
    team: 11
  }];
});

I'm not sure what's going wrong, but in the network calls I can see that only a call to '/teams' is being triggered. Any ideas?

Thanks




Ember extend just the component template

I am using Ember JS and have a slightly tricky requirment;

I have to extend a component (not fully in my control). So I plan to use the component JS, but want the template to be in my control (i.e. overwrite what the component provides)

Is that possible ? Does Ember support that? Any reference examples would be great.




jeudi 21 juillet 2016

In Ember js, how to create or mock hasMany relationship in unit test

I'm unit-testing a model which has properties with DS.hasMany() relationships. Whenever I do the following unit-test, I keep getting this error in my test-runner: Error: Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [<Ember.Object:ember367>,<Ember.Object:ember368>]

Can someone shed some light into this, please?

Model:

export default DS.Model.extend({
  accounts: DS.hasMany('account'),
  servicesAccounts: DS.hasMany('services-account'),
  address: MF.fragment('address'),
  appEligibilities: MF.fragmentArray('app-eligibility'),
  appsForPremise: Ember.computed('accounts', function () {
    return DS.PromiseArray.create({
      promise: this.get('store').find('app', {
        account: this.get('accounts').mapBy('id')
      })
    });
  })
});

Model uni-test:

import { moduleForModel, test } from 'ember-qunit';
import Ember from 'ember';

moduleForModel('premise', 'Unit | Model | premise', {
  needs: [
    'model:account',
    'model:services-account',
    'model:address',
    'model:app-eligibility'
  ]
});

test('Apps for premise', function (assert) {
  let model = this.subject({
      accounts: [Ember.Object.create({
        id: 'account-1'
      }),
      Ember.Object.create({
        id: 'account-2'
      })],
      appsForPremise: sinon.spy()
    });

  Ember.run(() => {
  });

  assert.equal(model.get('appsForPremise'), '[{id: account-1}, {id: account-2}]');

});




Ember js access value inside #each in the route

Trying to access the value of the radio button which is created inside a #each loop.


    <div class="radio">
        <label>
          
        </label>
    </div>


and in the route

console.log(get(controller, 'owner'));

But is always undefined. I've got no problem accessing the values of other radio buttons outside of the loop.

All questions around this seem to be from a couple of years ago and reference views which have since been depreciated.




The layout is broken when using material design lite in ember js

When I implement my ember web using material design lite. The following problems exist.

1.The header displays incorrect (the title is disappeared). 2.The drawer cant display in full-screen too.

enter image description here Here is my code

application.hbs

<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header">


    <div class="demo-drawer mdl-layout__drawer mdl-color--blue-grey-900 mdl-color-text--blue-grey-50">
            <header class="demo-drawer-header">

              <div class="demo-avatar-dropdown">
                <span>hello@example.com</span>
                <div class="mdl-layout-spacer"></div>

              </div>
            </header>
            <nav class="demo-navigation mdl-navigation mdl-color--blue-grey-800">
            <i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">home</i>My Task
              <a class="mdl-navigation__link" href=""><i class="mdl-color-text--blue-grey-400 material-icons" role="presentation">inbox</i>Inbox</a>
            </nav>
          </div>


    
    </div>

mytask.hbs

<header class="demo-header mdl-layout__header mdl-color--grey-100 mdl-color-text--grey-600">
        <div class="mdl-layout__header-row">
          <span class="mdl-layout-title">My Task</span>
          <div class="mdl-layout-spacer"></div>


        </div>
</header>  

<main class="mdl-layout__content mdl-color--grey-100">
        <div class="mdl-grid demo-content">   
</div>
</main>

ember-cli-builds.js

/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

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

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

app.import('bower_components/mdl/material.min.css');
app.import('bower_components/mdl/material.min.js');
app.import('vendor/styles.css');
  return app.toTree();
};




mercredi 20 juillet 2016

Using a local install of phantomjs for "ember test"

From a continuous integration perspective, I would prefer to use a local install instead of a global one as the docs currently state. I've searched for a while and looked at the api from "ember test --help" and I don't see the ability to explicitly state the location of phantomjs - ember expects it to be available globally.

Is it possible to run something like "ember test --phantomjs node_modules\phantomjs\bin\phantomjs"? Or modify testem.js to state phantomjs location?




Array variable in an ember controller

-I'm kind of new to ember js and javascript in general and I can't seem to figure out why my methods keep spitting out the error that both taskData and personData are undefined. Any feedback is appreciated!

import Ember from 'ember';

export default Ember.Controller.extend({

    taskData: [],
    personData: [],



      actions: {

          taskData: [],
          personData: [],

        saveTask() {

            var task = this.get("task");
            taskData.push(task);
        },

        savePerson()
        {
            var person = this.get("person");
            personData.push(person);
        },

        print(){

            alert(taskData);
            alert(personData);
        }

      }

});




Ember js, Can't push already normalized json api data into store

I'm unable to push a response into the store. According the the docs since I'm returning jsonapi spec I should be able to push it straight in without normalizing it first.

The code to push the response into the store looks like this:

  getCurrentUser() {
    return get(this, 'store').queryRecord('user', {self: true})
      .then((response) => {
        const user = get(this, 'store').push(response);
        set(this, 'account', user);
        return user;
      });
  }

This throws You must include an 'id' for undefined in an object passed to 'push'. However if I create a dummy response using the output from the server

 getCurrentUser() {
    return get(this, 'store').queryRecord('user', {self: true})
      .then((response) => {

        const testResponse =
        {
          "data": {
            "type": "user",
            "id": "578846b3e5438b26ebbce7d4",
            "attributes": {
              "identification": "admin",
              "display-name": "Administrator"
            },
            "relationships": {
              "servers": {
                "data": []
              },
              "jobs": {
                "data": []
              }
            }
          }
        };

        const user = get(this, 'store').push(testResponse);
        set(this, 'account', user);
        return user;
      });
  }

Everything works as expected. The data in testResponse is a straight copy and paste from postman, so should it not be the same as the data in response or response.data?

So I tried playing around with normalizing it anyway but get all sorts of errors.

 getCurrentUser() {
    return get(this, 'store').queryRecord('user', {self: true})
      .then((response) => {
        const [data] = response.data;
        const normalizedData = get(this, 'store').normalize('user', data);
        const user = get(this, 'store').push(normalizedData);
        set(this, 'account', user);
        return user;
      });
  }
});

throws Invalid attempt to destructure non-iterable instance TypeError

I've tried a few different combinations of above get various errors.

Any pointers would be appreciated.




EmberJS global error when running tests

I am trying to integrate automated testing using Ember Testing.

The application runs fine on browser, without any errors. I tried simply running

ember test

on command line, but get a bunch of global errors and all the tests fail.

These are the errors I'm getting:

not ok 1 PhantomJS 2.1 - Global error: SyntaxError: Unexpected token ',' at http://localhost:4302/assets/vendor.js, line 145617

not ok 2 PhantomJS 2.1 - Global error: Error: Could not find module ember-metal/core required by: ember-testing/index at http://localhost:4302/assets/test-support.js, line 62

not ok 3 PhantomJS 2.1 - Global error: ReferenceError: Can't find variable: define at http://localhost:4302/assets/tests.js, line 1

...

These don't make sense to me since I shouldn't be editing vendor.js and the modules it says it cannot find are there. Any ideas?




Storing initial model property value in Ember.js

Probably a simple answer but as a beginner, say for example I wanted to store a property from my ember model inside of my controller which I could then compare against new data, how could I go about doing it?

To provide more context, I have an input field where the value is retrieved using model.user_input, I want to be able to store this somewhere when the view is first loaded and then compare it when the value changes. I've tried using computed properties but they are also getting updated when the model changes.




Trying to speed up huge retrieval of data for web app.. separate cache?

I am working on a GPS system which uses EmberJS and Laravel.

We currently read all the IMEI's from a PgSQL DB, this is very time consuming and causes the load time of the application to be too slow for an application which one of it's main POI is real-time data.

Does this sound possible/feasible way of speeding this process up.. load all of the data into the cache using the IMEI of the device as its unique identifier.

The cache will run a check to see if any field has changed for a certain IMEI in the DB on a selected schedule. If it has then updated, then the data regarding the IMEI will be read and updated from the DB instantly.

The cache will then update the application constantly updating it every 30 seconds to or so.

So this would now read directly from cache upon application load not from the database although any updated information would come directly from there (any assets which are immobilised for example are a drain on resources).

If this idea is bad then why? and what alternative do you suggest?




Can we use ember-cli purely as a front end like we are using javascript and jquery?

Can we use ember-cli purely as a front end like we are using java-script and j query.I want to add reference of ember-cli in my .net project and use it just for validation.is it possible?any suggestion can be appreciated.




How can i use ember js without ember-cli with PHP or java?

How can I use ember js without ember-cli with PHP or java? How can I interact with back end data? Any example will be much appreciated.




How to compile public es6 sources by Ember CLI

I have a JavaScript source file in folder public/assets/js/foo.js, it uses es6 syntax, the app works on debug mode, but when I try to build a production package, it failed because of es6 syntax error. My question is how could I compile public es6 JavaScript source by ember-cli, thanks for reply.




mardi 19 juillet 2016

Ember embedded record mixin append related model

I have artist, album, track pages. Tracks are related to artist, track can have many artists. I have an artist page with listing artist's top tracks and albums. Problem is When i load album, album tracks are appended to toptracks after i updated the serializer with embeddedRecordsMixin Please help me to figure it out.

json response from backend API: "id": 12, "title": "test track", "artist": "test artist", "artists": [ { "id": 168, "name": "test artist" } ] },


//serializer, application serializer is a RESTAPISerializer
export default ApplicationSerializer.extend(EmbeddedRecordsMixin, {
  attrs: {
    artists: {
      deserialize: 'ids',
      serialize: false
    }
  }
});

//artist model
export default Model.extend({
  active: attr('boolean'),
  name: attr(),
  cover: attr(),
  like_count: attr(),
  releases: hasMany('album'),
  toptracks: hasMany('track'),
  albums: Ember.computed.filterBy('releases', 'single', false).readOnly(),
  singles: Ember.computed.filterBy('releases', 'single', true).readOnly(),
});

//album model
    export default Model.extend({
  title: attr(),
  artist: attr(),
  single: attr('boolean'),
  release_date: attr('string'),
  cover: attr(),
  like_count: attr('number'),
  tracks: hasMany('track', {async:true}),
  artists: attr(),
  discs: Ember.computed('tracks.[]', function(){
    return this.get('tracks').reduce(function(disc, track) {
      var id = track.get('disc');
      if (disc[id]) {
        disc[id].tracks.push(track);
      } else {
        disc[id] = {'tracks': [track]};
      }
      return disc;
    }, {});
  }).readOnly(),
  groupDiscs: Ember.computed('tracks.[]', function() {
    return _.uniq(this.get('tracks').mapBy('disc')).length > 1;
  }).readOnly()
});

//track model
export default Model.extend({
  album: belongsTo('album'),
  icon: attr(),
  title: attr(),
  artist: attr(),
  explicit: attr('boolean'),
  duration: attr(),
  disc: attr('number'),
  seq: attr('number'),
  active: attr('boolean'),
  like_count: attr('number'),
  minutes: Ember.computed('duration', function() {
    var duration = this.get('duration');
    if (duration) {
      return duration.substring(3);
    }
  }),
  playing: false,
  artists: hasMany('artist')
});




ember get current user information from session

I am using ember-simple-auth library. I was successfully able to logged in a user. But can't able to access current user. The following code is working:

    
      <p>i m logged in</p>
      <a href="#" >Logout</a>
    
      <p>i m not logged in</p>
    

but the following code is not working



I wanted to get user information but failed. So, I dig into the mater and used ember helper as:

<p></p>

It helped me and I was able to get current user information like:

<p></p>

which is good but I want something like the following:

<p></p> 

or simply:

<p></p>

how can I change my application controller so that will be able to get simple current user method which will look good. My application controller code looks like that:

// /app/controllers/application.js

import Ember from 'ember';

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

  actions: {
    logout() {
      this.flash.success('Successfully logged out!', 5000);
      this.get('session').invalidate();
    }
  }
});