vendredi 30 septembre 2016

Getting data from a REST API into ember.js application?

I followed the ember.js quickstart instructions to get a basic app up and running. I've been trying to figure out how to adjust this code in one of the route files to pull data from a REST API rather than defining it explicitly in an array.

   export default Ember.Route.extend({
      model() {
        return ['Ada Lovelace', 'Niklaus Wirth', 'Bill Gates', 'James Gosling', 'Guido van Rossum', 'Ken Thompson', 'Donald Knuth']
      }
   });

Except instead of writing in these names, I'd like to get data from a mock REST API URL. Can anyone tell me how to do this or direct me to an article that describes how? Some details about underlying concepts would also be greatly appreciated. Thanks!




How to distinctively separate HTML contents into pages - just like MS Word

Is there a way to separate an HTML content into A4 sized pages just like's done in MS word? I am working on a project that should automatically paginate contents into a new page once the first page exceeds a certain limit or length. This is exactly how I'd like it:

enter image description here




Sticky footer in ember

Hey I create Ember application , And I try to set Sticky Footer.
I try to do this by this tutorial Sticky Footer On CSS-Tricks , Cause it's work for me once.
But with Ember its dosen't work

My css:

.mainFooter {
     height:100px;
     color:white;
     background-color: #0c2635;
     text-align:center;
}
.wrapper {
    min-height: 100%;
    margin-bottom: -100px;
}
.wrapper:after {
    content: "";
    display: block;
}
.mainFooter, .wrapper:after {
    height: 100px;
}

My HTML:

<footer class="mainFooter">
    SOME TEXT
</footer>

As I said, it's dosent work.
I watch the source code via the Inspector and I saw that Ember added its own wrapper to content the I put in the application.hbs file, this wrapper have a class named ember-view so I try to do:

.ember-view {
    min-height: 100%;
} 

But it's dosent work either, the footer displayed in the middle of the page.
Someone maybe try this and successid?
I would like to know about a solution to this problem




Lookup route from URL in Ember router

The Ember router creates a URL from a route, e.g. with the link-to helper. Is it possible to reverse-lookup a route from a given URL?

The reason for this is that I have some absolute URL links in my database which point to pages in my Ember app, and I want to transition to them within the app. Using <a href=> works, but breaks my tests (when running ember test -s) as following the link redirects the whole browser page, stopping the test suite. If it's possible to redirect to an absolute URL without breaking the test suite that would also do the trick.

Many thanks.




ember application is not working in dev mode

I'm new to ember.I'm working on already build app and when i start server, I try visiting the localhost page (//localhost:4200/) in my browser but the page is blank.In bowser console it always shows error while processing route index.when i run in terminal ember test it gives me "not ok 1 PhantomJS 2.1 - Acceptance | config/index: visiting /config/users". enter image description here when i run ember test enter image description here

node --version : v0.10.36 ember-cli --version : 0.2.5 npm --version : 1.4.28

I cannot update above versions.i have to work on same versions.if i update it mismatches all the files. The terminal gives me a "Build successful" message but I go to localhost and see the blank page.Seems like I'm missing something simple but can't figure it out.Please and thank you for your help.




Combine Ember with Laravel

I'm new to Laravel & Ember.
And I sa some project that bulid like so:
All JavaScript Files found in laravel app/assets directiony, and also the hbs file.
When I get into the public index route its load a view with include script tags for all the files that found in the assets directiony.

So I want to know some things:

1) How I put JS and hbs files in this directiony and make them load from the broswer? cause I read that assets need to be putted in the public directiony?
2) How can I do manipulation on the hbs files ? meaning that I need to wrap the HandelBar template code in Ember.compile function?
3) If I want to use the newest version of Ember how do I write the code in client-side JS And not in ECA6 standart?
4) Which file of Ember I need to include in the view?




How JavaScript frameworks help web server reduce load?

JavaScript frameworks?

why we need JavaScript frameworks?

How JavaScript frameworks help web server reduce load?




Why insert the type when using DS.attr(type) in Ember

In ember documentation it says the following for the method DS.attr():

By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed

If you go to the transform method documentation it says the following:

You can specify that you would like a transform to run for an attribute by providing the transform name as the first argument to the attr method. Ember Data supports attribute types of string, number, boolean, and date, which coerce the value to the JavaScript type that matches its name.

So my question is: is it bad to explicitly insert the type of the attribute? It seems it forces some kind of cast as mentioned after (quoted below). So it could have some performance decrease (almost nothing).

The boolean transform can handle values other than true or false. The strings "true" or "t" in any casing, "1", and the number 1 will all coerce to true, and false otherwise.

The only reason I see to insert the type is to make it easier to read in your model, but that can be done in a comment as well...




Trouble generating a model instance and applying it to a specific key in Ember Mirage

While generating an instance of a staffMember within ember-cli-mirage I'm attempting to create a 'task' and assign it to the key 'tasksCreated' within the staffMember model. My current code is as follows;

It's creating a task, and creating a staffMember but the two have no relationships built between them.

app/models/staff-member.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    atWork: DS.attr('boolean'),
    avatar: DS.attr(),
    tasksCreated: DS.hasMany('task', {
        inverse: 'creator'
    }),
    tasksAssigned: DS.hasMany('task', {
        inverse: 'assignee'
    })
});

app/models/tasks.js

import DS from 'ember-data';

export default DS.Model.extend({
    creator: DS.belongsTo('staff-member', { inverse: null }),
    assignee: DS.belongsTo('staff-member', { inverse: null }),
    creationDate: DS.attr(),
    description: DS.attr('string'),
    urgency: DS.attr()
 });

mirage/models/staff-member.js

import {Model, hasMany} from 'ember-cli-mirage';

export default Model.extend({
    tasksCreated: hasMany('task'),
    tasksAssigned: hasMany('task', { inverse: 'assignee'})
});

mirage/models/task.js

import {Model, belongsTo} from 'ember-cli-mirage';

export default Model.extend({
    creator: belongsTo('staff-member'),
    assignee: belongsTo('staff-member')
});

mirage/factories/staff-member.js

import { Factory, faker, trait } from 'ember-cli-mirage';

export default Factory.extend({
    name: faker.name.firstName,
    atWork: faker.random.boolean,
    avatar: faker.image.avatar,
    withTasks: trait({
        afterCreate(staffMember, server){
            server.createList('task',2,{tasksCreated: [staffMember]});
        }
    })
});

mirage/factories/task.js

import { Factory, faker } from 'ember-cli-mirage';

export default Factory.extend({
    creationDate: faker.date.recent,
    description: faker.lorem.sentence,
    urgency: faker.random.number({
        'min': 0,
        'max': 4
    })
});

mirage/scenarios/default.js

export default function(server ) {  

    server.createList('staff-member', 4, 'withTasks');

}




Git Repository and commit going fine but refuse to upload folder content

new to git and have obviously read and watch lots of tutorial.

Set up everything with terminal, everything is working very well with bitbucket.

BUT: my ember.js project is not uploading at all. I have a greyout folder in my repository and nothing is commit or push.

Every files i commit or push goes up there no problem but i dont understand why my project folder wont upload.

I have try so many thing found here or elsewhere on the net, i even try with git client, and always, my folder containing my project wont upload.

last thing i tried : git init inside the folder :

iMac:new01 nick$ cd red-green-client

iMac:red-green-client nick$ git add * The following paths are ignored by one of your .gitignore files: bower_components dist node_modules tmp Use -f if you really want to add them. iMac:red-green-client nick$ git commit -m "third test" On branch master nothing to commit, working tree clean iMac:red-green-client nick$ git push fatal: No configured push destination.

Im out of idea. help ?




How to use "asNavFor" option in ember-cli-slick

I'm trying to implement slick slider in my ember application i found this ember-cli-slick via ember observer and i have to use Slider Syncing option.in jquery its possible by using below option.but in ember how to refer the class name?

asNavFor: '.slider-nav'




template won't render from model object after sorting

I am sorting an array of objects queried from Ember-Data by 'type'-key before returning them in the model()-method of an Ember.Route to be rendered.

app/routes/test.js

export default Ember.Route.extend({
  model() {
    let obj = Ember.Object.create({a: [], b: [], c: []});
    this.get('store').findAll('obj').then(function(unsorted){
      unsorted.forEach(function(item) {// sort per type
        obj.get(item.get('type')).addObject(item);
      });
      return obj;
    });
  }
});

The array returned by (the promise of) the Ember-Data query looks like this (all objects have Ember internal properties)

[
  {
    _id: '1',
    type: 'a',
    properties: {...}
  },
  {
    ...
  },
  {
    _id: '15',
    type: 'b',
    properties: {...}
  }
]

And the new object with objects sorted by "type"-key looks like this

