lundi 31 juillet 2017

Blank screen instead of welcome page in new app

I'm just learning ember, so sorry if this is a stupid question. I've not added any logic to my app yet, but I'm already having difficulty getting the ember welcome screen. Instead of the ember welcome screen, I get a blank screen but with no errors in the console or the browser. I've isolated the problem to this specific combination of packages (see package.json) but I'm not sure which one is causing the issue. No application code has been added; if you use this package.json file and run npm install, you should also find that the welcome screen fails to load.

package.json:

{
  "name": "against-humanity",
  "version": "0.0.0",
  "description": "",
  "license": "MIT",
  "author": "djcf",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "repository": "",
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test"
  },
  "devDependencies": {
    "ember-ajax": "^3.0.0",
    "ember-cli": "~2.14.1",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-babel": "^6.3.0",
    "ember-cli-dependency-checker": "^1.3.0",
    "ember-cli-emberscript": "0.0.18",
    "ember-cli-emblem": "^0.9.0",
    "ember-cli-eslint": "^3.0.0",
    "ember-cli-htmlbars": "^2.0.1",
    "ember-cli-htmlbars-inline-precompile": "^0.4.3",
    "ember-cli-inject-live-reload": "^1.4.1",
    "ember-cli-less": "^1.5.4",
    "ember-cli-qunit": "^4.0.0",
    "ember-cli-shims": "^1.1.0",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "~2.14.3",
    "ember-export-application-global": "^2.0.0",
    "ember-load-initializers": "^1.0.0",
    "ember-resolver": "^4.0.0",
    "ember-source": "~2.14.1",
    "ember-welcome-page": "^3.0.0",
    "loader.js": "^4.2.3"
  },
  "engines": {
    "node": "^4.5 || 6.* || >= 7.*"
  },
  "private": true
}




Ember testing with click and drag for SVG

For writing acceptance tests for clicking and dragging elements as seen in the link here, I have found this resource github jQuery-ui online. Are there any better options?




Ember LiveReload inside Kubernetes Pod

I'm setting up a local Kubernetes cluster using Minikube and Xhyve as the VM driver on Mac OS.

I have gotten volume mounting from my laptop to the pod working (when I bash into my pod with kubectl exec -it my-pod -- /bin/bash I can see the files inside the pod update with my filesystem), but the Ember app running inside the pod never reflects the file changes. I have to destroy the deployment, rebuild, and redeploy in order to see file changes take effect.

In my Dockerfile I EXPOSE port 42000 as the live reload port and start the server using a CMD which simply runs ember server --host 0.0.0.0 --live-reload-port 42000.

Is there some trick I'm missing to get the LiveReload feature working with Kubernetes? Thanks in advance.




How do I use a service property in a route?

I have a service that handles user authentication and gets the user data via a model. One of the pieces of data that it fetches is a date for the start of a dietary program. I want to use this date to calculate a number: the number of days since the start of the program, so I can use that number to query a different model that pulls content from a CMS.

I haven't been able to access that number anywhere other than a template.

This is the Controller for Dashboard

import Ember from 'ember';

export default Ember.Controller.extend({

  authManager: Ember.inject.service('session'),
    });

This is the template


  You are on a cleanse that starts 

  
  You are not on a cleanse.


All of the above code works, but when I try something like this in the controller:

  activeCleanse: Ember.computed( function(){
    return this.get('authManager.currentUser').then( (user) => {
    return user.cleanse_active;
    }.bind(this))
  }),

  startDate: Ember.computed( function(){
    return this.get('authManager.currentUser').then( (user) => {
    return user.cleanse_start;
    }.bind(this))
  })

And replace the template with:


  You are on a cleanse that starts 
  
  You are not on a cleanse.


It doesn't respond to activeCleanse being false (the template only seems to be checking for its existence) and the date tag only shows [object Object].

I am actually trying to get the date in the controller so I can manipulate it to pass as one of the parameters to the dashboard route, which gets a model based on the specific day:

The Dashboard Route

import Ember from 'ember';

export default Ember.Route.extend({

  model() {
    return this.get('store').queryRecord('cleanse-post', {
      filter: {
        tag: 'day-1'
        }
      });
    },

});

I want to be able to dynamically set the tag for the filter based on the calculation for the date.

Any help would be appreciated. I feel like I've been going in circles with this and I have no idea what to try.




Not retrieving any information from model using Ember.js using query() method

I'm trying to learn Ember.js by building a web application using the framework for the front end and node.js for the backend as well as mongoDB as a database.

I am using/attempting to use the url to feed in a parameter id and then query on that id.

I am having trouble grabbing the information from my model. My query works fine when I am using findAll(). However, when I switch to find() or query() I can't retrieve any results.

All the documentation I have looked at use different syntax that I have tried but none have worked.

I would greatly appreciate any hint or input. Thank you.

app/router.js

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

app/routes/stock.js

    export default Ember.Route.extend({
       model: function(params) {
         this.store.query('stock', {filter:{id : params.stock_id}}).then(function(stock){return stock.get('firstObject')});
       }
    });

app/models/stock.js

    export default DS.Model.extend({
       Symbol: DS.attr('string'),
       Name: DS.attr('string'),
       LastSale: DS.attr('string'),
       MarketCap: DS.attr('string'),
       IPOyear: DS.attr('string'),
       Industry: DS.attr('string')
    });

app/serializers/stock.js

    export default DS.RESTSerializer.extend({
       primaryKey: '_id',
       serializeId: function(id) {
          return id.toString();
       }
    });

app/templates/stock.hbs

   
   <h3></h3>
   




Suggest type of an object based on a given title

I am working on an Ember application that deals with geospatial data processing. Part of this project is importing a JSON object that describes a data layer which contains fields corresponding to data entries. For example, I suppose I am importing a data layer called "Laundry Facilities"; the JSON will look something like this:

 {
      key: "laundryFacilities",
      label: "Laundry Facilities",
      fields: [
        {
          "label": "Name of Facility",
          "key": "name",
        },
        {
          "label": "Number of Dryers",
          "key": "numberDryers",
        }
      ]
 }

At some point in my data import workflow, the user must specify a type for each field. For example, the type for "Name of Facility" would be a string, and the type for "Number of Dryers" would be an integer. I'd like to be able to provide a suggested type to the user based off of the label or key attribute rather than forcing them to specify the type for every field. Is there any kind of algorithm, package, framework, etc. that provides functionality for guessing a data type based off of something qualitative like a label describing the data field? Or does anyone know of another way I could implement this? I know not to expect 100% accuracy but even a rough type guess would be extremely helpful. Bonus points if it's an Ember addon.




dimanche 30 juillet 2017

Setting the title of the page using the model from the route

I’m a bit puzzled about setting the title element from my router using the ember-cli-document-title add-on. It works just fine if I pass it a function or a string, but I’m trying to access the current model via modelFor.

It works when the page first loads, but then, when I transition to another route, it changes to ‘undefined’. If I go to a previously visited route the value is populated. It appears that at the time of display, the value is not yet populated. How can I wait for DS to have the attributes on my model instance before trying to assign it to the title?

I had attempted calling reload() on my model, and then returning the resulting promise instead, ember-cli-document-title doesn't seem to like promises in the title attribute.