{
  a: [{
      _id: '1',
      type: 'a',
      properties: {...}
    },
    ...
  ],
  b: [
    ... ,
    {
      _id: '15',
      type: 'b',
      properties: {...}
    },
  c: [...]
};

app/routes/test.hbs

<h2>Test</h2>
<h3>Type a</h3>

  <div>
    
  </div>


The template doesn't render the part that loops over the array, nor does the Ember-inspector plugin list the Model property under "Own properties" of the route (right panel in "View tree"-mode).

However, when returning a POJO (literally pasting object with array's by key in code) everything behaves as expected.
I suspect this has something to do with the internal (Ember-)properties of the objects returned by Ember-data (I have read about the owner of an object etc.) but I can't seem to figure this out ...




How can I disable input field in ember-selectize?

I was able to do it with javascript input properties. I want to know if there is any other subtle way of doing.




jeudi 29 septembre 2016

EmberJS. How use two way binding for input and focus event?

I'm trying to create custom input component. First of all I tried to use native input component. Somthing like this

<input type="text" value="" onblur= onfocus=>

But this code does't provide two way binding. The observer doesn't triggered

valueChanged: Ember.observer('inputValue', function () {
  // deal with the change
  this.set("valueSet",(this.get('inputValue').trim().length > 0));
}),

After this I have try use input helper



In this case valueChanged observer is triggered but focus event doesn't listening, otherwise the key-press is triggered.

How can I use two way binding and focus event at one time?




Ember.js - Passing model to Component (by reference)

I have a pretty simple question about ember components. I'm defining my model in my route:

model() {
  return this.store.createRecord('player');
},

I'm passing the model to my component in my template:



Then, inside my component, I can succesfully get the correct data from my model, but nothing that I change in my model is getting sent to the database. I can only assume this is because the model is being passed by value instead of by reference. Is there a way to pass it by reference, and if not, what is the common workaround for editing a model inside of a component.

Thanks!




How to implement CRUD in a single Route in Ember

I'm trying to implement CRUD into a single route in Ember JS, all I have is a single route "products/index" which currently displays all the products but I would like to implement all 4 actions

The way it would work is through a modal window for 'editing' and 'creating' new products

is this even possible? and if so, how would I go about doing this?




In ember how do I wait for the result of a get to complete?

I have a simple admin page that does the following:

  beforeModel: function() {
    var permission = this.get('userService.currentUser.userPermission.isAdmin');
    if(!permission) {
      console.log("no permission");
      return this.transitionTo('index');
    }
  },

User and UserPermission are separate models. UserPermission is loaded async.

This works great if I navigate to /admin (the permission object is already cached), but if I go to /admin directly it does not, presumably because the userPermission object hasn't been loaded.

Is there a way to say "get the userPermission then evaluate"?




Using computed properties on page load

First, my current versions:

Ember      : 2.8.1
Ember Data : 2.8.1
jQuery     : 3.1.1

I'm using query params in a controller. If a user goes to assignments?strm=1292, the strm, computed term, and computed filteredClusters will be called. However, the filteredClusters will be empty on the initial page load (e.g. I navigate to /assignments?strm=1292 using my browser). It is only after the selectStrm action is called to update the strm query param that filteredClusters will start returning results.

My assignments index controller is listed below:

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['strm', 'cluster', 'title'],
  strm: null,
  cluster: null,
  title: null,

  term: Ember.computed('strm', function() {
    var strm = this.get('strm');
    var terms = this.get('model.terms');

    return strm ? terms.filterBy('strm', strm)[0] : null;
  }),

  filteredClusters: Ember.computed('term', 'model', function() {
    var term = this.get('term');
    var clusters = this.get('model.clusters');

    if(term) {
      return clusters.filter( (cluster, index, clusters) => {
        var terms = cluster.get('terms');

        return terms.mapBy('strm').includes(term.get('strm'));
      });
    } else {
      return clusters;
    }
  }),

  actions: {
    selectStrm: function(strms) {
      var strm = strms[0];
      this.set('strm', strm);
    }
  }
});

What can I do to get filteredClusters loaded on the initial page load?

Thank you for any and all information.




Upgrading Ember Web Application from 1.2.2

The Ember web application currently in our production environment has the following versions.

  • ember.js - 1.2.2
  • ember.data - 0.13

I've found upgrade notes from ember 1.10 onwards in the following guide but the version of ember in our application is much older.

Guide: http://ift.tt/1G8PK0G

Ideally, the application needs to be upgraded to 1.10 then following this guide to 1.13 and then progressing upwards to 2.0+ etc.

Are there any known issues with upgrading the application from a low version of 1.2.2 to 1.10. Ember-data will need to be upgraded in parallel, I assume but not too sure on when to upgrade each.

Finally, is there any possible way to add the ember-cli into an already existing application? If so, what ember-cli version should be added and when, to upgrade wit ember.js and ember-data.js.




Detecting that a textarea is focused during a button click

Explanation

I have a textarea and a button. When I click the button, I want to insert text into the textarea. However, the text that I insert depends upon the current focus of the texteara. Here are some cases:

Cases

(As of the time that the button is clicked)

  • Textarea focused
    • Insert text where the cursor is, as-is
  • Textarea unfocused
    • Insert text at the end of the textarea (ie add a newline to the inserted text)

Example / Attempt

Here is a fiddle with my example implementation: http://ift.tt/2cEe9lu

$(document).ready(function() {
    $('button').click(function() {
        var $text = $('textarea');

        var currentValue = $text.val(),
            len = currentValue.length,
            isTextAreaFocused = $text.is(':focus'),
            optionalNewline = isTextAreaFocused ? '' : '\n';

        var start = $text[0].selectionStart,
            end = $text[0].selectionEnd,
            beforeText = isTextAreaFocused ? currentValue.substring(0, start) : len,
            afterText = isTextAreaFocused ? currentValue.substring(end) : len;

        var insertedText = 'foo',
            newValue = beforeText + insertedText + afterText + optionalNewline; 

        $text.val(newValue);
    });
})

Problem

I believe that the button focuses before it has a chance to know if the textarea is focused. Is there a hook or way to handle the click event on the button such that I'll know (before it is focused) what is focused?

Off point: I'm using Ember as my framework. I'd really love to see a pure JS / jQuery solution, but I just wanted to place Ember on the table as well.




Ember display model which has relationship in one component

I want to expose my models to one component and show in one table. I want this to be modular in a way that I can use this component to other models.

The way I have done the attributes which have certain relationship do not show up. The problem that I found out is because by the time I grab it, the promise has not been resolved and I am not grabbing the attributes using . I cant figure out one way of doing that... I'm really new to ember and its' been a problem for me...

I have the following two models

// #models/inventory-summary.js
export default DS.Model.extend({
    name: DS.attr('string'),
    total: DS.attr('number'),
    projects: DS.hasMany('inventoryProject'), //I WANT TO SHOW THIS GUY HERE
});
// #models/inventory-project.js
export default DS.Model.extend({
    name: DS.attr('string'), // IN PARTICULAR THIS ONE
    summary: DS.hasMany('inventorySummary'),
});

Templates:

// #templates/inventory-summary.js
// here I'm sending the model to the component and mapping the attribute to something readable


// #templates/components/model-table.hbs
// here is where I show the value of the model

   


My helper

export function getItemAt(params/*, hash*/) {
    return params[0][params[1]];
}

And in my route I'm doing:

// #routes/inventory-summary.js
model(params) {
    let query_params = {page_size: 100};
    if (params.page !== undefined && params.page !== null) {
        query_params['page'] = params.page;
    }
    return Ember.RSVP.hash({
        inventoryProject: this.get('store').findAll('inventoryProject'),
        inventorySummary: this.get('store').query('inventorySummary', query_params),
    });
},
setupController(controller, models) {
    this._super(...arguments);
    controller.set('projects', models.inventoryProject);
    controller.set('inventorySearchResult', models.inventorySummary);
    let columnMap = [
        ['name', 'Name ID',],
        ['total', 'Total'],
        ['projects', 'Project', {'property': 'name', 'has_many': true}]
    ];
    controller.set('columnMap', columnMap);
},

Finally this is the part of the code which is really messed up which is where I'm passing to the template the values I'm trying to show

// #components/model-table.js
getValueForColumn(values, params) {
    if (values.length > 0) {
        if (typeof values[0] === "object") {
            return this.getResolved(values, params);
        } else {
            return values;
        }
    }
    return values;
},
getResolved(promise, params) {
    let result = [];
    promise.forEach( (data) => {
        data.then((resolved) => {
            let tmp = "";
            resolved.forEach((item) => {
                console.log(item.get(property)); // THIS GUY SHOWS UP LATER
                tmp += item.get(property) + ", ";
            });
            result.push(tmp);
        });
    });
    return result; // THIS GUY RETURN AS EMPTY!
},
didReceiveAttrs() {
    this._super(...arguments);
    let model = this.get('model');
    let columnMap = this.get('columnMap');
    for (var i = 0; i < columnMap.length; i++) {
        attributes.push(columnMap[i][0]);
        columns.push({'name': columnMap[i][1], 'checked': true});
        values.push(this.getValueForColumn(model.getEach(columnMap[i][0]), columnMap[i][2])); //WRONG HERE
    }
    this.set('model_table', {});
    let model_table = this.get('model_table');
    Ember.set(model_table, 'values', values);
 },

I am able to show in the template if I start doing a bunch of if's in the , because I believe the template does some kind of binding I am not doing and it resolves later, but it was really ugly and nasty. I wanted to do something cleaner... that's why I'm posting here.




Silent errors in ember components

Recently i have found strange behaviour in my application

if i have a problem in component, i don't receive any errors, application loads with blank screen and after several tens seconds i receive a deprecation: [deprecation id: ember-views.render-double-modify] without any clues what is the real problem

it might happen when i pass non existing closure action to component, or event if i manually throw error in computed property in component

it happens in all recent versions of Ember (2.4.6+)

I can not reproduce such behaviour in empty application, so probably problem in my application or addons, but i have no idea how to find what catches errors.

Any ideas how to find source of the problem?




Route refresh in ember does not clear input controls content

In a template i have many input controls like text box.

I want to refresh the page, so i called this.refresh(); in the corresponding route's actions hash. Route is getting refreshed (model hook is fired..), but the user entered text in text boxes do not disappear. Then what is the point in refreshing?

How to make the input controls appear as it is like when the route was loaded first time?




set the dependent keys of a computed property at run time

Here is the scenario

dep = function(){

     cannot put any "this" here
}

obj =  DS.Model.extend({
        response: DS.attr(),
        cp: Ember.computed(dep(), function(){ ...})
    });

the computed property is known only after the model has loaded ; the response is a json field, containing various keys. I want dependency on parts of the json, what exact part is known after the model is loaded

the dep() function would need to have access to "this" but it does not work if it is defined outside the create instruction, and it does not work if it is defined as a computed property either for instance

obj =  DS.Model.extend({
    response: DS.attr(),
    dep:Ember.computed('response', function(){ 
     some computation 
     and for instance 
     return 'response.path1{a,b}';
     }),
    cp: Ember.computed('dep', function(){ ...})
});

does not work either because dep is not changing from just 'response' dependency, we would need to apply the same dependency on cp and dep which is tautological, and dep would not be needed

Another thing that does not work is

  obj =  DS.Model.extend({
            response: DS.attr(),
            cp: Ember.computed(this.dep(), function(){ ...}),
            dep(){    this.get('response')...  }
        });

So does any one knows how to set the dependent keys of a computed property at run time, with a computation dependent on a Model instance

thanks




Redirecting to specific slug from textfield in ember

I am totally new to ember so please be nice :)

I have an Ember app where i want to redirect to a specific slug taken from an textfield input. In my .hbs i have the following code:




Emberjs: stop and retry transitions in willTransition

When a user is about to leave the present route, I'd like to display a warning and let him choose between leaving (and losing changes) and staying in the current route.

In order to catch all possible transitions, I need to do this in the routes willTransition method.

I'm attempting to abort() and then retry() the transition if the user chooses to. But the retry doesn't seem to have any effect. It should be noted that it is called asynchronously. Here's a twiddle that demonstrates that: http://ift.tt/2cDBsak

Here's my route example route:

import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
    willTransition(transition) {
      transition.abort();
      Ember.run.later(function(){
        console.log('Transition... now!');
        transition.retry();
      }, 2000);

      return true;
    }
  }
});

The log shows up, but I never get redirected to the application route.




mercredi 28 septembre 2016

How do I add a CSS class to the application view in Ember 2.8?

Views are gone since Ember 2.0.0, but you could do this:

// app/views/application.js or app/application/view.js
import Ember from 'ember';

export default Ember.Component.extend({
  classNames: []
});

In Ember CLI 2.8 this workaround no longer works, looks like the views folder is now being ignored. However, the Ember inspector still shows this for the application view:

view:foobar@view:toplevel

And the HTML is:

<div id="ember420" class="ember-view"><h2>application</h2>
</div>

So, there must be a way to customize the view.




Bind checkbox to element of one array in Ember 2+

I'm trying to bind elements of one array to the checked attribute of checkboxes using Ember 2.8. I'm also using this in one component.

The checkboxes show all marked, but whenever I tried to use the action hideOrShowAllColumns it does not mark all checkboxes again if there was one which was not checked... so I guess I'm passing the value of the array element and not the element itself. I don't know how to do this in javascript/ember...

This is my view

 
All

    
    


This is my component.js

export default Ember.Component.extend({
    init() {
        this._super(...arguments);
        this.set('allColumnsChecked', true);
    },
    didReceiveAttrs() {
        this._super(...arguments);
        let columnMap = this.get('columnMap');
        let allColumns = Array(columnMap.length).fill(true);
        this.set('allColumns', allColumns);
    },
    actions: {
         hideOrShowAllColumns() {
            let all = this.get('allColumnsChecked');
            all = !all;
            this.set('allColumnsChecked', all);
            if (all === true) {
                let allColumns = this.get('allColumns');
                allColumns = allColumns.map(() =>  true);
                this.set('allColumns', allColumns);
            }
        },
}

Helper getItemAt

export function getItemAt(params) {
    return params[0][params[1]];
}




Getting refresh_token using googleapis lib

So I have Google Oauth flow setup using googleapis lib, and I don't seem tog et a refresh_token after I use oauthClient.getToken(code, ..). It only returns the access_token and the id_token.

Here's my code:

function getOauth() {
  var oauthClient = new google.auth.OAuth2(
    config.googleOauth.id,
    config.googleOauth.secret,
    `${config.https ? 'https' : 'http'}://${config.baseUrl}/google`
  );
  return Bluebird.promisifyAll(oauthClient);
}

/**
 * Initialize session based of the auth code, which
 * gives us the accessToken and the payload.
 *
 * Returns a session with the user tokenized and
 * the accessToken for use to restore on page refresh.
 */
router.get('/initial', function * (req, res) {
  try { 
    let oauth = getOauth();
    let code = req.query.authorizationCode;
    let results = yield oauth.getTokenAsync(code);
    let tokens = results[0];
    let result = yield oauth.verifyIdTokenAsync(tokens.id_token, config.googleOauth.id);
    let payload = result.getPayload();
    let user = yield User.findOneByEmail(payload.email, req.communityConfig);
    let data = { user };

    if (user.role) {
      let role = yield Role.findOne(user.role, req.communityConfig);
      data.roles = [role];
    }

    let token = auth.createToken(data);

    res.json(extend({}, req.query, { token, accessToken: tokens.id_token }));
  } catch(error) {
    console.log(error.message);
    throw new StatusError(401, error);
  }
});

/**
 * Use the google provider's fetch method to restore the session
 * data using the accessToken.
 *
 * Returns a token created from the user and role, along with
 * all of the query props passed in.
 */
router.get('/restore', function * (req, res) {
  try {
    let oauth = getOauth();

    oauth.setCredentials({
      access_token: req.query.accessToken
    });

    let tokens = yield oauth.getAccessTokenAsync();
    let result = yield oauth.verifyIdTokenAsync(tokens[0], config.googleOauth.id);
    let payload = result.getPayload();
    let user = yield User.findOneByEmail(payload.email, req.communityConfig);
    let data = { user };

    if (user.role) {
      let role = yield Role.findOne(user.role, req.communityConfig);
      data.roles = [role];
    }

    let token = auth.createToken(data);

    res.json(extend({}, req.query, { token }));
  } catch(error) {
    console.log(error.message);
    throw new StatusError(401, error);
  }
});

So everything works, on initial and on refresh, but after the access_token expires, it no longer authenticates.

Token used too late, 1475070618.739 > 1475005777

I hear that I have to specify access_type to 'offline' but I don't even know where to set that in my case.




ember-cli-flot and 'plothover' or 'plotclick' events support

I have ember-cli-flot and ember-cli-flot-tooltip installed (ember 2.8) and have set the flot options to grid: {clickable: true, hoverable: true} but can't seem to generate any events for 'plothover' and 'plotclick'. Any ideas?




Emberjs invoke action from plain javascript

I have an iFrame embedded in an ember app. How can I call a components method from within the iframe?

I guess I somehow need to get the ember instance via window.parent but how to do it and especially how to trigger an ember action?




Overriding class in a composer package

Currently I have a Laravel installation using Laravel Passport (which uses league/oauth2-server for the server implementation). I would like to return the user id when a oauth2 token is granted, so I can use it to identify the authenticated user in my EmberJS app.

The suggested method to do this is:

Create my own class:

use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;

class UserIdBearerTokenResponse extends BearerTokenResponse
{
    protected function getExtraParams(AccessTokenEntityInterface $accessToken)
    {
        return [
            'user_id' => $this->accessToken->getUserIdentifier()
        ];
    }
}

Modifying AuthorizationServer.getResponseType() in vendor/league/oauth2-server/src

    protected function getResponseType()
    {
        if ($this->responseType instanceof ResponseTypeInterface === false) {
            // Return my own class instead of provided one
            $this->responseType = new UserIdBearerTokenResponse();
        }

        $this->responseType->setPrivateKey($this->privateKey);

        return $this->responseType;
    }

But this approach requires me to add the vendor/league/oauth2-server/src/AuthorizationServer.php file to my git repo.

This seems very messy and unreliable to me. Is there a better/cleaner way to achieve this?




mardi 27 septembre 2016

Ember one-to-one not serializing foreign key for one side of relationship

I have two things in a monogamous relationship. For the sake of their anonymity, we'll refer to them as a User and a Profile

user.js

export default DS.Model.extend({
    profile: DS.belongsTo('profile', { async: false }),
    name: DS.attr('string')
});

profile.js

export default DS.Model.extend({
    user: DS.belongsTo('user', { async: true }),
    active: DS.attr('boolean')
});

Users are attached at the hip with their profiles, so the profile is always sideloaded.

{
    "user": {
        "id": 23,
        "name": "Homer Simpson",
        "profile": 42
    },
    "profiles": [
        {
            "id": 42,
            "active": true,
            "profile": 23
        }
    ]
}

Now, say a user gets into trouble with the local criminal scene and decides to change his name. And to fly under the radar, he also wants his profile to be deactivated.

let user = this.get('user'),
    profile = user.get('profile');

profile.get('user.id'); // 23

user.set('name', 'Mr. Thompson');
user.save().then(() => {
    schedule.set('active', false);
    return schedule.save();
});

The payload for request.save is fine...

{
    "user": {
        "id": 23,
        "name": "Mr. Thompson",
        "profile": 42
    }
}

But for schedule.save..?

{
    "profile": {
        "id": 42,
        "active": false,
        "user": null
    }
}

Why, oh why, is the user being set to null?

There are no custom serializers coming into play nor any changes to .save

  • Ember CLI: 1.13.10
  • Ember Data: 1.13.15



Ember: difference between unloadRecord and destroy for new records

In the context of a route model that hasn't been persisted to the backend yet (its id is null still and we haven't called save yet), if we want to discard the record, is it more correct to use unloadRecord or destroy?

Context: For use when a form is transitioned away from but is neither saved nor canceled. I'm new to ember and I am a bit confused by the fact that unloadRecord is private for Model but not for Store. It may be obvious but I am also not positive when it is correct to refer to the object as a model vs. a record (I am assuming they are sometimes used interchangeably but it's technically correct to call them records if they are existing instances).




Ember integration test setup() not being called

I'm trying to follow these instructions to initialize a service in an Ember component integration test. However, it appears that setup() is never called and the tests fail. However, I can add that same code to the beforeEach() function and I can see that it was called and the tests pass.