export default Ember.Route.extend({
  title: function() {
    let model = this.modelFor(this.routeName)
    let title = model.get('title')
    return `${title} | Some More Text`
  }
}




Cannot convert object to primitive value at Array.toString (native) when populating ember-power-select with array of objects generated dynamically

I need to populate a power-select with objects from the store, but I can only get the options displayed with the hard coded arraymyOptions. I tried to generate myOption2 dynamically, and apparently got the same output as myOptions, but it throws an error:

ember.debug.js:19845 Uncaught TypeError: Cannot convert object to primitive value
at Array.toString (native)
at Object.addListener (http://localhost:4200/assets/vendor.js:30682:88)
at Object.addObserver (http://localhost:4200/assets/vendor.js:34026:23)
at Array.addObserver (http://localhost:4200/assets/vendor.js:47679:27)
at Class.updateOptions (http://localhost:4200/assets/vendor.js:88968:17)
at invoke (http://localhost:4200/assets/vendor.js:11825:16)
at Queue.flush (http://localhost:4200/assets/vendor.js:11891:11)
at DeferredActionQueues.flush (http://localhost:4200/assets/vendor.js:11699:17)
at Backburner.end (http://localhost:4200/assets/vendor.js:11013:25)
at Backburner.run (http://localhost:4200/assets/vendor.js:11135:18)


function addListener(obj, eventName, target, method, once) {
_emberMetalDebug.assert('You must pass at least an object and event name to Ember.addListener', !!obj && !!eventName);
_emberMetalDebug.deprecate('didInitAttrs called in ' + (obj && obj.toString && obj.toString()) + '.', eventName !== 'didInitAttrs', {
  id: 'ember-views.did-init-attrs',
  until: '3.0.0',
  url: 'http://ift.tt/2hdVPlZ'
});


//template.hbs


  


//component.js

myOptions: [
  { id: 1, name: 'First Option' },
  { id: 2, name: 'Second Option' }
],

myOptions2: [],

didReceiveAttrs() {
  this.get('model.content').forEach((option) => {
    this.get('myOptions2').push(option._data);
  });
}


//#=> myOptions: [{id: 1, name: 'First Option'},{"id":2,"name":"Second Option"}]
//#=> myOptions2 [{id: 1, name: 'First Option'},{"id":2,"name":"Second Option"}]





samedi 29 juillet 2017

EmberJS menu visibility based off of width

So I am trying to figure out a problem that I am having with my menu in mobile vs desktop. So I created a button that can toggle the visibility of the menu, but the behavior of the menu can also change based off the size of the browser window.

While in desktop the menu should be visible While in mobile the menu should be hidden

Here is a link to some sample code of what I have. If you load it up with the window wide enough, the menu will be displayed. Click the button it hides it, click it again and it shows it.

http://ift.tt/2va3c3j




Ember add-ons: what is the recommended way to handle input data?

When writing a (public) ember add-on; what is the recommended format for input data coming from the main ember app? Do you expect ember-data objects, or a simpler data model such as an array for example?

If the add-on accepts ember data objects; any modifications to this data can be persisted to the backend easily, but I'm certain that not everyone uses ember-data. If you don't use ember-data, converting a data model into ember-data's formats is madness.

On the other hand, if the add-on accepts an array (for example) as the input data, then the main ember app using ember-data has to extract the data into this array format for the add-on to use.

I haven't seen any guidance in the Ember docs or elsewhere in the web that I could find.




Issue with ember.js when querying for multiple records

I have no issues using store.findRecord() and store.findAll() but when I try and use store.query() it always returns everything in the model, not a subset like I'm expecting.

For example, I have 100 records in my person model and when I use the example on the ember.js website in my route:


    model: function() {
        this.get('store').query('person', {
          filter: {
            name: 'Peter'
          }
        }).then(function(peters) {
          return peters
        });
    }

All 100 records are returned to my template instead of only those with the name 'Peter'.

Can someone tell me what I'm doing wrong?

Thank you.




EmberJS : Customizing adapter host and port

After few tutorial reading on emberJS documents, and couple tryout of emberJS, I currently are stuck at calling custom JAVA API,

Right now I had startup a java server on apache to allow public API call, the host and port are:

host: 'http://127.0.0.1:8080'

i had changed my adaptor followed with the document :

items.js

export default DS.JSONAPIAdapter.extend({
    host: 'http://127.0.0.1:8080'
});

but I still getting the error on chrome inspector

GET http://localhost:4200/items 404 (Not Found)

I am using 2.13 version of emberjs, please guide me what am i go wrong, any helps are appreciated, thanks




vendredi 28 juillet 2017

Ember data - send only properties that have values

I have a model with many attributes and certain associations. Most of them may or may not be null. I am trying to do an Ajax call with this model as a payload, and certain properties can be null.

I want to send only the properties that have values, and not null, including associations.

Is it possible? Kindly let me know if it is possible.

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




Ember - Access Parent Model in a Child route Controller

I want to use both a parent route's model, and the child route's model from the child route. Not sure the "Ember way" to go about this.

To be a little more specific:

The Parent

The parent route has a group model and has the dynamic route groups/:group_id

The Child

Each group works on several units. In the template for the group route above, the list of units is displayed, each with a link to the child route in question, groups/:group_id/unit/:unit_id. The model for this route is the unit, set by passing the unit as an argument in the link-to helper in the parent route template.

The problem is that, in addition to the unit model, I also need to be able to access the parent model - the group, from within the groups/:group_id/unit/:unit_id route.

I might set-up an hash to return both models in the child route.js, but the model hook wouldn't be executed if the model is passed via the link-to. Stuck on exactly how to do this.

Thanks




how to pass parameters between hbs files in ember

i have created an application using ember.js. here i couldn't get the parameter value passed from tasks.hbs to subtasks.hbs.how could i get parameter value passed from tasks.hbs in subtasks.hbs and print it in subtasks.hbs?

app/templates/tasks.hbs:


<h1>Tasks</h1>

    <div class="well">
        <h4></h4>
        <small>Created: </small><br>
        <small>Due: </small>
        <h5>Priority: </h5>
        <p></p>
        <button  class="btn btn-danger">Delete</button><hr>

        <button  class="btn btn-primary">Create SubTask</button>

        <button class="btn btn-primary">Show SubTasks</button>
    </div>


app/templates/subtasks.hbs:


<h1>SubTasks</h1>
<h2></h2>

<h1></h1>

    <div class="well">
        <h4></h4>
        <small>Created: </small><br>
        <small>Due: </small>
        <h5>Priority: </h5>
        <p></p>
        <button  class="btn btn-danger">Delete</button>
    </div>



app/routes/tasks.js:

import Ember from 'ember';

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

app/routes/subtasks.js:

import Ember from 'ember';

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

router.js:

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

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

Router.map(function() {
  this.resource('tasks', function() {
    this.route('new');
    this.route('edit', {path: '/edit/:task_id'});
  });
  this.route('subtasks', {path: '/subtasks/:task_id'}, function() {
    this.route('subnew', {path: '/subnew/:task_id'});
    this.route('subedit', {path: '/subedit/:subtask_id'});
  });
});

export default Router;




Simulate Cntrl/Cmd + Delete keyevent combination in Ember

In the async test, I have keydown and keyup combinations, trying to simulate Cntrl + Delete on "selector name".

await triggerEvent(<selector name>, "keydown", {ctrlKey: true, keyCode: 46});
await triggerEvent(<selector name>, "keyup", {ctrlKey: false, keyCode: 46});




jeudi 27 juillet 2017

ember must call super method from component error

i just extending my ember component with my custom mixins class but unfortunately my log said an error

    Assertion Failed: You must call `this._super(...arguments);` when overriding `init` on a framework object. Please update <cahyowhy-mini-blog@component:post-item::ember395> to call `this._super(...arguments);` from `init`.
Error

but in my component(post-item) i've been declared my init method

import Ember from 'ember';
import BaseController from '../controllers/base-controller';
import Likepost from '../models/likepost';

export default Ember.Component.extend(BaseController, {
  posts: "",
  applyLayout(){
    Ember.$(document).ready(function () {
      let $grid = Ember.$('#post-container').imagesLoaded(function () {
        $grid.masonry({
          itemSelector: '.post-item',
          percentPosition: true,
          columnWidth: '.post-item',
        });
      });
    });
  },
  init(){
    this._super(...arguments);
  },
..... more code

and this is my basecontroller class

import Ember from 'ember';

export default Ember.Mixin.create({
  init(){
    //this._super(...arguments); //nek ra dipanggil neng component post item ra keno :(
    let afterRenderExist = this.afterRender !== undefined && typeof this.afterRender === "function";
    if (this.applicationRoute.documentReady && afterRenderExist) {
      Ember.run.schedule('afterRender', this, function () {
        this.afterRender();
      });
    } else if (afterRenderExist) {
      this.applicationRoute.on('onDocumentReady', this, function () {
        this.afterRender();
      });
    }
  },

but when i try to uncomment this syntax this._super(...arguments); in my base controller. the error is gone...

can anyone solve this :( ...




Multiple Promises in Ember won't resolve in the template

I'm stuck trying to return the value of a bunch of promises.

To explain the situation: there are 4 models - the students in a group have a score for each objective.

So I've made a component into which I pass an objective and the group. The component then handles the requests to the store to look up each student's score for that objective, and return the average.

The code seems to work, the console.logs give me exactly what I want, right up to the end, but the promises won't resolve into the template - I get the { object Object }, which I believe is the unresolved promise.

Something I'm missing here? Is there an extra step needed when waiting for multiple promises to resolve?

I appreciate this is a little specific, when I understand the answer I'll try and rephrase the question.

Component Code:

    averageScore: Ember.computed(function(){
    var students = this.get('group.students');
    var objective = this.get('objective');
    var store = this.get('store');
    var _this = this;

    // Create an array of promises of each student's scores
    var promises = [];
    students.forEach((student) => {
        var studentId = student.get('id');
        var objectiveId = objective.get('id');
        var newPromise = store.queryRecord('snapscore', { 'student' : studentId, 'objective': objectiveId });
        promises.pushObject(newPromise);
    });
    // When promises resolve, find and return the average
    return Ember.RSVP.allSettled(promises).then(function(scores){
        let scoreTotal = 0;
        let scoreCount = scores.length;
        console.log("Score count is " + scoreCount);
        scores.forEach((score)=>{
            console.log("Student's score is " + score.value.get('score'));
            scoreTotal = scoreTotal + score.value.get('score');
        });
        console.log("ScoreTotal is " + scoreTotal);
        var average = scoreTotal/scoreCount;
        console.log(average);
        console.log(typeof(average));
        return average;
    });
}),

The component's template then simply returns averageScore.

Thanks




Save nested models using Ember Data

I have two models in Ember:

Collection

export default DS.Model.extend({
    name: DS.attr(),
    description: DS.attr(),
    items: DS.hasMany('collection-item')

});

Collection Item

export default DS.Model.extend({
    date: DS.attr(),
    volume: DS.attr(),
    sequenceNumber: DS.attr()
});

I want to save the collection items inside the 'items' attribute of the collection, like MongoDB:

[{
    "name": "First Collection",
    "description": "This is my first collection",
    "items": [
        {
            "date": "2017-07-26",
            "volume": "1",
            "sequenceNumber": "1"
        },
        {
            "date": "2017-07-27",
            "volume": "1",
            "sequenceNumber": "2"
        }
    ]
},
{
    "name": "Second Collection",
    "description": "This is my second collection",
    "items": [
        {
            "date": "2017-07-26",
            "volume": "1",
            "sequenceNumber": "1"
        },
        {
            "date": "2017-07-27",
            "volume": "1",
            "sequenceNumber": "2"
        }
    ]
}]

I have read something about serializers, but I don't get the point ;) Can someone give me a hint?

BTW, I'm using Firebase (emberfire) for now, but I'm going to build my own API in future.




get data from store return undefined in ember

I have some problem with get data from storage.

Isset model orders:

import DS from 'ember-data';

export default DS.Model.extend({
   test: DS.hasMany('dealer-status'),
});

adapter (its is test data). I havn't normolize responce and i add params to data for normalize. It is implementation will be in serialize :

export default DS.JSONAPIAdapter.extend({
service:  Ember.inject.service('admin.auth'),
query(store, type, query) {

    var service = this.get('service');
    return new Ember.RSVP.Promise(function (resolve, reject) {

        service.fetch(query).subscribe(
            res => {

                var data = {
                    "data": [{
                        "type": "user",
                        "id": "1",
                        "attributes": {
                            test: 'test'

                        }
                    }]
                };
                resolve(data);
            },
            err => {
                reject(err);
            });
    });
}
});

The router:

model() {

    return   this.get('store').query('orders', {}).then(res => {
        console.log(res.get('test')); //undefined
        console.log(res.objectsAt(0)); //undefined

    })

In router I find by query, but i can't get param test. In Promise res.get('test') return undefined.

Why i get undefined in promise? How fix it?




jQuery [object Object] is not a valid selector

I am trying to select tree-node element with children and first child but it is not a valid selector.

<g class="nodes">
   <g class="tree-node enter" id="tree-node-cdl3c5he">
      <g class="node-group">
        <circle class="node-shape" r="80"></circle>
        <g class="node-label-group" transform="translate(-80,-80)">
        <foreignObject class="node-content-container" width="160" height="160">
        <div class="node-content">
         <div class="inner">
          <div class="node-label" data-test-id="node-label-new-part">New Part</div>
        </div></div></foreignObject></g><g class="root-group" transform="translate(0,-80)"><circle class="root-shape" r="15"></circle></g>
</g>
</g>
</g>

Using first child:

$('.nodes > .tree-node:first-child')

Ember test:

await click($('.nodes > .tree-node:first-child'));

Error: Failed to execute 'querySelector' on 'Document': '#ember-testing [object Object]' is not a valid selector.




Ember setup issue ETIMEDOUT error

I am running the following commands to setup my Ember project;

npm install
bower --force install
ember generate my-addon

While setting up, I am getting some errors as below;

installing my-addon
install bower packages ember, jquery-ui, jqwidgets, moment, blueimp-file-upload, d3, nvd3, jquery-cookie
cached
cached
cached
cached
cached
cached
cached
cached
cached
new version for
cached
progress received 2.1MB of 3.8MB downloaded, 55%
progress received 2.3MB of 3.8MB downloaded, 62%
progress received 2.6MB of 3.8MB downloaded, 69%
progress received 2.9MB of 3.8MB downloaded, 77%
progress received 3.2MB of 3.8MB downloaded, 85%
progress received 3.5MB of 3.8MB downloaded, 93%
{ [Error: connect ETIMEDOUT 216.58.196.100:443]
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '216.58.196.100',
port: 443 }
resolved
Installed browser packages via Bower.
Installed my-addon - jQWidgets
Installed my-addon images
Installed my-addon assets to addon dummy app

Could you pls help me with the same




Using ember-cp-validations across multi-page form

I have an order model that I’m collecting data for over a multi-page form. I’ve created some validations like this:

const Validations = buildValidations({
  // these should only be used when we’re on checkout.info route
  name: validator('presence', true),
  email: [
    validator('presence', true),
    validator('format', { type: 'email' })
  ],
  // these should only be used when we’re on checkout.shipping route
  address1: validator('presence', true),
  address2: validator('presence', true),
  city: validator('presence', true),
});

My model is set up to use them like this:

export default Model.extend(Validations, {
  // model set-up in here
})

What I’d like to happen is for it to only validate name and email when I’m on checkout.info and to validate address1, address2 and city when I’m on checkout.shipping.

How might I go about achieving this?




mercredi 26 juillet 2017

Material Design Lite: Dynamic Drawer Layout not showing with upgradeElement

application.hbs

<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
  
   //Auth is a service
    
  
  <main class="mdl-layout__content">
    <div class="page-content">
      
    </div>
  </main>
</div>

navigation-drawer.hbs

<span class="mdl-layout-title">Title</span>
<nav class="mdl-navigation">
  
    <span>Hi </span>
    <button type="button" name="logout">Logout</button>
  
    Login
  
</nav>

navigation-drawer.js

import Ember from 'ember';
/* globals componentHandler */

export default Ember.Component.extend({
  Auth: Ember.inject.service('Auth'),

  init() {
    this._super(...arguments);
    if(this.get('Auth').authenticated) {
      this.set('name', 'lokesh');
    }
  },

  didInsertElement () {
    this._super(...arguments);
    [].forEach.call(this.$(), function (el) {
        componentHandler.upgradeElement(el);
      });
  }
});

navigation-bar.hbs

<div class="mdl-layout__header-row">
  <span class="mdl-layout-title">Title</span>
  <div class="mdl-layout-spacer"></div>
  <nav class="mdl-navigation mdl-layout--large-screen-only">
    
      <button type="button" name="logout" >Logout</button>
    
      Login
    
  </nav>
</div>

navigation-bar.js

import Ember from 'ember';

export default Ember.Component.extend({
  Auth: Ember.inject.service('Auth'),
  actions: {
    logout() {
      this.get('Auth').logout();
    }
  }
});

Login route

import Ember from 'ember';

export default Ember.Route.extend({
  Auth: Ember.inject.service('Auth'),

  actions: {
    authenticate() {
      this.get('Auth').login();
      this.transitionTo('/');
    }
  }
});

<h3>Login Page</h3>
<button type="button" name="button" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored">Login</button>

What i am trying to do? I have a application route which has a navigation-bar displayed at all time and a navigation-drawer which should be displayed only if the user is logged in. so i wrote a condition to hide navigation-drawer. once user click login button in login route i am updating the AUTH service which is used across all the files. once user click login, he will routed to application route again. This time the condition will be true and navigation-drawer should show up. i checked in DOM. it has drawer. But the drawer button is not showing. When i refresh the page, it showed up. so i understood, material is acting on those components only during the onload time. However i understood that componentHandler.upgradeElement() is useful in case dynamic compoenents. i tried it in navigation-drawer.js. But it didn't work. Where i went wrong?




Ember.js 2, transitionTo using multiple synamic segments in first level route

I'm using Ember >= 2.13.x.

I need to use transitionTo from a route action to go in another route.

Here is the demo ember-twiddle: http://ift.tt/2uBQU1r

I have this situation:

router.json:

Router.map(function() {
  this.route('home', {path: '/'});
  this.route('categories', {path: 'categories'});
  this.route('category', {path: ':category_id'});
  this.route('posts', {path: 'posts'});
  this.route('post', {path: ':category_id/:post_id'}); //I have multiple synamic segments in here
});

routes/application.js:

actions: {
    goToPost() {
        let post = this.store.findRecord('post', 1);
        this.transitionTo('post', post);
    }
}

routes/post.js:

model(params) {
    return this.store.findRecord('post', params.id);
},

serialize(model) {
    console.log('model in serialize():', model);
    return { category_id: model.get('category.id'), post_id: model.id };
}

templates/application.hbs:

<button type="button" >GoToPost with action (transitionTo)</button>

So when I click everything works as expected.

I fetch the model in application action and then I use this.transitionTo('post', post);.

In my post route then I have serialize() which, I read now, is using for URL composition when dynamic segments are present.

My question: I'm using it the right way?

Why I cannot use something like this: this.transitionTo('post', post.category.id, post.id); and let model() in post route fetch the model (from DB or store)?

I also tried to use this.transitionTo('post', {category_id: post.category.id, post_id: post.id}); but obviously the post route model() doesn't load anything because it really thinks the object is already there.

So, I can fix this problem with serialize() method only. Is it the right way?




How to write test case using jquery in ember framework

How to trigger the drag event and drop event for unit test cases with assertion jquery in ember




How do I use Ember in the front-end and Java in the back-end for web apps development?

I am new to web application development. My task is to make a web app that uses ember framework in front-end and java in back-end. I am not going to use DB for storing data. How to connect ember and java programs?




Positing JSON to Rails API from Ember JS

I'm trying to post data from my Ember app to my Rails API for a blog application I'm playing with.

I'm having a few issues, which I think each stem from my initial problem.

First of all, when I try to store the data from my inputs in Ember, I can't seem to store them in any variables. I've tried checking to see if I'm trying to access the values the wrong way but the documents I've been reading (Ember docs, and other stack overflow questions) lead me to believe I'm doing this correctly.

//new.js
import Ember from 'ember';
import DS from 'ember-data';

export default Ember.Route.extend({
    actions:{
        createPost(){
            var created_at = new Date();
            var user = this.store.findRecord('user', 1);
            var title = this.get('title');
            var body = this.get('body');
            console.log(title, body);
            // console.log(user);
            var post = this.store.createRecord('post', {
                title: title,
                body: body,
                created_at: created_at,
                user: user
            })

            post.save();
        }
    }
});

and

//new.hbs

<form>
<strong>Title</strong><br/>
<br/>
<strong>Body</strong><br/>
<br/>

<button type="submit" >Submit</button>
</form>

My output of title and body returns undefined.

Another issue I'm having is when I try post this data to my Rails API, I get a 422 error. It says that there is an unpermitted parameter (created_at) included, so I was wondering if there was a way to exclude parameters from my post request?

Thanks in advance.




How is selectedSection.savedItems computed property modified twice?

I am looping through saved items in my component template and I am getting the following error:

"Assertion Failed: You modified selectedSection.savedItems twice on <wc-app@model:plan-section::ember615:goal> in a single render. This was unreliable and slow in Ember 1.x and is no longer supported.

This is the code in the component template:



This is the savedItem computed property on the plan section model:

savedItems: Ember.computed('orderedItems.@each.isNew', function() {
    let itemsSaved = this.get('orderedItems').filter( (i) => !i.get('isNew')) || [];
    return itemsSaved;
  }),

When there is 1 item or more this problem does not happen but when there are 0 items it causes this error.

How is this computed property modified twice?




Ember yield multiple actions into component

I have a checkout-form component which has some actions like next, previous, submitForm and selectDate. Currently I’m only able to yield the selectDate action like this:


<div class='checkout-form'>
  
</div>

I’d like to be able to use my checkout-form component like this:


 
  
  
  


How would I go about yielding multiple actions to be used inside of my checkout-form.hbs?




mardi 25 juillet 2017

Ember "Action passed is null or undefined in (action)" error

I have an Ember component checkout-form that contains some logic for handling a checkout process. Here’s a simplified version of how I’m using it:



  Liquid error: wrong number of arguments (1 for 2)
    
  



Inside of my checkout-form.js component I have the following action:

selectDate(day) {
  this.set("startAt", day.get("serverString"))
}

And finally inside of my course-date.js component I have:

click () {
  const courseStart = this.get('courseStart')
  this.get('selectDate')(courseStart)
}

However, when running this code I get the error:

ember.debug.js:19818 Assertion Failed: Action passed is null or undefined in (action) from <site@controller:checkout/date::ember389>.

What am I missing here? I am passing the action into the course-date component and not sure why is it asking for a controller?




Rails ActionCable and Ember CLI app - Resource Bottlenecks

We've successfully implemented real time updates in our app using ActionCable in Rails and implemented the consumer as a client service in Ember CLI, but am looking for a better, less-expensive approach.

app/models/myobj.rb

has_many :child_objs

def after_commit
  ActionCable.server.broadcast("obj_#{self.id}", model: "myobj", id: self.id)

  self.child_objs.update_all foo: bar
end

app/models/child_obj.rb

belongs_to :myobj

def change_job
  self.job = 'foo'
  self.save
  ActionCable.server.broadcast("obj_#{self.myobj.id}", model: "child_obj", id: self.id)
end

frontend/app/services/stream.js Here we're taking the model and id data from the broadcast and using it to reload from the server.

import Ember from 'ember';

export default Ember.Service.extend({

  store: Ember.inject.service(),

  subscribe(visitId) {
    let store = this.get("store")
    MyActionCable.cable.subscriptions.create(
      {channel: "ObjChannel", id: objId}, {
        received(data) {
          store.findRecord(data.model, data.id, {reload: true});
        }
      }
    );
  },

});

This approach "works" but feels naïve and is resource intensive, hitting our server again for each update, which requires re-authenticating the request, grabbing data from the database, re-serializing the object (which could have additional database pulls), and sending it across the wire. This does in fact cause pool and throttling issues if the number of requests are high.

I'm thinking we could potentially send the model, id, and changeset (self.changes) in the Rails broadcast, and have the Ember side handle setting the appropriate model properties. Is this the correct approach, or is there something else anyone recommends?




Ember computed property adds comma

I created a computed property to concat two model properties together, and create a list of them. It initially worked like this, which results in a list like so: prop1-prop2, prop1-prop2

modelName: Ember.computed(
  return this.get('modelName').map((o) => {
    return o.get('prop1') + '-' + o.get('prop2');
  }).join(', ');
})

Then I changed it to this which results in the same list:

modelName: Ember.computed(
  this.get('modelName').map((o, i) => {
    return (i > 0 ? ' ' : '') + o.get('prop1') + '-' + o.get('prop2');
  });
})

My question is, where is the second computed property getting the comma to put in the comma-separated list? The initial code I tried was (i > 0 ? ', ' : '') but that was adding two commas. Can anyone explain?




Firebase Query using emberjs

I'm trying to sort a list of products from highest to lowest. The file json has been uploaded to firebase. TypeError: Cannot read property 'query' of undefined thats the error i'm receiving. My model is called "product" and it has the price attribute Here is the code:

sortHigh: ['product.price'],
actions:{
  sortHigh(product) {
    sortedProducts: Ember.computed.sort('product', 'sortHigh')
    return this.store.query('product').sortHigh('price');
  }
}

HTML Highest Price




lundi 24 juillet 2017

Detect if object is Ember Data or not

In Ember.js, I need to write a function that behaves differently depending on whether an object is an Ember Data object, or something else (Ember Object, plain JSON object, etc.). Is there a way to determine whether an object is Ember Data or not?

myfunction(myObject) {
    if(isEmberData(myObject)) {
        // Do stuff
    } else {
        // Do something else
    }
}




Ember: Call Action on Input Field on Focus Out with Argument

I'm creating a simple Todo App as I explore EmberJS v2.14. I want to build in a manual inline editing feature--the user will double-click on a todo line item text span, to open up a input field. The user will then edit the todo, which will be double bound to a backing object. And then when focus is lost, the app will re-close the input field back to the newly edited text.

The following fragment of code is inside an block helper, and it almost works.


   <span ></span>

  


Working Pieces

  • I can double click to go to editing mode (i.e. openForEditing() is correctly called with the write argument.)
  • the action handler closeForEditing() is correctly called when focus is lost from the input field.

Pieces Not Working

  • I don't know how to pass the todo object model as an argument, so that the closeForEditing() handler can do the appropriate work of setting isOpenForEdit back to false.

--

Q) How do I pass an argument to an action handler while working with the input helper?

Q) Is there a different approach I can take, to achieve my goal?




"Ember serve" command execution takes too much time on Win7

When "ember serve" is being executed, the command window remains as shown in the image: When "ember serve" is being executed, the command window remains as shown in the image

and I can not type in any command. Please give me an answer to solve this problem, thanks.




Binding Ember input component to control update on every key-press

I’m building an input that I want to be able to control and validate on the fly. I have a card-input component, which I’ve set up to use like this:



My card-input.hbs component looks like this:



And finally my card-input.js component file:

import Ember from 'ember';

export default Ember.Component.extend({

  classNames: ['checkout-form-group'],

  cardNumber: null,

  actions: {
    handleCardNumber (value) {
      // do some stuff with the value
      this.set('cardNumber', value)
    }
  }

});

Currently the value of the input is being set as cardNumber. Whenever I key-press on the card-input, I want to be able to control and set the cardNumber, which will then be updated back at the card-input.

Not even sure this is the best way to do things. Any help would be greatly appreciated.




Black rear camera when accessing web application from Android Phone/Tablet

I am making a web application in Ember.js I want to access one of the pages from a mobile device such as phone or tablet. To access the cameras I am using HTML5, Javascript and MediaDevice interface. Everything works as expected when I access the web application from my laptop. The web application can recognize and successfully load both cameras. (one at the time).

The problem starts when I want to access the same web page from the android phone/tablet. I am able to toggle between two cameras (front and rear) but the back camera is black (seems like switched off). If I start the camera separately (with native camera application) and then access the web page I am able to see the view from the rear camera. Strange thing is that the front camera works all the time no matter what. I assume there must be something wrong with the permissions that grant access to the back camera's feed.

Did anyone else had that problem before?




Can't access date in ember-pikaday onSelection from the outside

Has any of you experienced this using the ember-pikaday addon? I would like to set the date from the onSelection to be stored on the selectedDate but the context inside the onSelection is of the addon and not of the component itself. Is there a way I could store the value of date to one of the properties in my component?

My code is like this:

import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['schedule-nav-date-picker'],
  selectedDate: null,

  onSelection: function(date) {
    this.set('selectedDate', date);
    return date;
  },

  actions: {
    saveClicked () {
        this.sendAction('saveClicked', this.get('selectedDate'));
    },

    cancelClicked () {
      this.sendAction('cancelClicked');
    }

  }
});

And it gives me this error:

pikaday.js:165 Uncaught TypeError: this.get(...) is not a function
at Class.userSelectedDate (pikaday.js:165)
at Class.onPikadaySelect (pikaday.js:151)
at Backburner.run (ember.debug.js:224)
at Backburner.join (ember.debug.js:247)
at Function.run.join (ember.debug.js:15904)
at Pikaday.<anonymous> (ember.debug.js:15966)
at Pikaday.setDate (pikaday.js:815)
at HTMLDivElement.Pikaday.self._onMouseDown (pikaday.js:462)




How to call Bootstrap jquery function from Ember 2 on specific action

I am doing Chat application ,Currently I managed to add bootstrap/bootsnipp code(Html,css,jquery) in my Ember2.14 project and jquery works fine when I add it in this folder public/assets/Chat.js then I add reference to it in app/index.html.it is now loaded in vendor.js and jquery is working fine when I am loading the page...

-My Question is: How can I call the jquery function (again) from Ember and where to put the code.. I want when I press Send button to put my input Message in Chat window with jquery effect like the Bootstrap example in the below link ..

I am totally new to jquery & Ember so I am not sure which function from the below jquery code I need to call (I think it may be sendMessage) and how to call it from Ember..

jquery:

(function () {
    var Message;
    Message = function (arg) {
        this.text = arg.text, this.message_side = arg.message_side;
        this.draw = function (_this) {
            return function () {
                var $message;
                $message = $($('.message_template').clone().html());
                $message.addClass(_this.message_side).find('.text').html(_this.text);
                $('.messages').append($message);
                return setTimeout(function () {
                    return $message.addClass('appeared');
                }, 0);
            };
        }(this);
        return this;
    };
    $(function () {
        var getMessageText, message_side, sendMessage;
        message_side = 'right';
        getMessageText = function () {
            var $message_input;
            $message_input = $('.message_input');
            return $message_input.val();
        };
        sendMessage = function (text) {
            var $messages, message;
            if (text.trim() === '') {
                return;
            }
            $('.message_input').val('');
            $messages = $('.messages');
            message_side = message_side === 'left' ? 'right' : 'left';
            message = new Message({
                text: text,
                message_side: message_side
            });
            message.draw();
            return $messages.animate({ scrollTop: $messages.prop('scrollHeight') }, 300);
        };
        $('.send_message').click(function (e) {
            return sendMessage(getMessageText());
        });
        $('.message_input').keyup(function (e) {
            if (e.which === 13) {
                return sendMessage(getMessageText());
            }
        });
        sendMessage('Hello Philip! :)');
        setTimeout(function () {
            return sendMessage('Hi Sandy! How are you?');
        }, 1000);
        return setTimeout(function () {
            return sendMessage('I\'m fine, thank you!');
        }, 2000);
    });
}.call(this)); 


Full BootstarpCode: http://ift.tt/2tT9j7J




Foundation 6 destroy and reinitialize on ember

i am trying to do destroy and reinitialize foundation 6 component in ember app. Currently i did these below. It works on the first click after that it won't trigger reinitialize:

// components/zf-reveal.js
import Ember from 'ember';

export default Ember.Component.extend({
  didInsertElement() {
    this._super(...arguments);
    Ember.Logger.log('open');
    this.set('reveal', new Foundation.Reveal(this.$('.reveal')));
  },
  willDestroyElement() {
    this._super(...arguments);
    Ember.Logger.log('destroy');
    this.get('reveal').destroy();
  }
});

// templates/components/zf-reveal.hbs
<a data-open="modal">OPEN REVEAL</a>
<div class="reveal" id="modal" data-reveal>
  <h1>Awesome. I Have It.</h1>
  <p class="lead">Your couch. It is mine.</p>
  <p>I'm a cool paragraph that lives inside of an even cooler modal. Wins!</p>
  <button class="close-button" data-close aria-label="Close modal" type="button">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

These snippets do destroy on route change but when i try to click it again after route change it's not reappearing wont even sending error message




dimanche 23 juillet 2017

Ember js list view

Im develop Ember js project for my university, i'm use ember paper i need to show Image 01 type list , im try to put it, i don't know how to do that, please help me to fix it, you can understand this in my images

I need like this

Image 01

enter image description here

My current view

enter image description here

My code part

  <div class="widget-content">
            <div id="exTab1" class="container">
              <div class="tab-content clearfix">
                <div class="tab-pane active" id="1a">
                  <div class="alt-table-responsive">
                      <table class="table">

                        <tbody>
                        
                          <tr>
                                                      <td class="text-center">
                            
                                                      </td>
                            <td class="text-center">


                              
                            </td>


                            <td class="text-center">
                              
                            </td>
                            <td class="text-center">
                              <p>< </p>
                            </td>
                            <td class="text-center">
                              <a  class="btn btn-mini btn-success"
                                                                                                     role="button" disabled=>
                                Add
                              </a>
                            </td>
                          </tr>
                        
                        </tbody>





                      </table>
                  </div>
                </div>
                <div class="tab-pane" id="2a"></div>
                <div class="tab-pane" id="3a"></div>
              </div>
            </div>
          </div>




Ember-formly Addon's component isn't found

I'm am trying to get the ember-formly addon working like the readme.md file for that addon shows. So, I:

  1. Ran ember install ember-formly
  2. Dumped the example form data Model() and fields into my application/controller.js file
  3. Put the basic template data into my templates/application.hbs file

And that gives me this error when I load it up in my browser:

Assertion Failed: Could not find component named "custom-fields/html-input" (no component or template with that name was found)

Being rather new to Ember.js I'm sure I'm missing something simple... Any ideas? Thanks!




Two design questions from Ember.js framework;

I have two questions:

Is there a way where I can use a button for showing/hiding content separately for every item in each loop? Because I only know how to toggle single property.

Is there a way where I can slowly show content not immediately?




createRecord for relationship of unsaved record

I have the following scenario:

1- Parent route that creates a record for multi-page form

routes/feedback.js
model() {
  return this.get('store').createRecord('feedback');
},

2- child route that return two models, question is non-related model that return multiple questions showing in dynamic route. And answer which creates a record that answer these questions in its page

routes/feedback/question.js
model(params) {
    return Ember.RSVP.hash({
      question: this.get('store').findRecord('question', params.question_id),
      answer: this.get('store').createRecord('answer')
    })

  },

3- Answer has a belongsTo relationship feedback

models/answer.js
choice: DS.attr(),   // receives data from question through a controller
feedback: DS.belongsTo()

models/feedback.js
submittedAt: DS.attr(),
answers: DS.hasMany()

4- data passed from a question to an answer record through controller

controllers/feedback/question.js
getChoice(choice) {
  let answer = this.get('model.answer');
  let questionId = this.get('model.question').get('id');

  answer.setProperties({
    choice: choice,
    questionId: questionId,
    // review: should relationship go here?
  })
  answer.save()

controllers/feedback.js
newModel: null,
actions: {
  save(newModel) {
    newModel.save()
  }
}

So how the relationship should be assigned if feeback doesn't have an ID yet?

Also can I hold the answer saving till the newModel for feedback is saved? Actually, I tried to bubble getChoice action to parent controller but the same problem of null record.




vendredi 21 juillet 2017

Ember collectionAction not working when sending attachment as params

I have to send a attachment as params in ember collectionAction

> let attachment = this.get('store').createRecord('attachment');
> attachment.set('resource', file);
>this.get('store').createRecord('applicant').parseResume(attachment);

where parseResume is the collectionAction for applicant

This throws "Maximum call stack size exceeded" in browser console.

I can't save attachment first and send parse resume second, as it involves two network request. I want to achieve it in single request.




Ember could not get select value from template to component

I'm struggling with this. I would like to pass a select value from template to component. Here is my template

<select name="bank" class="form-control" id="sel1" onchange=>
        
        <option value=></option>
        
        
      </select>

And here is my component

  actions: {
  updateValue: function(bank) {
  this.set('bank.id', bank);
  },
  login() {
    console.log(this.get('bank.id'));
  }

And i've got this beautiful error : Property set failed: object in path "bank" could not be found or was destroyed.

Any idea ? Thanks




Ember addon and processing files

I have successfully managed to render a React component inside of ember. You can see the relevant code here.

The basics being adding an addon, that uses the preprocessTree hook, to use broccoli-react to parse the jsx files as per here. And a ReactComponent (which is an ember component) to wrap any react component.

This works well in ember cli 2.11.0 and 2.12.0, but in 2.13.0 and 2.14.0 something has changed and I can't figure out what.

I have narrowed the error down to this line in ember-resolver, for some reason this._moduleRegistry in the newer versions don't have the react component but the older versions do...

Any ideas?




Ember js user active notification

Im develop Ember js project for my university, im use ember paper i need to show user login after on the top user name active bubble int he green color, and display some error this bubble is get red color, i don't know how to put it and how to write this code for ember js, please help me to fix this you can understand this look my image

My currant view

enter image description here

i need like this

enter image description here

code part .hbs

  <div class="custom-navbar custom-navbar-fixed-top">
      <div class="custom-navbar-inner">
        <div class="container">
          <div class="brand"> Velocity </div>
          

          
    
       

         <h2><span style="color:black; margin: 0 12px;">Hi</span></h2>
         <span class="flex"></span>
          <i class="icon-user icn-01"></i>
          <i class="icon-question-sign icn-01"></i>
         <a ><i class="icon-off icn-01"></i></a>

       
     
          
          <!--/.nav-collapse -->

        </div>
        <!-- /container -->

      </div>
      <!-- /navbar-inner -->

    </div>

css

.custom-navbar .icon-user:before {
    content: "\f007"; color: black;
    margin: 0 25px;
}
.custom-navbar .icn-01 {margin: 0 5px;  text-decoration: none; }


.custom-navbar  .icon-question-sign:before {
    content: "\f059";color: black;  margin: 0 25px;
}

.custom-navbar .icon-power-off:before, .icon-off:before {
    content: "\f011";color: black;  margin: 0 25px;
}

.custom-navbar .md-toolbar-tools {
    font-size: 20px;
background: none;
    letter-spacing: 0.005em;
    box-sizing: border-box;
    font-weight: 400;
    display: -ms-flexbox;

    -ms-flex-align: center;
    align-items: center;
    -ms-flex-direction: row;
    flex-direction: row;
    width: 100%;
    height:auto;
    max-height:54px;
    padding: 0 16px;
    margin: 0;

}
md-toolbar {
    box-sizing: border-box;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    position: relative;
    z-index: 2;
    font-size: 20px;
    min-height: 52px;
    width: 100%;
}
md-toolbar.md-default-theme:not(.md-menu-toolbar), md-toolbar:not(.md-menu-toolbar) {
  background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(229, 229, 229, 1) 100%);

}
 .custom-navbar h2 {
    margin: 0;
    font-family: inherit;
    font-weight: bold;
    color:#428bca;
    text-rendering: optimizelegibility;
}




jeudi 20 juillet 2017

EmberJS - validating field from `Model` not works

I am trying to validate my email and message fields from model. but It seems that the validation not works as per expected.

my model :

import DS from 'ember-data';

export default DS.Model.extend({
    email: DS.attr('string'),
    message: DS.attr('string'),
    emailAddress:'',
    message:"",
    isValid :  Ember.computed.match('emailAddress', /^.+@.+\..+$/),
    isMessageValid : Ember.computed.gte('message.length', 5),
    isDisabled : Ember.computed.and("isValid", "isMessageValid")
});

my contact hbs file :

<h1>Contact</h1>
<div class="form-group has-success">
    <label class="control-label" for="inputSuccess1">Input Email</label>
    
    <label for="inpuitSucess2">Input Message</label>
    
    <br><br>
    <div class="col-xs-10 col-xs-offset-1 col-sm-offset-0 col-sm-4 col-md-3">
        <button disabled=""  class="btn btn-primary btn-lg btn-block">Send message</button>
    </div>
</div>


<div class="col-md-6">
    <br/>
    <div class="alert alert-success">
        <h4>Thank you! Your message is sent.</h4>
        <p></p>
    </div>
</div>


When I keep all this validation on controller it was worked well. when I move to model I am getting that validation fails.

Thanks in advance




How to Use ember-data Adapters Without Model Name in URL

I'm trying to pull data from an API (OMDb) whose endpoint does not include a 'namespace' or actually anything at all beside the root URL (http://ift.tt/2tuYJIS;).

I know how to use an 'empty' namespace for the URL I'm calling so that the adapter isn't tacking on '/api' or anything similar...BUT I cannot figure out how to NOT have the model name added to the URL (i.e., I want the URL to be 'http://www.omdbapi.com/' rather than 'http://ift.tt/2tLUUu8'.

The documentation I've read has dealt with a 'namespace' (e.g., '/api') or changing the model name to something else in the URL-- but I can't figure out how to have the adapter construct a URL with NO model in the URL...a 'naked' URL, if you will...




Emberjs How to Form Validation like jQuery Validation Pluging?

Hi I would like to know if there is a way to create a form validation for diferente model properties for a route like jQuery Validation pluging handles the validations? for example:

My route needs to go first and retrieve some data from a REST API, and then complement the info with extra properties so the template renders the new form.

export default Ember.Route.extend({

userType: Ember.inject.service('user-session'),

model: function (params) {

      return $.getJSON('APIURL', function (data) {


            return {

                  "serverData": data.e.results[0],
                  "id": null,
                  "name": null,
                  "option": 1

             };

      });

   }

});

Then the user changes some info on the form and press the submit button. The problem is, since I do not have any validation the form can be send it by the user with no data.

I used to solve this kind of problems with the jQuery validation plugin creating some rules like:

rules: {
name: {
 required: true
},
id: {
 required: true
}
}, messages: {

  id: { required: 'El campo es requerido (Required in spanish)' }
}

But here on ember.js, I dont know if there is a way to validate the form data.

I have found many plugins that use very basic route models for the examples but since my model is a complex type they dont seem to fit.

Is there any way that I can validate my emberjs forms?




Ember observer not changing field value

So I'm new to Ember and have been doing some digging around for the a while looking for the answer to this.

What I have is a field and I want to restrict the use of whitespace (basically if the user hits the spacebar, I don't want it to do anything).

The issue, is that I can still hit the spacebar and add multiple spaces, and it's not until I hit another character that the value loses all the whitespace (To help this description, instead of swapping spaces, I'm going to swap the letter 'a').

So far I have an observer and a function (in my component js file):

emailChanged: Ember.observer('email', function() {
  // console.log('email changed');
  Ember.run.once(this, 'formatEmail');
}),

formatEmail() {
   // console.log('email', this.get('email')); 
   this.set('email', this.get('email').replace(/a/g, ''));
  // console.log('should be', this.get('email'));
},

So what is happening is that (when I use the console logs).

If I type a 'b' character in the console I get, email changed, then email b, then should be b.

When I type 'a', in the console I get email changed then email ba, then formatEmail() actually runs and changes the email, so then I get should be b, email b, should be b.

But it's still displaying 'ba'.

Hard to explain this, but basically, it looks like set is working, except that it's not changing what is displayed on the screen.

Ember-twiddle




From the router, how can I route to a completely different parent route in EmberJS

Suppose I have the following URL.

http://ift.tt/2uDRbn4

And in my router, it might look something like this:

this.route('foo',  function() {
    this.route('fooo');
    this.route('foooo');
    this.route('abc', function() {
      this.route('def');
      this.route('def, {path: 'def.html'});
       // Some other routes
    }
    // Some other routes
}
// Some other Routes

So what happens now if I want my foo/abc/def to redirect to somewhere COMPLETELY different. Like, for example, bar/uvw/xyz. How can I redirect to there? Is there a way to do it from a the router? I could write transition logic within the /foo/abc/def route but that seems a bit messy.

The reason I need to do this is because I'm transitioning one of our companies websites to a new Ember site. And we want to change the routes to some of our products but make sure people who have saved links to those webpages won't get dead-links.




Pressing Enter in textarea using jQuery and Ember test selector

In an acceptance test, pressing Enter key after text input triggers an event. I tried to fillIn text and hit enter with the keyEvent. PS: I used ember test selector plugin for data-test-id. Please help why the keyEvent is not running. Testem ignores the keyEvent. jQuery solutions are also encouraged.

HTML:

<div class="issue-container">
<div class="create-container">
<div id="ember13" class="input-field ui-textarea md-animated ember-view">
<label id="ember1369-label" for="ember1369-input" class="">Add an issue</label>
<textarea data-test-id="txtid" id="ember1369-input" class="md-textarea" style="height: 21.5px; overflow: hidden;"></textarea></div></div></div>

Acceptance test:

test('review-an-element', async function(assert) {
await fillIn(testSelector('txtid'), 'Input is typed here and then hit enter');
await keyEvent(testSelector('txtid'), 'keypress', 13);});

My jQuery attempt:

var e = jQuery.Event("keypress");
e.which = 13;
e.keyCode = 13;    
await $('.md-textarea').trigger(e);




EmberJS - check if template exists

How can I check if a template exists in an Ember Route object?

I need to check this inside a route; if it does not exist, I will render a default template for that route.

Many thanks!




mercredi 19 juillet 2017

How to reload the model when using this.get('store').query?

I have a user model with attributes name and city, i am fetching 25 records at a time from server since there are lot of user records

so my routes has this

model(){
return this.get('store').query('user', {page:1}); }

which fetches me the first 25 records

Now in my template i have a button which on click hits the action to fetch the next 25 records ie

action:{
findMoreUsers(){
        this.get('store').query('user', {page:2});
    } }

Now in the browser, in the ember data the new records are loaded ie it shows 50 records

but when i try to do something like this.get('model'), it gives me the only the old records but not the newly loaded records

So how to to refersh the model so that it shows me all the old as well as new records(50 records)?

Thanks




How to access nested resources in API

I have a Ember app that uses a Rails API. I have a teams table and a referees table, both link to another table called refereeTeamStats. I am trying to get all the refereeTeamStats for a team and include the referee resource so I can get the referee's name. In short, I need my Ember app to call /teams/:team_id/refereeTeamStats?include=referee Initially I had my app get the refereeTeamStats through the route by doing this:

model() {
  return this.modelFor('teams/show').get('refereeTeamStats');
}

This will call /teams/:team_id/refereeTeamStats however, this will not include the referee resource. What is the best way that I can get the refereeTeamStats with including a resource (referee) on a nested resource (refereeTeamStats)?




How to get handlebars to call get() method on context?

I'm using handlebars by itself with an Ember Object as context. I'd like it so that it works as it does in Ember+HTMLBars, where it seemingly calls get() instead of assuming context is a POJO.

var template = Handlebars.compile("My ember object: ");
var str = template(Ember.Object.create({value: "hello"}));

assert.equal(str, "My ember object: hello"); // Fails. str == "My ember object: "

Is there a way to have handlebars call get()?




res.render an ember route with express

I currently have a webapp using Express, Node, Ember, and Mongo. Ember app resides in a project folder (./public/index.html) in the root of the node/express install. I have express set to serve static files from the public directory and render index.html to any get requests so the ember app is accessible.

I have a route/view in my Ember app that has a form that accepts a file upload, this form's action is a post request to an express route that performs calculations and queries a local mysql database with updates. The function works fine but at the end of the .post express function when I res.json or res.send the response appears in the browser window and clears out my ember view.

I assume the correct way to handle this is to res.render('view',{data:'Finished processing file'});

then display the data value on the ember template. Question is how can I render an ember view with express. I added express-handlebars to my project and setup the view engine correctly but I don't know how to associate ember views with express so it knows how to render the correct view with response data.

hbs file for the ember view

<div class="col-md-8 col-md-offset-2 text-center">
  <h2 class="toolTitle">Reactivate SKUs</h2>
  <p class="lead">CSV Should Contain 1 Column (SKU) Only</p>
  <form action="/tools/sku/reactivate" method="POST" enctype="multipart/form-data">
    <input class="center-block" type="file" name="csvdata">
    <button type="submit" class="btn btn-md btn-danger">Submit</button>
  </form>
</div>

router.js(express router)

var quotes = require('../api/quote');
var cors = require('cors');
var sku = require('../api/tools/sku');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var util = require("util");
var fs = require("fs"); 

var corsOptions = {
    origin: 'http://localhost:4200'
}

module.exports = function(router){
    router.route('/quotes').post(cors(corsOptions),function(req,res){
        console.log(req.body);
        quotes.addQuote(req,res);
    }).get(cors(corsOptions),function(req,res){
        quotes.getAllQuotes(req,res);
    });
    router.route('*').get(cors(corsOptions), function(req,res){
        res.sendFile('public/index.html',{root:'./'});
    });
    router.route('/tools/sku/reactivate').post(upload.single('csvdata'),function(req,res){
        console.log('handing request over to sku.reactivate');
        sku.reactivate(req,res);
    });
};

sku.js express function

var mysql = require('mysql');
var csv = require('csv-parse');
var multer = require('multer');
var fs = require('fs');

//mysql setup
const connection = mysql.createConnection(
    {
        host     : 'localhost',
        user     : 'rugs_remote2',
        password : 'ofbiz',
        database : 'rugs_prd2',
        multipleStatements: true
    }
);
connection.connect();


module.exports.reactivate = function(req,res){
    //define mysql query function for once readStream emits end event
    function reactivationQuery(arr){
    console.log(arr);

       const queryString = "UPDATE PRODUCT SET SALES_DISCONTINUATION_DATE = NULL WHERE PRODUCT_ID IN (?)";
       connection.query(queryString,arr,function(err,rows,fields){
            console.log(rows,fields);
            if(err){
                console.log('Error running sku.reactivate module error is: '+err);
            }
            res.send('DONE');
        });
    }

    //define array for holding csv data in this case skus
    const skuArray = [];
    //define filesystem readstream from uploaded file
    let readStream = fs.createReadStream(req.file.path).pipe(csv());
    //push csv data to array ignoring headers to skuArray
    readStream.on('data', function(chunk){
        if(chunk[0] !== 'SKU'){
            skuArray.push(chunk[0]);
        }
    });
    //error handling
    readStream.on('error',function(err){
        console.log('Error while reading file stream [ERROR] '+ err);
        res.send('Error while processing file');
    });
    //once read is finished map skuArray to usable string for IN Clause
    readStream.on('end',function(){
       let stringifyArray = skuArray;
       stringifyArray = [stringifyArray]; 
       reactivationQuery(stringifyArray);
    });

} 




Accessing Ember data has-many relationship on template

I have a rails back-end, serving data as per the JSON API standards. I have two models: song and review.

class Song < ApplicationRecord
  has_many :reviews
end

class Review < ApplicationRecord
  belongs_to :song
end

This is the JSON response for the API endpoint.

{
  "data": {
      "type": "songs",
      "id": "2",
      "attributes": {
          "id": 2,
          "artist": "Parliament Funkadelic",
          "title": "Chuck Norris doesn't need a debugger, he just stares down the bug until the code confesses."
      },
      "links": {
          "self": "/songs/2"
      },
      "relationships": {
          "reviews": {
              "links": {
                  "self": "/songs/2/relationships/reviews",
                  "related": "/songs/2/reviews"
              },
              "data": [
                  {
                      "type": "reviews",
                      "id": "2"
                  }
              ]
          }
      }
  },
  "included": [
      {
          "type": "reviews",
          "id": "2",
          "attributes": {
              "id": 2,
              "author": "Underworld",
              "content": "Helvetica leggings mixtape keffiyeh lo-fi."
          },
          "links": {
              "self": "/reviews/2"
          },
          "relationships": {
              "song": {
                  "links": {
                      "self": "/reviews/2/relationships/song",
                      "related": "/reviews/2/song"
                  }
              }
          }
      }
  ]
}

These are my Ember models:

for song:

import DS from 'ember-data';

export default DS.Model.extend({
  artist: DS.attr('string'),
  title: DS.attr('string'),
  reviews: DS.hasMany('review', {async: true})
});

for review

import DS from 'ember-data';

export default DS.Model.extend({
  author: DS.attr('string'),
  content: DS.attr('string'),
  song: DS.belongsTo('song', {async: true})
});

This is my route handler:

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.findRecord('song', params.song_id, {include: 'reviews'});
},
(...)

I am unable to access the reviews for a song on the template by doing:

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

Also, the data for the reviews exists in the ember console. What am I missing?




Check if an image exists using EmberJS

I'm new to Ember testing,

I am the only tester on a team and they want to check if our images are loading correctly in every route. Is it possible to check that an image both exists and loaded correctly?

We upload our photos to Cloudinary and want to check for problems such as images containing dead-links.




Ember.js - Passing Params/Model info through a redirect

I am a bit confused how Ember.js handles models and redirects.

Basically, I have a posts page, a post page, and a comments page. The comments page is embedded in the post page, so my route map looks like this:

  define(function(require) {
  require('./loadingRoute');
  require('./rootRoute');
  require('./rootLoginRoute');
  require('./userRoute');
  require('./postsRoute');
  require('./postRoute');
  require('./commentsRoute');

  return function() {
    this.resource('root', {path: '/'}, function() {
      this.route('login', {path: '/login'});
      this.resource('user', {path: '/me'}, function() {
        this.resource('posts', {path: '/posts'});
        this.resource('post', {path: '/:post_id'}, function() {
          this.resource('comments', {path: '/comments'});
        });
      });
    });
  };
});

When I click on a post in the posts page, it transitions to the post page:

Posts Route:

define(function(require) {
    var Ember = require('ember');
    var App = require('app');

    return App.registerRoute('posts', {
        view: require('../view/postsView'),
        controller: require('../controller/postsController'),
        route: Ember.Route.extend({
            actions: {
                showPost: function(post) {
                    this.transitionTo('post', post);
                }
            },
            model: function(params, transition) {
                return this.controllerFor('posts').findPosts();
            },
            renderTemplate: function() {
                this.render({ into: 'root', outlet: 'posts' });
            }
        })
    });
});

Post Route:

define(function(require) {
    var Ember = require('ember');
    var App = require('app');

    App.registerRoute('postIndex', {
        route: Ember.Route.extend({
            redirect: function() {
                this.transitionTo('comments');
            }
        })
    });

    return App.registerRoute('post', {
        view: require('../view/postView'),
        controller: require('../controller/postController'),
        route: Ember.Route.extend({
            model: function(params, transition) {
                return this.controllerFor('post').findPost(params.post_id);
            },
            renderTemplate: function() {
                this.render({ into: 'root', outlet: 'posts' });
            }
        })
    });
});

However, as you can see in the Post Route, it redirects to my comments route upon loading (I think).

I need access to the post.post_id once I get into the comments route, but I don't understand how to pass this through the redirect.

There are some examples of redirect() having parameters (model, transition), however model always comes up undefined to me.

Here is Comments Route for reference:

define(function(require) {
    var Ember = require('ember');
    var App = require('app');

    return App.registerRoute('comments', {
        view: require('../view/commentsView'),
        controller: require('../controller/commentsController'),
        route: Ember.Route.extend({
            actions: {
                showComment: function(comment) {
                    this.transitionTo('comment', comment);
                }
            },
            model: function(params, transition) {
                console.log(params);
                //return this.controllerFor('comments').findComments(params.post_id);
            },
            renderTemplate: function() {
                this.render({ into: 'post'});
            }
        })
    });
});

The above has my controller line of code commented because params was undefined, and so was giving me issues (which is what I'm trying to solve).




Why does my Ember component integration test pass when I run it in isolation, but fail when I run the full suite?

I have a simple, bare-bones integration test for a component which depends on an i18n service (which the test injects). The component itself is a simple select dropdown from ember-select-list, with a default value of Select Language. Here's the test:

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('language-select', 'Integration | Component | language select', {
  integration: true,
  beforeEach() {
    this.inject.service('i18n');
  }
});

test('it renders', function(assert) {
  this.render(hbs``);

  assert.equal(this.$().text().trim().includes('Select Language'), true);
});

When I attempt to just run this one test file (i.e. ember test -f "language-select"), the output I see indicates that only linting tests were performed:

[ hospitalrun-frontend ] $ ember test -f "language-select"
WARNING: Node v7.5.0 is not tested against Ember CLI on your platform. We recommend that you use the most-recent "Active LTS" version of Node.js.
cleaning up...
Built project successfully. Stored in "/Users/richie.thomas/Desktop/Workspace/OpenSource/hospitalrun-frontend/tmp/core_object-tests_dist-5MT1adu7.tmp".
ok 1 PhantomJS 2.1 - ESLint - acceptance/language-select-test.js: should pass ESLint
ok 2 PhantomJS 2.1 - ESLint - components/language-select.js: should pass ESLint
ok 3 PhantomJS 2.1 - TemplateLint - hospitalrun/templates/components/language-select.hbs: should pass TemplateLint
ok 4 PhantomJS 2.1 - ESLint - integration/components/language-select-test.js: should pass ESLint

1..4
# tests 4
# pass  4
# skip  0
# fail  0

# ok

However when I run a plain ember test, I see that this test fails because I am apparently injecting the i18n service incorrectly:

not ok 488 PhantomJS 2.1 - Integration | Component | language select: it renders
---
    actual: >
        null
    expected: >
        null
    stack: >
        http://localhost:7357/assets/hospitalrun.js:4090:18
        get@http://localhost:7357/assets/vendor.js:35757:32
        get@http://localhost:7357/assets/vendor.js:40664:22
        compute@http://localhost:7357/assets/vendor.js:33758:29
        value@http://localhost:7357/assets/vendor.js:33625:52
        value@http://localhost:7357/assets/vendor.js:65639:37
        value@http://localhost:7357/assets/vendor.js:33512:34
        create@http://localhost:7357/assets/vendor.js:31495:53
        evaluate@http://localhost:7357/assets/vendor.js:66320:43
        execute@http://localhost:7357/assets/vendor.js:72898:36
        render@http://localhost:7357/assets/vendor.js:72472:30
        render@http://localhost:7357/assets/vendor.js:30793:52
        runInTransaction@http://localhost:7357/assets/vendor.js:41756:28
        _renderRoots@http://localhost:7357/assets/vendor.js:31058:64
        _renderRootsTransaction@http://localhost:7357/assets/vendor.js:31096:26
        _renderRoot@http://localhost:7357/assets/vendor.js:31017:35
        _appendDefinition@http://localhost:7357/assets/vendor.js:30930:23
        appendOutletView@http://localhost:7357/assets/vendor.js:30913:29
        invoke@http://localhost:7357/assets/vendor.js:19795:19
        flush@http://localhost:7357/assets/vendor.js:19865:15
        flush@http://localhost:7357/assets/vendor.js:19989:20
        end@http://localhost:7357/assets/vendor.js:20059:28
        run@http://localhost:7357/assets/vendor.js:20182:19
        run@http://localhost:7357/assets/vendor.js:40972:32
        render@http://localhost:7357/assets/test-support.js:20665:30
        http://localhost:7357/assets/tests.js:15398:16
        runTest@http://localhost:7357/assets/test-support.js:3859:34
        run@http://localhost:7357/assets/test-support.js:3845:13
        http://localhost:7357/assets/test-support.js:4037:15
        advance@http://localhost:7357/assets/test-support.js:3522:26
        begin@http://localhost:7357/assets/test-support.js:5213:27
        http://localhost:7357/assets/test-support.js:4407:11
    message: >
        Died on test #1 http://localhost:7357/assets/tests.js:15392:24
        exports@http://localhost:7357/assets/vendor.js:123:37
        requireModule@http://localhost:7357/assets/vendor.js:38:25
        require@http://localhost:7357/assets/test-support.js:19547:14
        loadModules@http://localhost:7357/assets/test-support.js:19539:21
        load@http://localhost:7357/assets/test-support.js:19569:33
        http://localhost:7357/assets/test-support.js:7584:22: undefined is not an object (evaluating 'i18n.get')
    Log: |
...

I don't see anything in the documentation here about the filter flag affecting the type of tests that are run (i.e. lint vs non-lint tests).

I'm happy to post a separate question about how to properly inject the i18n service, but my question here is:

Why does adding the filter flag result in only filtering tests being run?




Why do I not have access to a parent-scope variable in one "then" block, but I do have access in a subsequent block?

I'm contributing to an open-source Ember app, and I'm attempting to chain several promises together. The intent of the code below is to set a user into the current_user document of the PouchDB store, and then set their i18n preferences into the preferences store. Here's the code:

setCurrentUser(userName) {                                 // block 0
  let config = this.get('configDB');
  let sessionData = this.get('sessionData');
  if (!userName && sessionData.authenticated) {
    userName = sessionData.authenticated.name;
  }
  config.get('current_user').then((doc) => {               // block 1
    doc.value = userName;
    config.put(doc);
    return userName;
  }).then((user) => {                                      // block 2
    let configDB = this.get('configDB');
    let preferences = configDB.get('preferences');
    let promises = { user, preferences };
    return RSVP.hash(promises);
  }).then((promises) => {                                 //  block 3
    let { preferences } = promises;
    let userName = promises.user.name || 'default';
    this.set('i18n.locale', preferences[userName].i18n);
  }).catch((err) => {                                      // block 4
    console.log(err);
    config.put({_id: 'current_user', value: userName});
  });
}

As you can see, the userName variable is passed in as a parameter to the setCurrentUser method. Because of this, I would expect to have access to this parameter inside each of the blocks of code inside each then block.

However that's not the case. I do have access to it in blocks 0, 1, 3, and even in the scope of catch in block 4. But for some reason, I don't have access to it in block 2. The above code, specifically the passing of the RSVP object with both the preferences doc and the user object, represents a hacky workaround to make my code work, since I keep getting Uncaught ReferenceError: userName is not defined inside block 2. However, I'd prefer to do something like this (note: code below is for illustrative purposes only, and may have errors):

setCurrentUser(userName) {
  let config = this.get('configDB');
  let sessionData = this.get('sessionData');
  if (!userName && sessionData.authenticated) {
    userName = sessionData.authenticated.name;
  }
  config.get('current_user').then((doc) => {
    doc.value = userName;
    config.put(doc);
    return userName;
  }).then((user) => {
    let configDB = this.get('configDB');
    let preferences = configDB.get('preferences');
    return preferences[username] || preferences['default'];
  }).then((user_preferences) => {
    this.set('i18n.locale', preferences[userName].i18n);
  }).catch((err) => {
    console.log(err);
    config.put({_id: 'current_user', value: userName});
  });
}

My question is, what is the difference between blocks 0/1/3/4 and block 2, which would allow the first blocks to access userName but would prevent block 2 from doing so?




Observing a property on a service from a router in EmberJS

I think I'm not understanding a concept here. As far as I know any Ember.object can observe properties on another Ember.object.

So, I have a service, a router, and a component. I need the component and the router to be able to observe a property on the service. It's entirely possible that I'm just structuring the solution in the wrong way, I'll include an overview of what I'm trying to do at the end.

Here is approximately what I have:

/services/thing-manager.js

export default Ember.Service.extend({
  observedProperty: 'original value'
});

/components/thing-shower.js

export default Ember.Component.extend({
  thingManager: Ember.inject.service(),
  myObserver: Ember.observer(
    'thingManager.observedProperty',
    function() {
      // This shows up as anticipated, unlike the one in the routes
      console.log('THING SHOWER COMPONENT observed change on thingManager')
    }
  ),
 actions: {
   changeObservedProperty: function() {
     let thingManager = this.get('thingManager')
     let newText = thingManager.get('observedProperty') + '!'
     // here i am sure to call `set` to make sure observers fire
     thingManager.set('observedProperty', newText)
   }
 }

});

/routes/things.js

export default Ember.Route.extend({
  thingManager: Ember.inject.service(),

  underObservation: Ember.observer('thingManager.observedProperty', function() {
    // This is what I expect to fire, but does not.
    console.log('THINGS ROUTE observed change on thingManager')
  }),
});

As you can see, I'm expecting console output from both observers in the component and router. Why doesn't this work?

Twiddle here!

My Overall Goals

This is perhaps a separate question, but I'd like to know if there is a better way to accomplish what I'm trying to do. I've been learning about 'data down, actions up', which led me to this approach. I'm building a website that load a json file with a bunch of GPS coordinates and sticks them on a map.

The goal is to click a map marker, and have that load the corresponding data. This should also change the route. So, my thinking was, to keep track of my markers in a service, and when the selected marker changes, the router would observe that and transition to the next route. The component would also notice the changed property and update the map.

Thanks folks!




Inject Ember service from subfolder

My current ember project is structured like this:

+-- app
| services 
|   +-- service1.js
|   |   subfolder
|   +-- service2.js

I have a service (service1.js) just in the root of the services folder. I can perfectly inject that into a controller like this:

    service: Ember.inject.service("service1"),

But I want some more structure in my services folder. I want to put a service (service2.js) in a subfolder ('subfolder').

How do I inject this into my http://ift.tt/2teWlBI? If I write down:

service: Ember.inject.service("subfolder/service2") or
service: Ember.inject.service("subfolder.service2"),

This doesn't work

Attempting to inject an unknown injection

How can I inject a service from a subfolder into my controller/component/etc ?




define a logic as alias in ember handlebar using "with" helper

Is there a way to use #with handle bar like this
I want to define a logic as alias is it possible?




mardi 18 juillet 2017

Alertify not working with Ember transitions from route

I am trying to use alertify confirmation box when someone tries to navigate from the page. But in the willTransition action of the route, alertify is very asynchronous, and ember doesn't wait for the confirmation. No matter what you click, the page is already navigated.

willTransition(transition) {
  alertify.confirm('Confirm', 'Are you sure you want to navigate?', function(e) {
    if(e) {
     return true;
    } else {
     transition.abort();
    }
  });
}

Please help me with this!!




Dynamically generating components with Ember, Rails and AWS

I would like to create a blog with an Ember front-end, a Rails API acting as the back-end and and AWS to store the images. I was thinking of dividing up the posts into objects: paragraph, image, etc... and storing them in a relational database (postgres). This would then allow me to generate the corresponding Ember components on the front-end depending on the model i.e. render a paragraph component for each paragraph, an image component for each image, etc. I figured this would allow me greater flexibility when displaying the posts The end goal would be to also create the CMS to manage the blog. Is this the right way to go about this?




Change ember build directory without command line flags

I am trying to make my Ember project build to a directory outside of the project and for future builds I don't want to use command line flags each time. ember build --output-path=/not-dist will work for me but I want Ember to add the flag automatically.

    outputPaths: {
      app: {
        html: '../presentation/index.cfm',
        css: {
          'app': '../presentation/assets/ember-presentation-viewer.css'
        },
        js: '../presentation/assets/ember-presentation-viewer.js'
      },
      vendor: {
        css: '../presentation/assets/vendor.css',
        js: '../presentation/assets/vendor.js'
      }
    }

I have tried this as per the ember-cli documentation but ember-presentation-viewer.css was insisting on getting built in the dist directory with all the additional paths put there.

Is there a way to do this?




injecting and ember service from outside

Can I inject service to a component from an initializer? I would like to have a property in any component in my app's components that brings static config info. I know I can do this inside the component:

cfgStore: Ember.inject.service('cfgstore-reader')

And I can add an object to my components in an intializar:

let cfg = Ember.Object.extend(cfgStore);

export function initialize(application) {
  application.register('cfgstore:main', cfg);
  application.inject("component", "cfgstore", "cfgstore:main");
}

Can I do the same for an injector? I could find any sample and it does seem to work...




Ember fingerprinting

I am new to ember and am running into an issue deploying an ember app. I am using ember server to server my ember app that was built with fingerprinting enabled.

/app/node_modules/ember-cli/bin/ember build --environment=production

When I run this in production mode, it works great, until I scale to multiple deployments.

/app/node_modules/ember-cli/bin/ember server --port 80 --live-reload=false --environment $EMBER_ENV

When I have more then one ember server instance in a load balancer, the fingerprint generated on each is different, even though they were the same build, and this causes an intermittent 404.

172.x.x.x - - [18/Jul/2017:18:44:59 +0000] "GET /assets/vendor-a4e09847ae5ed0421fd631873a322bdb.js HTTP/1.1" 404

  • Is this fingerprint generated at run time and not build time?
  • Is there any way I can make it a build time action?

Thanks so much.




Were Ember Computed Properties meant to be used with / contain asynchronous code?

I'm an experienced Ember.js developer. In guides, we can find an example of Computed Property with full name (synchronous, easy, relies on first name and last name). In the wild, we can find however lots of usages of Computed Properties in an asynchronous manner (for example setting itself after promises resolve - while the first run and get returns undefined).

The more I see this asynchronous Computed Properties the more I wonder - were Computed Properties meant to be used with an asynchronous code? Isn't it asking for trouble?

A common issue is that other Computed Property (CP2) relies on async CP1. CP2 gets CP1 but it gets undefined (as CP1 will set its value in later time as it is async). CP2 finishes its calculation with the wrong value of CP2 (undefined). CP1 sets itself, but CP2 does not recalculate anymore (even CP1 changed) because CP2 isn't referenced in the template (which would mean it is bound and its value is needed all the time, always recalculates when CP1 changes) - but instead was referenced by some JavaScript call.

The real world example of this could be the calculation of total order (from e-commerce shop) price based on items in the order. Computed property relies on asynchronous relationships to items, which could contain other asynchronous relationships, like tax type.