moduleForComponent('header-editor', 'Integration | Component | header editor', {
  integration: true,
  setup () {
    // manually invoke the ember-intl initializer
    instanceInitializer.initialize(this);
    let intl = this.container.lookup('service:intl');
    // this log statement will NOT appear in the console
    console.log('setup', intl);
    intl.setLocale('en-us');
  },
  beforeEach () {
    // // manually invoke the ember-intl initializer
    instanceInitializer.initialize(this);
    let intl = this.container.lookup('service:intl');
    // this log statement appears in the console
    console.log('beforeEach', intl);
    intl.setLocale('en-us');
  }
});

Does anyone know why setup() would not be called?




Turns warnings into errors in Ember.JS

Is it possible to throw warnings as errors in Ember application. I found

Ember.ENV.RAISE_ON_DEPRECATION = true

but as I understand it works only for depreciation warning. I want to throw warnings like

"WARNING: Binding style attributes may introduce cross-site scripting vulnerabilities; please ensure that values being bound are properly escaped. For more information, including how to disable this warning, see http://ift.tt/2dwCNSm."




Ember addObserver works for array but not for object

In my Ember app, I am able to apply addObserver on simple array, but not for simple object ?

Is it designed to work only with arrays ?

I am getting an error "addObserver is not a function"




Ember.js acceptance test check inputs' values

I have a lot of logic in a big form, where input values depend on each other. I am trying to test values of these inputs.

In this case find("#sales_price").val() results in empty string:

fillIn("#sales_price", 12345);
andThen(function() {
  assert.equal(find("#sales_price").val(),123456);
...

In such example binding stops to work and find("#sales_price").val() gets initial value of input (but not 12345):

find("#sales_price").val(12345);
andThen(function() {
  assert.equal(find("#sales_price").val(),123456);
...




Spreading plain objects into Ember Component

I'm working with Ember (ember-cli v2.8.0) and trying to add some properties to a component. I found a few objects were using really similar code, so I created a function to generate the code rather than copy&pasting all over. In my ember-cli-build.js I've added the following babel options:

var app = new EmberApp(defaults, {
  babel: {
    optional: ['es7.decorators']
  },
  /* ... */
});

This is a simplified version of the generator function:

function generateProperties(name, defaultValue) {
  return {
    [name]: defaultValue,
    [`tenTimes${name.capitalize()}`]: 10 * defaultValue
  };
}

If I test out the object spread notation it looks fine in the console:

console.log(generateProperties('five', 5));
console.log({ ...generateProperties('five', 5) });

/* Both output { five: 5, tenTimesFive: 50 } */

Now I want to use that in an Ember component:

Ember.Component.extend({
  four: 4,
  ...generateProperties('five', 5),
  ...generateProperties('six', 6),
  seven: 7
});

Now I get a syntax error - the code that gets generated looks like this:

_ember['default'].Component.extend({
  { key: 'four', initializer: function initializer() { return 4; } },
  { key: },
  { key: },
  { key: 'seven', initializer: function initializer() { return 7; } },      
});

What's going on here?? The workaround I came up with is this:

Ember.Component.extend(generateProperties('five', 5), { four: 4 })

It seems to work, but all the documentation I can find says that you can use as many Mixins as you want, and then the object properties. These aren't technically Mixins, so it seems like it might bite me later on. Is this a proper workaround? Why doesn't the object spread notation work here?




Ember.merge does not trigger property change

I'm manipulating an array using Ember.merge. However, this does not seem to trigger a change in the template where I display something if the array is present. This seems to work when I use array.pushObjects. Just wondering if this is desired behavior. Related twiddle: http://ift.tt/2czRVRQ




lundi 26 septembre 2016

Authentication failure upgrading Ember from 2.7 to 2.8

I'm upgrading an app from Ember 2.7 to 2.8 and am having some odd test failures. I use ember-simple-auth for authentication, I test this in an acceptance test by filling in my login form appropriately with a variable email then using:

equal(currentSession(application).get('data.authenticated.user_email'), email, "Successfully logged in " + email);

This works fine in 2.7 but in 2.8 the variable currentSession(application).get('data.authenticated.user_email') sometimes returns undefined. This happens intermittently - I have a test which logs in several different users and if I run the test suite multiple times, different users fail to log in each time.

I'm quite confused by this - any ideas would be gratefully appreciated!




How to pull data from an outside API using EmberJS?

So I'm trying to learn EmberJS, and I'm struggling really hard with this one. Basically, I have the following basic structure

Template:

<ul>
  
    <li> - </li>
  
</ul>

Route File:

export default Ember.Route.extend({
    model() {
        return [
         {'title':'Super Mario Bros', 'console':'NES'},
         {'title':'Pac Man', 'console':'Arcade'},
         {'title':'Galaga', 'console':'Arcade'},
         {'title':'Frogger', 'console':'Arcade'},
         {'title':'Marvel vs. Capcom', 'console':'Arcade'},
         {'title':'The Legend of Zelda', 'console':'NES'},
         {'title':'CastleVania', 'console':'NES'},
         {'title':'Final Fantasy IV', 'console':'SNES'}];
    }
});

But instead of just hardcoding it like I have here, I want to pull it from an Apiary API link using a GET call. How do I do I do this?

(Apiary http://ift.tt/2d4JNaZ)




Changing assets outputPath doesn't update in html

I'm trying to change the outputPaths for my assets from the default assets to media so I can more easily integrate it with my php framework.

In my ember-cli-build.js file, I've made the following modifications to my app as defined here:

var app = new EmberApp(defaults, {
    fingerprint : {
        replaceExtensions : [ 'html', 'php', 'css', 'js' ]
    },
    outputPaths: {
      app: {
        css: {
          'app': '/media/application-name.css'
        },
        js: '/media/application-name.js'
      },
      vendor: {
        css: '/media/vendor.css',
        js: '/media/vendor.js'
      }
    },
    'ember-power-select': {
      theme: 'bootstrap'
    }
  });

While the generated application-name.css, application-name.js, vendor.css and vendor.js files are saved on the hard drive in the correct assets directory, the index.html file is not updated to match. Instead, it links to the same default assets/application-name.*s[s] files.

Any ideas why this isn't working? Thanks.




EmberJS Authorization and User Roles: Best Practice

Suppose I am building a web application through which users can make and sell hot dogs. I am using EmberJS for the client.

Background:

  1. I am currently implementing authentication using Ember-Simple-Auth, which seems to be a fairly standard library to use with Ember for the purpose of signing in, having user sessions, or tokens.

  2. There are two types of users - cooks and consumers.

  3. I will have my server determining if a specific user is a cook or a eater, and then will be placing that information into a cookie in the page served to the client.

  4. I have a navbar (which is an isolated Ember Component) that will have the home button, and one more button. If the user is a cook, the Cook button must be shown, and the Consumer button will be hidden, and vice-versa if the user is a consumer.

My question is, what is the optimal/recommended way to implement these user roles with Ember Simple Auth?

TLDR: Need to authorize user to access elements in web page based on user role. What is the current recommended way to do this in EmberJS?




Ember serializer customization for alternate url

I am a newbie to ember. So here is what i faced. I got backend RESTAPI written in python/Django. It provides following json response on /api/works/

[
{
    "id": 17,
    "title": "about us",
    "description": "some project",
    "owner": "admin"
},
{
    "id": 19,
    "title": "test1 profit project",
    "description": "dev null",
    "owner": "test1"
}
]

also on detail view E.g:/api/works/17/:

{
"id": 17,
"title": "about us",
"description": "some project",
"owner": "admin"
}

there is also /api/works/17/tasks/ for listing work tasks

[
{
    "id": 2,
    "title": "secondWorkTask",
    "description": "task2 description",
    "due_date": "2016-09-26",
    "assign": 1,
    "project": "about us"
},
{
    "id": 3,
    "title": "some task name",
    "description": "some task description",
    "due_date": "2016-08-27",
    "assign": 2,
    "project": "about us"
}
]

on the front-end side i am using ember-cli version2.7.0 + ember-django-adapter. I can get /api/works without problem. What i want to achieve is on the ember side when work detail url load, it must show all tasks. Currently i can get work detail by this url /api/works/17/ But how can i get tasks? Please help me to find a way to solve this.




How to avoid Ember treating a model as a nested property of another model when fetching data

I have two models with their own end points:

myurl.com/items

myurl.com/markets

Also, items and markets are related where in the item`s model I have

 markets: DS.hasMany()

Now, in the item template when I try to access, item.markets, I want ember to use the markets model already loaded in the app. But instead it tries to make a call to http://ift.tt/2cFIvm3 which does not exist.

Is there any way to stop ember from making that call? The app does get the data from the markets model which is already loaded and the data is displayed. But I have this failed call (Error: Ember Data Request GET http://localhost:3000/items/1/markets returned a 500) in my console and I do not know how to avoid it.




Saving a belongsTo relationship fails

I'm having trouble saving a new record because the belongsTo relationship isn't being assigned to the newly created record (promise something Promise).

Anyway, my backend is rails and these are the params that are required:

Parameters: {"photo"=>{"title"=>"Hello word", "image"=>"someimage.jpg", "user_id"=>nil}}

As you can see the user_id is nil even though my session successfully returns the logged in user id

Ember Controller

  let photo = this.store.createRecord('photo', {
    title: this.get("newModel.title"),
    image: this.get("newModel.image")
  });

  this.get('store').findRecord('user', this.get('session.data.authenticated.userId')).then(function(user){
    photo.set('user', user);
  });

  photo.save();

This fails because from reading the ember docs you cannot assign a promise as a relationship (?!?!?). There are no errors returned from ember side, however the belongs_to relationship for the user looks like this

user <DS.PromiseObject:ember891>

I also seem to notice that Ember keeps adding the user_id param despite no value being present

Note that I cannot save the record without user_id because of presence validation on the backend and it's not a solution to remove those.

Any solutions for this?




When a route gets a bad parameter, why do route links with other parameters get an "active" class?

I have an Ember site with a navigation bar that has multiple links to the same route but with different parameters, like this:




When I click on a link, it goes to the right page, and the link gets an active class, as expected.

However, when I enter a URL with a bad parameter for the same route (e.g. /foo/bar), it goes to my error route as expected, but it adds an active class to all foo links. I would expect that none of these foo links would appear active.


I can produce this behaviour with a very simple ember-cli app. All I have to do is run ember new foobar and add/edit a few files as shown below:

/* app/router.js */

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

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

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

export default Router;


/* app/routes/foo.js */

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    if (params.foo_id !== '1' && params.foo_id !== '2') {
      throw 'error';
    }
  }
});


/* app/routes/error.js */

import Ember from 'ember';

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


/* app/templates/application.hbs */




Then, when I run ember s and go to http://localhost:4200/foo/bar in my browser, all the links have the active class.


Is this an Ember bug, or am I doing something wrong, or is this the way Ember is designed to work? In any case, how can I prevent Ember from adding an active class to foo links when the user goes to a bad foo URL?




EmberJS API questions using PHP

I'm using Laravel/PHP to output some JSON for Ember to pick up.... a couple of things here.

First, my PHP looks like this (is there another way to send the data)

        return Response::json([
        'articles'  => $articles->toArray()
        ], $statusCode);   

This is what I am used to doing.

      foreach($articles as $article) {
         $response['articles'][] = [ 
            'id'    =>  $article->id,
            'body'  =>  $article->body,
            'title' =>  $article->title
        ];
     }

The first PHP snippet works fine, but the second does not. I get all kinds of errors about resource types by Ember.

Next question is for Ember heads. Right now I am getting everything working with RESTAdapter but should I be using JSONAPIAdapter instead? When I try to get it working with JSONAPIAdapter and JSONAPISerializer I get this error " One or more of the following keys must be present: \"data\", \"errors\", \"meta". I can get that error to go away but then I get an error about an undefined type or an unknown resource.




Ember observe nested model property

In EmberJS, if I want to observe a property "selectedValue" which is inside a nested model, how can I do that ?

The below does not seem to be working;

modelChanged: function() {  

}.observes('myModel.@each.@each.selectedValue'),




My ember-cli project is prompting this message at the time of building the project. and the file mentioned in the message is collapsed. How to solve this? Actually after referring the internet i found a solution. BABEL Note: The code generator has deoptimised the styling of "app.js" as it exceeds the max of "100KB in Meteor But this is not working, i still get the same message. please suggest a method to avoid this message.




Ember.computed.sort property not updating

I've been cracking my head for the last several days, trying to understand what am I doing wrong. I'm implementing an infrastructure of lists for my app, which can include paging/infinite scroll/filtering/grouping/etc. The implementation is based on extending controllers (not array controllers, I want to be Ember 2.0 safe), with a 'content' array property that holds the data.

I'm using Ember.computed.sort for the sorting, and it's working, but i have a strange behaviour when i try to change the sorter. the 'sortedContent' is not updating within the 'displayContent', even though the 'sortingDefinitions' definitions are updated.

This causes a weird behaviour that it will only sort if I "sort" it twice, as if the sorting was asynchronous.

I am using Ember 1.5 (but it also happens on 1.8) (attaching a snippet of code explaining my problem)

sortingDefinitions: function(){
    var sortBy = this.get('sortBy');
    var sortOrder = this.get('sortOrder') || 'asc';

    if (_.isArray(sortBy)) {
        return sortBy;
    }
    else {
        return (sortBy ? [sortBy + ':' + sortOrder] : []);
    }
}.property('sortBy', 'sortOrder'),

sortedContent: Ember.computed.sort('content', 'sortingDefinitions'),




displayContent: function() {
    var that = this;
    var sortBy = this.get('sortBy');
    var sortOrder = this.get('sortOrder');
    var list = (sortBy ? this.get('sortedContent') : this.get('content'));

    var itemsPerPage = this.get('itemsPerPage');
    var currentPage = this.get('currentPage');
    var listItemModel = this.get('listItemModel');

    return list.filter(function(item, index, enumerable){
        return ((index >= (currentPage * itemsPerPage)) && (index < ((currentPage + 1)  * itemsPerPage)));
    }).map(function(item) {
        var listItemModel = that.get('listItemModel');
        if (listItemModel) {
            return listItemModel.create(item);
        }
        else {
            return item;
        }
    });

}.property('content.length', 'sortBy', 'sortOrder', 'currentPage', 'itemsPerPage')

Thanks in advanced, Manu




Reference rootURL / any absolute path in hbs

The ember-cli-generated index.html file includes this line

<script src="assets/vendor.js"></script>

and rootURL is replaced with respective the value from environment.js (just '/' in develompent).

Now I want to include an icon in a component (in fact, a template used only with partial) used in different routes (also at different nesting levels), but

<img src="assets/img/some_logo.svg">

just does not do the trick -- rootURL is empty, as is any other string else defined in environment.js.

I guess I could create a class file, import ENV from '../config/environment' and defined rootURL: ENV.rootURL, but surely ember does not expect me to do this whereever I want to include anything from my assets folder, does it?




What is the best practice to serialize `User` model for guest and authrized user specified by JSONAPI?

I'm building API with express.js according to JSONAPI specification and have sequelize.js model. For example, User model with attributes such as name, email, balance, last_login_time and etc.

If user on client application request data about third-party user API needs to respond only with public attributes such as name and last_login_time.

If user on client application request data about himself API needs to respond with public and private attributes.

As a serializer I use jsonapi-serializer lib. I have serializer like that:

var JSONAPISerializer = require('jsonapi-serializer').Serializer;

module.exports = new JSONAPISerializer('users', {
  attributes: ['name']
});

Sould I create 2 different serializer? Will not it lead to troubles because almost all models will have 2 serializers and it could lead to confusion of references?




How to configure emberjs routes in SpringMVC?

We have an Ember frontend and Spring Boot backend. When Ember runs standalone on port 4200 and the Spring Boot backend on 8080, then everything works. But this scenario is somewhat unusual for production environments, not only because of CORS problem. The URL of the backend must be known already on build time (!) of the Ember application, because it's integrated within the compiled ember app. This is not possible for many projects. Therefore, we want to integrate the frontend Ember App in the Spring Boot backend, which is usual for e.g. SPA with AngularJS. The Ember app (from /dist) is thus copied to src/main/resource/static. After adjusting the rootURL and API.host with the Ember app that works very well. The problem arises now, when a manual reload for an URL is made in the browser. Such a URL is now an Ember route. The http-request arrives at the Spring Boot backend which don't knows the route and we got a 404 error.

How should SpringMVC (as part of the Spring Boot backend) answers the httpRequest for such a route, so that the Ember app continue their work and handle the request ?

HTML Page request (by browser)
http://host/springBootAppContext/index.html => src/main/resource/static/index.html (ember app) 

REST API request (by Ember App)
http://host/springBootAppContext/users => RESTController mapped for /users

Ember Routing (by Ember App)
http://host/springBootAppContext/user-list => ???

You can't provide a normal Spring MVC @Controller class because the ModelView response is interpretet as user-list.html or similar which doesn't exist




Ember.js - Filter messages

I'm getting the following JSON response on /messages endpoint:

{ "messages": [ { id: 1, sender: 2, receiver: 1, body: "this is a first comment", created_at: "2016-09-05 10:00:00", updated_at: "2016-09-05 10:00:00", user: 2 }, { id: 2, sender: 1, receiver: 2, body: "this is a second comment", created_at: "2016-09-05 11:00:00", updated_at: "2016-09-05 11:00:00", user: 2 }, { id: 3, sender: 3, receiver: 1, body: "this is a first comment", created_at: "2016-09-05 12:00:00", updated_at: "2016-09-05 12:00:00", user: 3 }, { id: 4, sender: 1, receiver: 3, body: "this is a second comment", created_at: "2016-09-05 13:00:00", updated_at: "2016-09-05 13:00:00", user: 3 }, ] }

These are all the messages the current user has with the other users. The user property is the user whom the current user is having the conversation with, whether is receiving from or sending to. I need to filter these messages and get only the last message with each user.

In this example I'll end up with the messages with the id's 1 and 3.

Moving forward I have set up the route messages/:user_id and when going to this route you can see all the messages exchanged with that particular user.

If doing the filter I need server side, then when visiting messages/:user_id route, all the messages with that user would be loaded in the store. Then when going back to messages I get all these messages that were previously loaded in the store.

I've put up an Ember Twiddle to help illustrate this.

I was looking into the mapBy and uniq methods and toying around with them with no success.

Any directions or suggestions are greatly appreciated.




Import mixin into add-on in Ember cause "Uncaught Error: Could not find module"

I am doing the following in my addon/component/my-component.js:

import Ember from 'ember';
import layout from '../templates/components/my-component';
import myMxixin from '../mixins/my-mixin';

export default Ember.Component.extend(myMixin,{
    layout
});

However doing this gave me Uncaught Error: Could not find module foo/mixins/my-mixin imported from foo/components/my-component

The path of my-mixin.js is app/mixins/my-mixin.

How do I import my mixin, given the above structure? Thank you.




Ember loader on Model save

is there a way to show loading template when we save a model.

i am able to use Application level loading template when transition to different route but when a model is saved at that time loading template does not show.

this.transitionTo('routeName') takes you to loading.hbs until it gets the promise from server but when doing model.save() it does not show.




Firefox: default outline on focus not visible

I have a situation with Firefox browser on Win 7 and Win 10. I have a left menu on the page with a menu icon and 5 menu items. The Menu icon can expand/collapse the left menu. So when the page loads first time or when we switch to any other page, the focus will go to the menu icon and user can use keyboard tabbing to navigate through the menu items.

Now the issue is this. On firefox, in a particular scenario, I do a form post and leave the page and land on another page. From there I click the exit button and land back on my original page. And when I do that, I want the menu icon to be focused with the white outline(user agent style) visible. But what I see is that the menu icon is not outlined.

For debugging purposes, I am printing document.activeElement and it says that the menu icon indeed is the active element. Also when I press the tab key, the focus goes to the next element after the menu icon, and shift+tab now takes focus back to the menu icon with a visible outline now.

So the situation is that the icon is focused but the outline is not visible. The icon is a div with tanindex="0" and focus is set using JS.

Any help would be appreciated. This works fine on all other browsers including FF on Mac.

NOTE: AM using ember framework, and the left menu here is a component and am setting the focus on the menu icon on the component's didInsertElement lifecycle hook.




Ember-data model resets other relationship when loading hasMany

I have an OrderTask model in my project, that belongs to Order and belongs to assignee which is represented by User model, so the schema looks like this:

// order-task.js
export default Model.extend({
  //...
  order: belongsTo('order', { inverse: 'orderTasks' }),
  assignee: belongsTo('user', { inverse: 'orderTasks' }),
});

// order.js
export default Model.extend({
  // ...
  shop: belongsTo('shop'),
  orderTasks: hasMany('order-task', { inverse: 'order' }),
});

// user.js
export default Model.extend(userValidations, {
  // ...
  shop: belongsTo('shop'),
  orderTasks: hasMany('order-task', { inverse: 'assignee' }),
});

On the order page we fetch tasks via order.get('orderTasks') and server returns all order tasks: completed and active.

In the toolbar we fetch user's tasks via user.get('orderTasks') and server returns only active tasks that assigned to current user.

Every time user.orderTasks is reloaded, the list of order's tasks (order.orderTasks) loses assignee relationship (orderTask.assignee), but only for completed tasks.

Probably this happens due to the fact that server returns only active user tasks, BUT I can't understand how this affects order tasks. Is it possible to define relationships so they don't interfere in the data store like that?

Thanks in advance!




dimanche 25 septembre 2016

Ember js: Making dynamic routes and models and controllers

I have to replicate the same behaviour (nested routes, models, controller functions, store functionality) for like 12 different routes. The only difference is in their model attributes for which the template will also be updated. So for instance I have two routes named Notes and Tasks which are fetched in the same way and also have the same functionality in the controller but the Tasks route has attributes say Subject and Text whereas Notes has Name and Description but even the template functionality is the same.

What would be the best approach to not repeat the same functionality for such routes? Can one model or route or controller be created generic enough such that ember.js can decide on run time to do stuff for each individual route? Can I reuse one model/controller/route's functionality for the 12 different routes that I have?




Is it possible to enable Ember Cli Mirage Scenario for acceptance test

In documentation it shows how to use server global to create models and everything, but it is possible to use scenarios to populate the mock database? Or are we supposed to create objects on the fly?




How to observe store collection

I have code for generate checkboxes list:

  accountsCheckboxes: Ember.computed('accountsCheckboxes.@each', function(){
  return this.model.accounts.map(row => {
    return {
      label: row.get('name'),
      value: row.get('id')
    };
  })
}),

but after modify accounts collection, add or remove, this computed property doesnt refresh. I tried find how to do it with events, or how to observe store collection, but without success. I modyfy this model collection in others controllers.




Testing an ember computed function returns a function not the result of the get

I have a simple Ember object with a computed function which formats a date, e.g.

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

export default DS.Model.extend({
    date: DS.attr('date'),
    posted_date: Ember.computed('date', function() {
        return this.get('date').toLocaleDateString("en-GB");
    })
});

When I test the computed, I weirdly get a failure saying that the the result of get('posted_date') is a function, qUnit outputs it like this:

Expected:   
"2016-05-01"
Result:     
function(){
  [code]
}

Seems like I'm doing something stupid here but I can't figure it out. The value displays ok in my template, so I think there may just be a problem with the test but I can't see anything wrong with it. The test looks like this:

test('date is formatted to UK format', function(assert) {

  const model = this.subject();

  Ember.run(function() {

    model.set('date', new Date('2016-05-01')); 

    assert.equal(model.get('posted_date'), '2016-05-01');
  });
});

Any thoughts?




ember tests failing using Mirage for GET requests

I'm following the tutorial on the emberjs website. I have it all working but the tests are failing with 404s.

mirage/config.js

export default function() {
  this.namespace = '/api';
  this.get('/rentals', function(db, request){
    if(request.queryParams.city !== undefined) {
      let filteredRentals = rentals.filter(function(i){
        return i.attributes.city.toLowerCase().indexOf(request.queryParams.city.toLowerCase()) !== -1;
      });
      return { data: filteredRentals };
    } else {
      return { data: rentals };
    }
  });
}

application.js

import DS from 'ember-data';

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

list-rentals-test.js

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

moduleForAcceptance('Acceptance | list rentals');

test('should redirect to rentals route.', function(assert) {
  visit('/');
  andThen(function(){
    assert.equal(currentURL(), '/rentals', 'should redirect automatically');
  });
});

the result is

Not found: /api/rentals
should redirect automatically
Expected:   
  "/rentals"
Result:     
  "/"

The app works perfectly but I would like to get the tests to pass as well. Any suggestions?




Ember data fetch json file

I'm trying to get data from json file from server. My code:

adapters/application.js:

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    host: 'http://exampleweb.com',
    namespace: 'file.json'
});

models/item.js

import DS from 'ember-data';

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

routes/index.js

import Ember from 'ember';

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

templates/application.hbs


<br>


JSON file on server look like this:

{
  "Products": [
  {
    "name": "Aviator"
  },
  {
    "name": "Dark"
  }]
}

Now ember requst http://ift.tt/2dhpHfr. How can I get this Products correctly and display them in template?




belongsTo relation call returns null within observer

I have belongsTo relation on a model:

//book.js
export default DS.Model.extend({
    name: attr('string'),
    item: belongsTo('item', {async: true}),
});

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

When I call:

let b = store.createRecord('book', {name: 'test'});

b.save().then(function(b) {
  //b is saved correctly here

  b.get('item').then(function(item) {

  //item relation is gotten successfully - all works well

 });

});

(NOTE: I'm not initially setting the item relation when creating the book record, because this is determined by the backend response)

...everything works as expected so far.

now, somewhere else I have an observer that fires when a change to a books array is made.

when it fires I'm iterating over the books array with the newly saved book and calling the relation item the exact same way as I do right after saving the book.

but for some reason item relation on the book record is always null within the observer.

booksChanged: on('init', observer('books.[]', function() {

//this gets triggered
    let b = this.get('books').get('firstObject');//->just assume the book created is the first object

   b.get('item').then(function(item) {

     //item is null, why???

   });


}));

version 2.7 ember and ember-data.

any thoughts?

thanks




Ember dynamic routing not working

I want to have a url like this /restaurants/:pageNumber and I want /restaurants to assume the pageNumber parameter is 1.

Here is my Router.js :

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

If it remove the function() {} for it, I just get a blank page with no errors in the console for /restaurants/1

My routes/restaurants/index.js :

export default Ember.Route.extend({
  ajax: Ember.inject.service(),
  model(params) {
    return Ember.RSVP.hash({
      response: this.get('ajax').request('/getAllRestaurants', {method: 'GET'}),
      currentPage: params.pageNumber | 1
    });
  }
});

On the templates/restaurants/index.hbs I check and it's always 1. If I remove the | 1 it's undefined.




samedi 24 septembre 2016

Ember CLI sends analytics information by default to who?

This is the .ember-cli file.

{
  /**
    Ember CLI sends analytics information by default. The data is completely
    anonymous, but there are times when you might want to disable this behavior.

    Setting `disableAnalytics` to true will prevent any data from being sent.
  */
  "disableAnalytics": false
}

Who does Ember CLI send analytics to by default?




Ember.js Computed Properties (Overwriting get and set)

I am working on an Ember.js application and I'm using ember-cli 2.7. I'm trying to overwrite the properties for get and set, but when I do, I get an unexpected token error.

Here is the code of my controller file:

  import Ember from 'ember';

  export default Ember.Controller.extend({

  isDisabled: true,

  emailAddress: '',

  actualEmailAddress: Ember.computed('emailAddress', function(){
    get(key){
      return `getting email...${this.get('emailAddress')}`;
    }
  }),

  emailAddressChanged: Ember.observer('emailAddress', function(){
    console.log('observer is called: ', this.get('emailAddress'));
  })
});

This seems like a simple solution, but I do not find the bug and it's killing me. Please help me and thank you.




htaccess - Redirect All but Sub-Directory (Ember js)

I am running my main website with Ember and because of that have my htaccess file set up to redirect all requests to my index page for routing.

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) /index.html [NC,L]

However, I have since added a sub-directory called /horror that is also running on Ember. Any request made to domain.com/horror I want to have redirect to /horror/index.html again, for proper routing.

How can I configure my .htaccess file to handle this?




vendredi 23 septembre 2016

Ember include in-app shared components addon in in-app engine

In an Ember application that contains an in-app engine (my-engine) and an in-app addon for shared components (shared-components), how do you include the shared components addon as a dependency of the in-app engine so you may use the components in the templates of the engine? The shared components addon has two components, global-header and global-footer.




How to create template helper

I want to create eq helper. It already exists in ember-truth-helpers addon, but I need only eq helper so I decided create it by myself in my plugin.

I've created file assets/javascripts/discourse/helpers/eq.js.es6 in my plugin with such content:

import { registerHelper } from 'discourse/lib/helpers';

registerHelper('eq', function(params) {
  return params[0] === params[1];
});

and use it in template in this way:

 <h1>hello</h1> 

But eq is not defined.

What is the right way to create helper?




Google Places Autocomplete not appearing

Component

import Ember from 'ember';

export default Ember.TextField.extend({
type: 'text',

didInsertElement: function() {
  this.$().addClass("form-control");
  var autocomplete = new google.maps.places.Autocomplete(
    (document.getElementById('autocomplete')),{types:['geocode']} //trying without jQuery, but still.
  );
}});

Template



which renders to

<input id="autocomplete" type="text" class="ember-view ember-text-field form-control" placeholder="Enter a location" autocomplete="off">

but still, i get:

InvalidValueError: not an instance of HTMLInputElement

Any help would be really appreciated.

EDIT: Ember 2.6




Nesting ember acceptance test helpers in "andThen"

I've always written ember tests like this:

test('should add new post', function(assert) {
  visit('/posts/new');

  fillIn('input.title', 'My new post');
  click('button.submit');

  andThen(() => {
    assert.equal(find('ul.posts li:first').text(), 'My new post')
  });

  click('button.edit');
  fillIn('input.title', 'My edited post');
  click('button.submit');

  andThen(() => {
    assert.equal(find('ul.posts li:first').text(), 'My edited post')
  });
});

but I also see tests written "nested" style like this:

test('should add new post', function(assert) {
  visit('/posts/new');

  fillIn('input.title', 'My new post');
  click('button.submit');

  andThen(() => {
    assert.equal(find('ul.posts li:first').text(), 'My new post')

    click('button.edit');
    fillIn('input.title', 'My edited post');
    click('button.submit');

    andThen(() => {
      assert.equal(find('ul.posts li:first').text(), 'My edited post')
    });
  });
});

Is one way better than the other or correct? Could the first style be a source of race conditions?




Delete item after sorting jQuery UI with Ember

I am using Ember with jQuery UI sortable and it works fine until I want to delete some item after sort. This questio is allready answerd on stackoverflow but that solution does not work for me. I am using Ember 2.6.

Component template

<ui id="department_roles">
    
        
            <li data-id=""  role_id="" class="ui-state-default role_droppable">
                <span>
                    
                </span>

                <button >Remove</button>
            </li>
    
</ui>

Component, The sorting works fine and after delete action item is deleted from array but DOM is incorrect.

    import Ember from 'ember';

export default Ember.Component.extend({
    list: Ember.ArrayProxy.create({content: Ember.A()}),
    init: function () {
        this._super();
        this.get('list').pushObject({
            id: 1,
            index: 1,
            name: 'name1'
        });
        this.get('list').pushObject({
            id: 2,
            index: 2,
            name: 'name2'
        });
        this.get('list').pushObject({
            id: 3,
            index: 3,
            name: 'name3'
        });
        this.get('list').pushObject({
            id: 4,
            index: 4,
            name: 'name4'
        });
        this.get('list').pushObject({
            id: 5,
            index: 6,
            name: 'name5'
        });
    },
    sortProps: ['index:asc'],
    sortedList: Ember.computed.sort('list', 'sortProps'),
    updateSortedOrder(indices) {
        this.beginPropertyChanges();
        let tracks = this.get('list').forEach((item) => {
            var index = indices[Ember.get(item, 'id')];
            if (Ember.get(item, 'index') !== index) {
                Ember.set(item, 'index', index);
            }
        });
        this.endPropertyChanges();
    },
    didRender: function () {
        this._super();
        var self = this;

        Ember.$("#department_roles").sortable({
            update: function () {
                var indices = {};
                Ember.$(this).children().each((index, item) => {
                    indices[Ember.$(item).data('id')] = index + 1;
                });

                self.updateSortedOrder(indices);
            },
        });

        Ember.$('#department_roles').disableSelection();
    },
    actions: {
        removeItem: function (itemId) {

            var self = this,
                deleteItem,
                list = this.get('list');

            this.$("#department_roles").sortable("destroy");

            list.arrayContentWillChange();

            list.forEach(function (item) {

                if (item.id === itemId) {
                    deleteItem = item;
                }
            });

            list.removeObject(deleteItem);

            list.arrayContentDidChange();

            Ember.$("#department_roles").sortable({
                update: function () {
                    var indices2 = {};
                    Ember.$(this).children().each((index, item) => {
                        indices2[Ember.$(item).data('id')] = index + 1;
                    });
                    self.updateSortedOrder(indices2);

                },
            });

            console.log(self.get('sortedList'));
        }
    }
});




Can't get current value from select in Ember 2

I'm trying to get the value every time the user changes the select component. But the value always returns 'undefined'.

I've been through all Stackoverflow questions and other sites, but without success. I feel like I'm missing something here. I'm using Ember 2.8.

My component template:

<div class="form-group">
    <label for=""></label>
    <select name="" id="" class="form-control" >
        <option value="0" selected></option>
        
            <option value=></option>
        
    </select>
</div>

My component logic:

import Ember from 'ember';

export default Ember.Component.extend({
    tagName: '',
    currentValue: null,
    actions: {
        getSelectValue(value) {
            console.log(value); //always returns undefined
        }
    }
});

I'm calling it like this:



In the template I've also used the onchange="" syntax, but then the action wasn't called.

At this point I have no logic in my route or controller handling this.

Thanks for your help!




Ember find model by Id

In my Ember app, I have a complex model that looks like below (kind of contains 2-dimensional array)

[
    [
        {
            id: 'Section1_123',
            label: 'abc'
        },
        {
            id: 'Section1_456',
            label: 'xyz'
        }
    ]
],
[
    [
        {
            id: 'Section2_123',
            label: 'abc'
        },
        {
            id: 'Section2_456',
            label: 'xyz'
        }
    ]
]

There are a lot of other attributes, but this is the overall structure.

Now my question is can I drill-down & find a specific object. It has unique ids (as shown in the example above)

So I need something like model.findBy(Id) I then need to change/set some values for that object. Say I want to change the obj.label from 'abc' to 'abc_NEW'

Just to add, The main model is actually a simple JS array...but the inside objects (e.g. those with id: 'Section1_123', etc) are actually Ember objects




How to insert extra item to template each

I have such template

<tbody>
  
    
  
</tbody>

I want to insert extra item into this rendering template list, something like this:

<tbody>
  
    
      
    
      
    
  
</tbody>

But the problem is this solution will skip some topic when someCondition is true, ie it will note insert but replace.

Is there a solution to add an item to template render list?




jeudi 22 septembre 2016

Ember unable to pass router action to component

I have a component that need to receive an action that I placed on the router since its job is to refresh part of the model.

Apparently I can call the router action from a button but I am not able to pass the same action down to the component.

The router

export default Ember.Route.extend({
    actions: {
        doSomething: function(){
            alert('Router handled!');
        }
    }
});

The page template

<button >speak</button>


The component

export default Ember.Component.extend({
    actions: {
        onPageClicked: function(pageNo){
            this.sendAction('onGetUsers', pageNo);
        }
    }
});

The button click works. When I use the component I make it to its action but the sendAction never work or fires.

Is there a rule that I cannot pass actions to down line components? or am I doing something wrong in the code?




How to deal with list of partial data in ember

(Ember 2, if it matters)

I am trying to show a list of search results on an ember page. The api I am using basically just returns a list of ids and names for a particular record type (let's call it foo). Unfortunately, I also need to get a thumbnail with each item and the search results route doesn't provide it. The search-result model is comprised of a list of several attributes, each of which is simply a DS.hasMany to a different model, e.g.

  foos: DS.hasMany('foo', {
    async: true
  }),
  bars: DS.hasMany('bar', {
    async: true
  }),

The data returned from the server looks like this:

{
    "actions": [{
        ... irrelevant
    }],
    "data": {
        "foos": [{
            "id": "test",
            "name": "test"
        }],
        "meta": {
            "total": 1
        }
    }
}

Foo's model has lots of properties, including name, thumbnailURI, etc.

When I try to use in my template, the property is undefined; I would have expected the store to fetch the model for foo/test, since it's missing the image property, but it doesn't. What am I supposed to do to tell Ember -- hey, that list of items from the server didn't get all of the properties you need; go ask the server for that data for each item via /api/foo/test, /api/foo/test2, etc.




Ember Store Push to Model within Model

I have a relationship setup between my models like so...

A {
 a1: undefined,
 a2: undefined,
 B: {
    Cs: [{}],
    Ds: []
 }

A contains basic attributes, and has a model B that belongsTo it. Model B hasMany Cs and hasMany Ds.

Typically you push to the store doing something like this, and it would update the model A in store to have a1 = 'blue'.

store.push({
  id: 0,
  type: 'A',
  a1: 'blue'
}

How can I push to the store to update a specific item in Cs, or Ds?




Ember inline if gives error TypeError: options.template is undefined

If I do


   
     <li class="active"><a href="#"></a></li>
   
     <li><a href="#"></a></li>
   
 

It works well, but it is too repetitive...

I wanna make an inline if like this:


    <li ><a href="#"></a></li>


But this gives the following error:

TypeError: options.template is undefined

Which I couldn't find anywhere. The closest topic I found was this one, but it is not what I want...

My eq helper is:

import Ember from 'ember';
const eq = (params) => params[0] === params[1];
export default Ember.Helper.helper(eq);




EmberJS Second level of service are not injected when calling from template

When calling a service function from a template e.g. onClick=, the services which should be injected into myFirstLevel stay undefined.

The call through a component action is working.

<button onClick=>Hello Service</button>
<button onClick=>Hello Action</button>


App = Ember.Application.create();

App.MyFirstLevelService = Ember.Service.extend({
  mySecondLevel: Ember.inject.service(),
  hello: function() {
    console.log('Hello first level');
    this.get('mySecondLevel').hello();
  }
});

App.MySecondLevelService = Ember.Service.extend({
  hello: function() {
    console.log('Hello second level');
  }
});

App.MyButtonComponent = Ember.Component.extend({
  myFirstLevel: Ember.inject.service(),

  actions: {
    hello:  function() {
      this.get('myFirstLevel').hello();
    }
  }
});

http://ift.tt/2cwwlfi




Ember-Simple-Auth / Ember-Simple-Auth-Token does not authorize findAll queries / Safari only

I've got a very weird issue here, maybe some of you have any pointers for me.

I'm using ESA and ESA-token (JWT) to authorize my API requests, using all the appropriate mixins (ApplicationRouteMixin, AuthenticatedRouteMixin etc.)

Developing in Chrome, I see no problem at all. However, when triggering a store.findAll (or an empty store.query, for that matter) query in Safari, the request does not get decorated with the appropriate bearer token. Curiously enough, a call to store.findRecord) passes without problems.

My versions are:

"ember-simple-auth": "1.0.1",
"ember-simple-auth-token": "1.1.1"

The applicable section in environment.js:

'ember-simple-auth' : {
      authenticationRoute: 'login',
      routeAfterAuthentication: 'clients',
      routeIfAlreadyAuthenticated: 'clients',
      authorizer: 'authorizer:token'
    },

  'ember-simple-auth-token': {
      refreshAccessTokens: true,
      timeFactor: 1000,
      refreshLeeway: 300, // Refresh the token 5 minutes (300s) before it expires.,
      identificationField: 'username',
      passwordField: 'password'
  }

And in the application adapter:

authorizer: 'authorizer:token'

enter image description here enter image description here

Now I've also step-by-step debugged this, and what's even more weird, the authorization header is present at the beginning, but gets erased at some point in the wrapping function.

Any pointers would be very appreciated




Is it advisable to modify the resolver to achieve a pod / nonpod hybrid?

Our API makes it necessary to always have the model/serializer/adapter trio for each and every model. The non-pod structure makes this a pain to chase down those files for a single feature. The PODS feature is a real daysaver for this. However, it tweaks me a little bit to have UI stuff (routes, templates, controllers,etc) commingle with data-ish stuff (models, adapters, serializers).

We have discovered that we can extend the resolver and have our cake and eat it too. We have successfully done this in a laboratory setting:

app\pods{ui-feature-name}\route.js (and template.hbs, etc.) app\data{model-name}\model.js (and serializer.js, etc).

This isn't a question of "Can I do this?", but more of "Should I do this?" Before we embark on a nice day or two of refactoring, I'd like to know if I have a loaded gun pointed at my foot.




Do we have abstract equality check in ember handlebar?

In ember handlebar, we are allowed to use the strict helper

eq  if (a === b)  or     ex:  1 === '1'     false

I need to check the abstract equality which is
1 == '1'      true

How can i achieve that in .hbs file ? with helper ?




Ember Multitple belongTo relationships not working with JSONAPI

I have the following json api document:

{
  "data": [
    {
      "type": "haves",
      "id": "2708f443-0857-4ae9-9935-9aa4b4e9f721",
      "attributes": {
        "quantity": 1
      },
      "relationships": {
        "card": {
          "data": {
            "type": "cards",
            "id": "3be08f31-3361-404c-9977-23535ed837f3"
          }
        }
      }
    }
  ],
  "included": [
    {
      "type": "cards",
      "id": "3be08f31-3361-404c-9977-23535ed837f3",
      "attributes": {
        "name": "Name"
      },
      "relationships": {
        "set": {
          "data": {
            "type": "sets",
            "id": "0fec70de-02e0-4646-bdcf-f86acea90d23"
          }
        }
      }
    },
    {
      "type": "sets",
      "id": "0fec70de-02e0-4646-bdcf-f86acea90d23",
      "attributes": {
        "name": "Name"
      }
    }
  ]
}

With the following ember models:

// app/models/have.js
export default DS.Model.extend({
  quantity: DS.attr('number'),
  minPrice: DS.attr('number'),
  account: DS.belongsTo('account'),
  card: DS.belongsTo('card')
});

// app/models/set.js
export default DS.Model.extend({
  name: DS.attr('string'),
  cards: DS.hasMany('card')
});

// app/models/card.js
export default DS.Model.extend({
  name: DS.attr('string'),
  set: DS.belongsTo('set'),
  haves: DS.hasMany('have')
});

And a custom inflector rule:

inflector.irregular('have', 'haves');

When I load the json document with this structure though, I can't seem to do something like have.card.set.name in my template when I iterate this jsonapi document. I'm guessing my jsonapi structure is incorrect. What am I missing? I don't get any errors in my chrome console or in the ember server running. When I load Ember Inspector, I see the set model under Data.




Use parent properties in nested component in Ember

I have a component inside which I am nesting component. I want this input to use parent properties (id, placeholder, etc.). Is there any way of doing this?




mercredi 21 septembre 2016

Simplest way to take an Ember application down for maintenance

I have an Ember.js application being served from S3, uploaded using ember-cli-deploy. It has a Rails backend that I take down for maintenance from time to time. During this time I would like my ember application to redirect every route to an "undergoing maintenance" page.

Can I do this within the Ember framework, or am I better off temporarily replacing index.html on S3 with a static file?




Ember Data mix of find(), query(), findAll()

If I do

this.get('store').findAll('model')

It will make a request to /models and it will expect for an array. On the other hand, if I do

this.get('store').find('model', my_id)

It will make a request to /models/my_id and it will expect for one record of my model. The method .query() will basically do a GET request with the parameters I pass like

this.get('store').find('model', {something: 'foo'})

It will make a request to /models?something=foo.

My question is the following:

Can I make something which mixes all the three methods above? I want to make a request to the path /models/foo and I want to expect one array.

I did .find('model', params.something), but it threw an assert exception saying that it was expecting for one model and not one array.




Ckeditor usage in Ember

I want to use CKEditor with my Ember app. I am 100% a n00b with Ember, but I'm getting there.

I have tried my darndest to figure this out, but I've gotten nowhere :(

I have tried to use ember-ckeditor. This ended up with the editor throwing a bunch of net::ERR_NAME_NOT_RESOLVED errors for things such as config.js and other "assets" it expected to find in the assets folder.

I have tried ember-cli-ckeditor. Same exact issues as above.

These two addons have pretty lame documentation. For example, I have no idea how provide a custom config file, CSS, etc. Or what if I want to use CkFinder?

The two above addons also throw some depreciated warnings when loading up the server, but I disgress....

I finally tried to manually include ckeditor v4.5.6 in the vendor folder. I then included in ember-cli-build.js as such: app.import('vendor/ckeditor/ckeditor.js'); I'm not sure if I'm correct in doing this, and if so, how do I include use the editor plugin within my controller or component?

CKEDITOR.replace("content"); as per usual outside of Ember?

Please school me!




Ember index page stays when transitioning to other pages

I'm making an Ember.js app. The index page contains an image and some text, when I navigate to other pages the image and text from the home page stay on the page. This image and text are located inside

 <script type='text/x-handlebars' data-template-name='index'>

Here is the page http://ift.tt/2djOLSi If you reload the page you've transitioned to it looks normal. eg. http://ift.tt/2cRJ8bn

Thanks




Handle long time sorting in ag-grid (pure JS)

I am working with a big amount of data (1M - 5M), and rows in the grid should be groupable, sortable, and filterable. As ag-grid can populate table with data quickly enough, I use in-memory row model to satisfy requirements.

However, when I click column in order to sort all rows by this column, it takes some time to do this. Moreover, sequential clicking on columns while rows are still being sorted may crash grid as well as browser application.

Are there any ways to prevent user from clicking on columns (disable sorting, show loading overlay, or something like this)?

I am trying to use beforeSortChanged and afterSortChanged events to show overlay or modify DOM elements (to make grid a little bit grey and show loading circle), but it doesn't work properly: beforeSortChanged event handler seems to be stuck for a moment and then only executed.

Ag-grid is used inside Ember framework as a component.




Passing data from controller to model in emberjs

I have an controller where i get the value from the hbs which sends me the selected country value. I need this selected country in the model to compute and return back some results back to the hbs. How set this value in controller and get it in the model so i can compute using that value.




ember-moment shows "Invalid date" (only in Safari, both desktop and mobile)

ember-moment shows "Invalid date" (only in Safari, both desktop and mobile)



P.S.: Firefox, Chrome works fine..




Ember testing: injecting controller in a component test

I'm facing some issue with one of my component integration test. To explain briefly, my component uses a sub-component which uses some ember-can ability to select options to display.

The abilities are relying on a controller to know which is the current project and so what are the permissions of the user. So in our app.js file, we have something like that:

application.inject('ability', 'projectController', 'controller:project');

Of course, when doing the integration test for the component, the ability is unable to find the controller, nor the project and so always consider the user does not have the required permission.

I tried so far stuff like that:

this.register('controller:project', Ember.Object.create({
  project: this.project
}));
this.inject.controller('controller:project', {as: 'projectController'});

But this does not have any impact on the abilities (the test documentation shows how to inject services but is pretty poor on the controller injection).

Does anyone have a good idea on how to solve that issue ?

Best regards, Vincent




Ember unable to observe controller property

In my Ember app, I want to observe a controller property change.

Below is my code to set the mode;

var togglerModel = this.controllerFor(this.routeName).Vmtoggler[0];
this.controllerFor(this.routeName).set('togglerModel', togglerModel);

modelChanged: function() {  
            debugger;
    }.observes('togglerModel.model'),

My togglerModel is an object that looks like

{
label: 'XYZ',
model: [{
id: '123',
selectedValue: 'abc'
},{
id: '456',
selectedValue: 'def'
}]
}

The individual model array elements actually correspond to some form elements (text box, dropdown, etc) and the model.selectedValue does get updated on change

But my question is my "modelChanged" property does not get invoked as I change any of the form elements.

What am I doing wrong here?