jeudi 30 novembre 2017

d3 zoom x-domain only

I currently have a d3 bar graph for which I am trying to restrict zooming to only its x-axis.

The data spans a high number of years along the x-axis, resulting in a highly concentrated bar graph. I'd like to be able to zoom along the x-axis, thus spreading the bars farther apart horizontally - similar to what is being done on this line graph here.

Right now, I have a function within my ember app in which I select each of the elements within the SVG and zoom in along both axes. How do I restrict zooming to occur only along the x-axis?

enableZoom() {

const svg = d3.select('svg');

const zoomHandler = d3.zoom().scaleExtent([1, 2]).on('zoom', zoomed);

const bars = svg.selectAll('.bar'),
      lines = svg.selectAll('.line'),
      circles = svg.selectAll('circle');

zoomHandler(svg);

function zoomed() {

  lines.attr('transform', d3.event.transform);
  circles.attr('transform', d3.event.transform);
  bars.attr('transform', d3.event.transform);

}

},




jquery issue while setting up Rails 5.1.4 with Ember.js

I've created a new rails application and installed Ember.js bootstrap there. Unfortunately, I'm receiving error shown below when I'm trying to enter the landing page:

Sprockets::FileNotFound in DataVisualisation#index
Showing /Users/user/apps/example-app/app/views/layouts/application.html.erb where line #7 raised:

couldn't find file 'jquery' with type 'text/coffeescript'
Checked in these paths: 
  /Users/user/apps/example-app/vendor/assets/ember/development
  /Users/user/apps/example-app/app/assets/config
  /Users/user/apps/example-app/app/assets/images
  /Users/user/apps/example-app/app/assets/javascripts
  /Users/user/apps/example-app/app/assets/stylesheets
  /Users/user/apps/example-app/vendor/assets/ember
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/jquery-rails-4.3.1/vendor/assets/javascripts
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/ember-rails-0.21.0/app/assets/javascripts
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/coffee-rails-4.2.2/lib/assets/javascripts
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/actioncable-5.1.4/lib/assets/compiled
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/actionview-5.1.4/lib/assets/compiled
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/turbolinks-source-5.0.3/lib/assets/javascripts
  /Users/user/apps/example-app/node_modules
  /Users/user/apps/example-app/tmp/ember-rails
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/ember-source-2.17.0/dist
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/ember-data-source-2.17.0/dist/globals
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/active-model-adapter-source-2.1.1/dist
  /Users/user/.rvm/gems/ruby-2.4.2@example_app/gems/ember-cli-assets-0.0.37/vendor/assets
Extracted source (around line #1):
1 #= require jquery
2 #= require jquery_ujs
3 #= require ./environment
4 #= require ember
5 #= require ember-data
6 #= require active-model-adapter

There is how application.coffee file looks like:

#= require jquery
#= require jquery_ujs
#= require ./environment
#= require ember
#= require ember-data
#= require active-model-adapter
#= require_self
#= require ./data-visualisation

# for more details see: http://ift.tt/XTBcuN
window.ExampleApp = Ember.Application.create()

Gemfile includes gems like:

gem 'rails', '~> 5.1.4'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'ember-rails'
gem 'jquery-rails'

Do you have any suggestions why I'm receiving this error?




Change model value on hover of div element in emberjs

I am trying to create a component some thing like list view where each item is a div. On hover of an item it gets highlighted and also 2 icons should appear, for these icons to appear I can monitor model variable and change class accordingly. Is this correct thought process, or is there a simpler way.

At present I am unaware on how to change model variable on hover over div element. Please help in either of 2 mentioned ways

  1. Help in changing model variable on hover over div element
  2. Is there a better way to do this kind of work in emberjs?

list-view.hbs

<div class="listViewContainer">
    <div class="dropdown ulContainer">
      
        <div class="listItem row">
            <div class="message col-md-10">
                
                    <span class="counter"></span>
                
                    
                
            </div>            
            <div class="actions col-md-2">
                <img src="assets/images/filter_add.svg" class=""  width="25px" height="25px"/>
                
                    <img class="actionsCol" src="assets/images/action_menu.svg" data-toggle="tooltip" data-placement="top" title="Action" alt="Action" />
                
            </div>
        </div>
        <hr class="divider"/>
      
    </div>
</div>

CSS

.listViewContainer {
    text-align: left;
    .ulContainer {
        height: 100%;
        line-height: 2em;
        padding: 0;
        margin: 0;
        overflow-x: hidden;
    }
    .listItem:hover { 
        background-color:#E2F1FD; 
        opacity: 1;
        filter: alpha(opacity=100);
        border: 1px solid #71B8FF;
        border-radius: 5px;
    }
    .listItem {
        padding: 5px;
        list-style-position: inside;
        list-style: none;
        word-wrap: break-word;
        margin-left: 0px;
        margin-right: 0px;
        border-radius: 5px;
    }
    .counter {
        font-family: $app-font;
        font-size: 20px;
        margin-right: 18px;
    }
    .message {
        padding-right: 0px;
        padding-left: 0px;
    }
    .actions {
        float: right;
        padding-right: 10px;
    }
    .divider {
        margin-top: 2px;
        margin-bottom: 2px;
        margin-left: 0px;
        border-top: none;       
    }       
    .actionsCol {
        display: inline-block;
        height: 20px;
        width: 20px;
        cursor: pointer;
        opacity: 0.2;
        filter: alpha(opacity=0);
    }
}

Current view screenshot enter image description here

The desired outcome needed enter image description here




Understand loading of unrelated models for nested route in Ember

My routes look roughly like this:

```

/
  /sites
    /:site_id
      /settings
        /user-defined-params
          /:param_id  

```

Now in /user-defined-params I want to display table-list of parameters assigned to that given site. The models are not related, I mean site doesn't have collection of params as a relation, so I can't simply fetch them via this relation.

Should model() hook for my router return list of these params? By default the model seems to be site loaded from parent route (:site_id). What if loading takes some time and I'd like to actually display this table (so do actual transition) but then show kind of loading indicator waiting for table to fill in with the data.

When I try to load this in model() hook, transition blocks. When I try to load it in afterModel() hook, I don't have a way to assign it and make it available for template (other than force-assigning params property to site model, which seems to be wrong).

All the examples I've found over the Internet seem to be lacking this scenario, which I feel is one of the basic ones, so any hints on that? How should I load it (ideally without blocking transition)?




Modifying model's observed properties in action Ember

I have a search results page with the retrieved search results stored in the model as results. on the same page, I have a button to check all the results for extraction.

I have a property named checked and initially, it is set to falsein the button action I want to change this property on each result to true.

this is my action

checkAll(){
      this.controller.get("model.results").map(doc=>{
        doc.checked = true;
      })
    }

but I keep getting this error:

Assertion Failed: You must use Ember.set() to set the checked property (of [object Object]) to true.

I don't how to use Ember.set() only on that property. and I don't know if this is the right way to go about this as I'm new to ember.

any help would be much appreciated. Thank you.




Is it possible to trigger programmatically a ember mirage request response

I use Ember mirage in my tests. I need to check the state of my tested component after a request has been send but before the respond has been received.

How it is possible to configure my test to avoid the mirage server responds automatically and trigger the response programmatically?

I used to do that with sinonjs but I do not find the way to manage this use case with Ember mirage. It is possible?




EmberJS Tutorial mod - Why, when adding Complex Component, my page content disappeared?

I'm currently working through the EmberJS tutorial and adapting it to a project I have as I go. The tutorial is to build a house rental site. I'm adapting it to build a bus route listing site as a basis for a project I'm working on.

The site was progressing in line with the tutorial steps until I added a complex component (described here). The changes I made are described in this commit on GitHub.

Instead of producing a form to search the project site's data for listings (in my case, routes) that match the basic search parameters, my project site has lost the main page content.

enter image description here

I can't work out how I broke this and why the search form isn't being rendered on the page? I followed the steps and mostly substituted references to rental with route to try and minimize the overall changes to the tutorial code.

I'm using the tutorial to gain a better understanding of EmberJS so I more completely redevelop my Modiin Bus site using this framework.




EmberJS - Refactoring item into a Component stops Query Params and actions triggering

I currently have a small report builder in my application that updates query params in the URL. The query params are used to define criteria in a query on my back end and return the required report.

I am trying to refactor it into a component so that it can be used in other parts of the application.

Here is the report builder:

<div class="container" style="margin-top:100px">

  <div class="panel panel-info">
    <div class="panel-heading">
      <h3 class="panel-title">Report Builder</h3>
    </div>
    <div class="panel-body">
      <form class="form-horizontal" method="get" >
        <div class="form-group">

          <div class="col-sm-3"><label>Module:</label>
            
                  
            
          </div>

          <div class="col-sm-3"><label>Date From:</label></div>
          <div class="col-sm-3"><label>Date From:</label></div>
          <div class="col-sm-3"><label>Unit Number:</label></div>
          <div class="col-lg-10 col-lg-offset-5" style="margin-top:15px">
            <button type="reset" class="btn btn-default">Reset</button>
            <button type="submit" class="btn btn-info">Submit</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

And here are the actions that are used to set the query params for the query and take the user to the correct page afterwards. This code is on the controller for the reports.hbs template:

import Controller from '@ember/controller';

export default Controller.extend({

  queryParams: ['dateFrom', 'dateTo', 'unitNumber'],
  dateFrom: null,
  dateTo: null,
  unitNumber: null,

  actions: {
    selected(x) {
      module = x
    },

    onChangeDateFrom(selectedValue) {
      this.set('dateFrom', moment(selectedValue).format('DD-MM-YYYY'))

    },

    onChangeDateTo(selectedValue) {
      this.set('dateTo', moment(selectedValue).format('DD-MM-YYYY'))

    },

    submitQuery(dateFrom, dateTo, unitNumber) {
      switch (module) {
        case 'Option 1 List':
          this.transitionToRoute('option1list', {
            queryParams: {
              dateFrom: this.get('dateFrom'),
              dateTo: this.get('dateTo'),
              unitNumber: this.get('unitNumber')
            }
          })
          break;
        case 'Option 2 List':
          this.transitionToRoute('opton2list', {
            queryParams: {
              dateFrom: this.get('dateFrom'),
              dateTo: this.get('dateTo'),
              unitNumber: this.get('unitNumber')
            }
          })
          break;
        case 'Option 3 List':
          this.transitionToRoute('option3list', {
            queryParams: {
              dateFrom: this.get('dateFrom'),
              dateTo: this.get('dateTo'),
              unitNumber: this.get('unitNumber')
            }
          })
          break;
        case 'Option 4 List':
          this.transitionToRoute('opton4list', {
            queryParams: {
              dateFrom: this.get('dateFrom'),
              dateTo: this.get('dateTo'),
              unitNumber: this.get('unitNumber')
            }
          })
          break;
        case 'Select a Module:':
          alert('Please select a Module')
          break;
        default:
          console.log('error')
      }
    }
  }
});

When I create a component (report-builder) and put in the HTML the fields and actions no longer operate. Attempting to copy the actions into the report-builder.js.

transitionToRoute cannot be used in a component either. I tried to separate the actions into the JS file for the component and the transitions into a controller called report-builder but this did not produce any results.

I am new to Ember and Software Development, any advice is gratefully appreciated.




mercredi 29 novembre 2017

Change the content of the response after fastboot has done its work

I want to know if it's possible to change the content of the HTML response of fastboot. I want to do some post processing in the code. I checked their code and they have a middleware (fastboot-express-middleware) that looks promising.

Before diving more into the code I wanted to know if there is currently an approach that people usually use in their pipeline.




Nesting more than one JSON - is it the best option for data grid and tables? If yes, how to do it?

I have a database that I will query to calculate some time series (about 150 of them) - they are all financial statements calculated from a general ledger.

I'm writing a code that iterates through the list of accounts (chart of accounts in the financial language) and queries them all.

The result of that code is several JSON objects like:

Account 1:

[
{
    "Y": 2015,
    "ValorTotal": 328.0,
    "M": 4
},

Account 2:

[
{
    "Y": 2015,
    "ValorTotal": 493.0,
    "M": 4
},

Given my objective is to display the information on a datagrid/table (something like the Ember Financial Table) in which the time element is in the columns, and "Accounts" are rows - probably to feed a JQuery plug-in, Bootstrap table or something like that, I ask:

  • Should I work with several JSON or one single JSON?
  • Any other data structure I should look at?

In case the nested JSON is the best option, how could I transform the N objects (showed above) to the nested object (showed below)?

{
    "Y": 2015,
    "M": 4,
    "Accounts": {
        "Account1" : 328,
        "Account2" : 493,
        "Account3" : 574,




How to prevent Ember Data from saving a read-only attribute for ActiveModelSerializer

I am trying to use the {readOnly: true} functionality with ActiveModelSerializer by customizing the serialize method to ignore readOnly attributes like this for JSONAPISerializer or this for RESTSerializer, to prematurely save on upload bandwidth.

Does anyone know if something similar can be done with ActiveModelSerializer?




How to send data as x-www-form-urlencoded in ember data

Out server api accepts data only in x-www-form-urlencoded form instead of json.

I can override the headers in model adapter:

import DS from 'ember-data';
export default DS.RESTAdapter.extend({
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

But I don't know how to serialize data now:

import DS from 'ember-data';
import { inject as service } from '@ember/service'
export default DS.JSONAPISerializer.extend({
  api: service('page-data'),
  serialize(snapshot, options) {
    var json = {
      stock_name: snapshot.attr('stock_name'),
      licence_type: snapshot.attr('licence_type'),
      priceable: snapshot.attr('priceable')
    };

    if (options.includeId) {
      json.stock_id = snapshot.stock_id;
    }
    // add csrf token
    json[this.get('api.pageData.csrf.token')] = this.get('api.pageData.csrf.hash')

    return json;
  }
});

This will always post data in json form to the api. But I need it to be in stock_name=*&licence_type=*&priceable=* form.




EmberJS: Can I update a model from a service?

I'm trying to use a service, let's say for User Login session. I retrieve the user's info from the service.

Now I want to display this info - ideally using a model (user-profile).

My question is, in my service - can I set the user-profile model's attributes? So that my "profile-view" route can show the data in the user-profile model.




Ember - How to display component name in the HTML

when I'm working with an ember app, I would appreciate to see what component html I'm looking at. I know there is an Ember extension into the browser that can show me component names, but it would be much better to see it in the html. Something like this

<div id="ember282" class="ember-view">
  <!-- components/my-component -->
  <div id="ember317" class="ember-view">Component content</div>
  <!-- components/my-component end -->
</div>

is it possible? and how?

Thank you




mardi 28 novembre 2017

Does Ember Data 2.16.0 support meta for findAll()?

In the Ember Guide for Ember Data 2.16.0 (http://ift.tt/2BjGp4M), it says that if we want to access the top level meta, we could do

 this.store.findAll('user').then((results) => {
      return {
        users: results,
        meta: results.get('meta')
 };

I've tried to do the same thing using Ember data 2.16.0. The results returned from findAll() does not contain meta, while results from query() does contain meta. This is consistent with older versions of Ember Data (http://ift.tt/1KmAC1T). Is such behavior changed in 2.16.0? If not, then the Ember guide might need a little touch up.




Installing Boostrap 4 on ember js

I've looked around but can't find the proper way to include boostrap with ember. I don't want the ember-boostrap package since it doesn't support boostrap 4.

I'm also lost about every article outhere telling to use bower to install it but since bower is being remplaced with yarn I don't want to use a deprecated method.

I've try many times but it always fail when I'm trying to import the boostrap.js file in my ember-cli-build.js like so --> app.import('bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js'); I'm having this error

The Broccoli Plugin: [BroccoliMergeTrees: TreeMerger (vendor & appJS)] 
failed with:
Error: ENOENT: no such file or directory, open '/private/tmp/my-first-
ember-app/tmp/source_map_concat-input_base_path-
http://ift.tt/2AaCMkx
official/assets/javascripts/bootstrap.js'

Many thanks !




Is it possible to write conditional check for two variable in one conditional check

I have a case where two condition need to check for disabling button.

sample code , the way i have did

<div class=" ">Submit</div>

Thanks.




Is this possible to group the in-repo engines under lib folder? Example: lib/group1/engine1...etc

Is this possible to group certain in-repo engines under lib folder? Example: lib/group1/engines lib/group2/engines




lundi 27 novembre 2017

ember inline if else statement

I'm using Ember JS and i'm having a weird problem neither the documentation of ember nor the truth helper docs helped me to figure it out

Simple problem but driving me crazy, i want to write an inline "if" statement with "else" clause but it won't work

Here is my code

<option class="form-control" value="" selected=">

The "if" statement in the value attribute is working just fine the problem is in the selected attribute, here is the dilemma.

I'm optimizing my code so i wrote a component with foreach loop but the foreach could iterate from either a service i written for some hardcoded data or some data from the database so if serviceList is true that means that the data is coming from the service not the database which in case wouldn't deal with "id's", so i want my inline "if" statement to check wether if serviceList is true or not, if serviceList is true then check if the item from the service equals the value from the database and display the current value in the edit from, else if serviceList is false then check if the item.id equals a value already stored in the database and display it.

Thanks for help in advance.




How to use asynchronous service in ember.js?

Before my ember.js app start, I need to access a entry api to get all those api endpoints and csrf token.

I'm trying to do it in service so the response can be accessed everywhere:

import Service from '@ember/service';
import $ from 'jquery'
export default Service.extend({
  pageData: null,
  init () {
    this._super(...arguments)
    var self = this
    $.ajax({
      type: 'get',
      url: '/page_data',
      dataType: 'json'
    }).then((response) => {
      self.set('pageData', response)
    })
  }
});

And I'm injecting the service in initializer:

export function initialize (application) {
  application.inject('route', 'api', 'service:page-data');
  application.inject('controller', 'api', 'service:page-data');
  application.inject('component', 'api', 'service:page-data');
}

export default {
  initialize
};

But I can't use the service in my router directly with this.get('api').pageData because it's asynchronous.

I found something on ember.js documetation here:

Operations performed in initializers should be kept as lightweight as possible to minimize delays in loading your application. Although advanced techniques exist for allowing asynchrony in application initializers (i.e. deferReadiness and advanceReadiness), these techniques should generally be avoided. Any asynchronous loading conditions (e.g. user authorization) are almost always better handled in your application route's hooks, which allows for DOM interaction while waiting for conditions to resolve.

But it 's used in initializers, not service.

Any suggests what I can do with my service now?




dimanche 26 novembre 2017

Ember doesn't create nested models on store.createRecord

I have a nested model with default values. After I call this.get('store').createRecord('event') I try to get nested property in my form. But the only thing I can see is a null and an error in console because of 'can't get property country of undefined' for example. In this case I found workaround and created nested models manually like that. But I think it is not the best idea.

// the method to create event
           createEvent() {
                    let event = this.get('store').createRecord('event');
                    let location = this.get('store').createRecord('location');
                    let address = this.get('store').createRecord('address');
                    Ember.set(location, 'address', address);
                    Ember.set(event, 'location', location);
                    this.set('event', event);
                }

        // event model
        export default DS.Model.extend({
            '@type': DS.attr('string', {defaultValue: 'Event'}),
            'startDate': DS.attr('string', {defaultValue: tomorrow}),
            'endDate': DS.attr('string', {defaultValue: theDayAfterTomorrow}),
            'name': DS.attr('string'),
            'eventType': DS.attr('string'),
            'timeZone': DS.attr('string'),
            'location': DS.belongsTo('location', { async: false }),
        });

        // location model
        export default DS.Model.extend({
            '@type': DS.attr('string', {defaultValue: 'OnlineLocation'}),
            'name': DS.attr('string', {defaultValue: ''}),
            'url':  DS.attr('string', {defaultValue: 'http://'}),
            // 'address': DS.belongsTo('address', { async: false }),
            'address': DS.attr(),
            'location': DS.belongsTo('event')
        });
        // address model
        export default DS.Model.extend({
            '@type':    DS.attr('string', {defaultValue: 'Address'}),
            'country': DS.attr('string'),
            'locality': DS.attr('string'),
            'region': DS.attr('string'),
            'postalCode': DS.attr('number'),
            'streetAddress': DS.attr('string'),
            'location': DS.belongsTo('location', { async: false })
        });

     <!-- language: lang-js -->




samedi 25 novembre 2017

Ember TransitionTo with queryParams not working

I'm new to ember and I'm trying to use transitionTo with queryParams but I can't get it to work I tried a lot of the solution but I can't find out what is wrong with my code. here the code for the two routes I'm to transition between:

1- index.js:

export default Ember.Route.extend({
 setupController: function(controller, model) {
 this._super(controller, model);
 controller.set("model", model);
 },
 model() {
  return {
   searchQuery: ""
  };
 },
 actions: {
  search() {
   const query = this.controller.get("model.searchQuery");
   this.transitionTo("/search-results", {
     quaryParams: {
       q: query
     }
   });
  }
 }
});

2-search-results.js:

export default Ember.Route.extend({
 model() {
  return {
   fieldsInput: []
  };
 },
 setupController: function(controller, model) {
  this._super(controller, model);
  controller.set("model", model);
 }
});

I don't know if anything else should be added. I tried setting queryParams on the controller but it didn't work either. also, I tried adding

  queryParams: {
   q: ""
  },

to the search results route but no use.




ember-cp-validations conditional validator

I'm using ember-cp-validations on models and forms. I want a validation to be active only when certain conditions are met. Like, when a route is active or when a component is used in a particular context.

To illustrate, I have a basic email model that has typical validations on the model itself. When that model is being used in the context of a user account, I want an additional validator to be active (a username-exists validator, used to tell if they are trying to update their email address to one that exists on another account).

My email model:

import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';

const { attr } = DS;

const Validations = buildValidations({
    email: {
        validators: [
            validator('presence', { presence: true, description: 'E-Mail'}),
            validator('format', {
                type: 'email'
            }),
            validator('length', {
                max: 200,
            })
        ]
    },
});

export default DS.Model.extend(Validations, {
    email: attr('string'),
    optin: attr('boolean', { defaultValue: false })
});

I already have a username-exists custom validator. I just can't figure out how to add that validation conditionally.

The simplest solution would be adding the validated with a disabled option that keeps it disabled unless a condition is met.

validator('username-available', {
    debounce: 300,
    disabled: computed.bool(what is the dependent key??)
})   

But I have no idea what the dependent key would be. I don't think the route name is available in the model definition.

Or should I add the conditional validator to the component itself? Is there a way to append a validator to the validators array from the component js?

I think I am probably missing something obvious ;)




How can I import Handlebars compiler in ember-cli?

I'm building an Ember app and I use ember-cli. The version of Ember is 2.14. I need to compile client side a string into a Handlebars template, for this reason I know that I have to import the module. Now, in my package.json I have ember-source, which have Handlebars inside. Is there a correct way to use it and import it in the right way? I tried with import Source from 'ember-source'; at the beginning of the file and then use it as Source.Handlebars.compile(textToCompile); but it didn't work.

Also, if the answer is nope, is there a way, in general, to import the Handlebars compiler easily for an ember-cli project?

Thank so much.




vendredi 24 novembre 2017

EmberJs: modelFor() returns nothing from parameterized child-route

I have problems getting the parent route-model in a child route with this.modelFor(), because returning undefined in a specific child route.

The routes-structure:

// router.js
....
this.route('backstage', function() {
   this.route('schedules', function() {
      this.route('production', {path: ":production_id"}, function() {
         this.route('develop');
      });
...

in backstage.schedules' route.js:

// route.js
model() {
    return Ember.RSVP.hash({
        productions: this.store.findAll('production'),
    });
},

in backstage.schedules.production's route.js:

model(params) {
    console.log(this.modelFor('backstage.schedules'));  
    // this gives me the correct data for the schedules' model, 
    // hence the productions: {productions: Class}

    return this.store.findRecord('production', params.production_id);
},

and in the template for this route I can access it's model, so it is resolving successfully:

production label:   // prints the production's label

So, it all good till there.
But one level deeper I get the troubles:

in backstage.schedules.production.develop

model() {
    console.log(this.get('routeName')); // backstage.schedules.production.develop
    console.log(this.modelFor('backstage.schedule')); // undefined
    console.log(this.modelFor('backstage.schedule.production'));  // undefined
    return Ember.RSVP.hash({
        production: this.modelFor('production'), 
                 // won't work because it's undefined
                 // I also don't have access to the params of the parent route
    });
},

also in the corresponding template

  // undefined in console
   // reders to [object Object]
  // nothing

I get nothing back.
Could it be, that it's just not possible for dynamic route-models?
Or is there anything I'm doing wrong?

Yes, I know I could get the production in the controller, but I need to setup several other models in the route depending on (beeing filtered by) the production

Infos:
Ember-Cli 2.16
the route in question: http://localhost:4200/backstage/schedules/2/develop




Passing $.geJSON object to another ember controller

So i'm struggling getting this to work. Maybe my aproatch is not good. I'm quite noob at using a Frontend framework like ember.js.

So, i've got a $.getJSON request obtaining a JSON data from a local file. The problem is that I need to pass this data, not to the template but to another object inside one ember controller.

I'm trying to use ember-cli-charts to I need to return the object in the last lines of the propierty.

  diffData: Ember.computed('model', function(){

    let url = "log_hr24_diff.json";
    let diff_data = Ember.$.getJSON(url);         

    return {
      labels: ['Difficulty', 'Date'],
      datasets: [
      {
        label: "Difficulty",
        data: diff_data
        },
        {
        label: "Date",
        data: date_data
        }
      ]
    }
  })

So that is not working. Either do this:

let diff_data = Ember.$.getJSON(url).then(function(data){
       return Ember.Object.create(data);
    });

So how do I get the JSON object from the diff_data JSON response to pass it to the return object?

Tried and search it a lot, but couldn't find an answer.

Thanks in advance!




Generating additional js file to be shared with Ember app

I would like my Ember app to generate an extra javascript file that can be consumed by non-ember apps, so the code can be shared without creating an extra project just for it.

Inside the app, I create a public folder with two files, index.js and notifications.js to test if the pipeline is working:

/app
  /public
     index.js
     notification.js

And the files:

//notification.js
export function test(){console.log('test')}

//index.js
import {test} from "./notifications"; 

window.console.log('loading...'); $(document).ready(function() { window.console.log('initializing...'); window.test = test; }); Then in ember-cli-build file I create as a new output:

// ember-cli-build
app.import('app/public/index.js', { outputFile: 'assets/public.js' });

The transpiling seems to be working ok, but just creates a module out of index.js to be imported inside the app

 define('app/public/index', ['app/public/notifications'], function (_notifications) {
  'use strict';

  window.console.log('loading...');

  $(document).ready(function () {
    window.console.log('initializing...');
    window.test = test;
  });
});//# sourceMappingURL=public.map

How can I generate a lib that can be consumed directly in the browser?




jeudi 23 novembre 2017

Ember datatables not able to redraw after changing data

I am using ember-datatables addon which is based on jquery Datatables. I have created one datatables as per their guidelines.

But I am chaning the data of table after some time and redrawing the table. Redrawing table do not delete previous data.

Here is Ember twiddle created by me. Also I am adding code below.

templates/application.hbs

<h1>Please find data table below</h1>


  <thead>
    <tr>
      <th>Name</th>
      <th>Salary</th>
      <th>Position</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
      <th>Salary</th>
      <th>Position</th>
    </tr>
  </tfoot>
  <tbody>
    
        <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    
  </tbody>


routes/application.js

import Ember from 'ember';

export default Ember.Route.extend({
  setupController: function() {
    Ember.run.later(this, function() {
      this.controller.set('data1', [{
        'name': 'John Smith 1',
        'salary': '$2000',
        'position': 'developer'
      }, {
        'name': 'Alex 1',
        'salary': '$2000',
        'position': 'developer'
      }, {
        'name': 'Leonardo 1',
        'salary': '$2000',
        'position': 'developer'
      }]);

      var api = new $.fn.dataTable.Api('#myTable');
      api.row.clear();

      api.draw();

    }, 5000);
  }
});

controllers/application.js

import Ember from 'ember';

export default Ember.Controller.extend({
  appName: 'Ember Twiddle',
  data1: [{
    'name': 'John Smith',
    'salary': '$2000',
    'position': 'developer'
  }, {
    'name': 'Alex',
    'salary': '$2000',
    'position': 'developer'
  }, {
    'name': 'Leonardo',
    'salary': '$2000',
    'position': 'developer'
  }]
});




Ember Data Snapshot and how to detect changes?

I'm writing my own adapter/serializer. In order to send data to backend, I have to detect changes in DS.Snapshot and original Ember object. For ordinary attributes, it is possible to changedAttributes() but I did not found a way how to detect changes in hasMany relations.

I can detect new relation using snapshot.hasMany('foo') and changedAttributes(). But this approach is not able to find deleted relations.




ember.js Need to see if I can write Ember model items to a file then download

So I am new to ember (and stackOverflow) and have an issue that I am trying to work through. I have a model for list items that I am able to add into, update, and delete and everything on that end works fine. What I would like to do is to try and take the items in the model and write them to a formatted text file to download.

The model data is fine.
I know I can use this code to download a file from a url: < a href="urlFile" download="filename">

I just don't see any guides that can get me from the model to the download and I was wondering if anyone had any suggestions that could point me in the right directions. Thanks.




mercredi 22 novembre 2017

Unspecified Error in Office Addin Dialog Window

I'm developing a Word Addin for Word 2016 and getting a rather unhelpful error in the Dialog window; Unspecified error. It appears to be occurring at a history.replaceState call but I'm having trouble figuring out why.

The Dialog window contains a web app in an iframe and seems to break when it attempts to load the web app. I have a stack trace:

Error: Unspecified error.
  at replaceState (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:43050:7)
  at initState (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:42930:7)
  at applyStr (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:58464:7)
  at tryInvoke (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:58954:7)
  at Anonymous function (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:42582:7)
  at _setupLocation (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:46600:11)
  at setupRouter (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:46242:7)
  at startRouting (https://localhost:4200/assets/vendor-63142ea35c982dab5ee087d2647e494f.js:46227:7)

The web app works in IE11 and Edge - just not in the Dialog window of the Word 2016. I should note the Word Addin works in Office Online and Word for Mac (v15.30).

My question is: does anyone have any intuition or insights as to why/where this might be happening? I'm completely stumped. Anything to point me in the right direction?

Sorry it's all a bit vague but that's all I've got to go on - hence, why I'm having trouble. I'm using Windows 10 and the web app is Ember 2.13.3.




Ember Installation Issue: SyntaxError: Use of const in strict mode

When trying to install Ember.js on Windows (and possibly other systems), after running the following commands:

npm install -g npm
npm install -g ember-cli
npm install -g bower

No errors are raised, how the command ember -v outputs the following:

C:\Users\<user>\AppData\Roaming\npm\node_modules\ember-cli\lib\cli\index.js:3
const willInterruptProcess = require('../utilities/will-interrupt-process');
^^^^^
SyntaxError: Use of const in strict mode.
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at C:\Users\Shayn\AppData\Roaming\npm\node_modules\ember-cli\bin\ember:26:11
    at C:\Users\Shayn\AppData\Roaming\npm\node_modules\ember-cli\node_modules\resolve\lib\async.js:50:13
    at processDirs (C:\Users\Shayn\AppData\Roaming\npm\node_modules\ember-cli\node_modules\resolve\lib\async.js:182:39)

This suggests an issue with my Ember installation, how can I address this?




ember-cli-pagination - how to scroll to top of page on page change?

I've got the at the bottom of the page. When I click a page number, the page loads fine, but I'm still at the bottom of the page.

How can I get it to scroll to the top when changing pages?

Is there a better addon to use for this?




Check class names of nested divs || Ember/Mocha/Chai tests?

So I am writing integration tests using Mocha and Chai. I am new to tests.

Long story short.

I installed couple Chai jQuery plugins like chai-dom , chai-jq and chai-jquery.

I am running the tests by "ember test --server"

I have a div with a ".navigation" class. This div has three nested divs, each with a unique class.

In my tests, I am checking if the parent div exists:

should.exist('.navigation');

How can I "expect" the other 3 nested divs to have the classes I want?

I want something like:

expect($('.navigation)).children[0].to.have.class('flex1')

OR

expect($('.navigation)).children().to.have.class('flex1, flex2, flex3')

OR

expect($('.navigation)).descendants.to.have.class('flex1, flex2, flex3')

Something like that..?

Same goes to IDs I believe?

Thank you in advance.

Mo.




How can I load an external config file with Ember JS

Is there a way with Ember JS to avoid building the application for all the environment but instead build the app ONCE and the have the app dynamically load the right config file at runtime ?

This way we can put the right config file when we deploy and we only have to build the app once for all our environments




How to use shared components in multiple apps without addon

we have a four apps that share a lot of components. So far we use addons to manage this shared code, but we're facing a lot of troubles with addons approach.

Something like this:

App1
- basic-form-elements-addon
- feedback-form-addon
- tables-management-addon
App2
- feedback-form-addon
- tables-management-addon
App3
- basic-form-elements-addon
App4
- basic-form-elements-addon
- tables-management-addon

The problem with this approach is that updating an addon is a quite long process involving a lot of steps:

  1. Link addon into app (using yarn link)
  2. Modify addon code
  3. Publish addon into npm
  4. Update dependency in App1
  5. (and possibly if I have a time and energy, update dependency and usage in App2,3,4 as well or leave it for someone else who touches that code :cry:)

Apart from this, there are other problems - maintaining 8 different ember apps costs a lot of time - updating ember versions - updating other dependencies - maintaining same linting configs and other tooling

these are the biggest issues we face now with this approach.

I don't know what's the best solution to this problem, but my idea was that we would - merge all addons into one addon (now that it's possible to require just part of the ember tree, it shouldn't have a bad impact of a code size, right?) - move all code into one repository (kind of monorepo) - use addon not as npm dependency, but somehow import it from the sibling directory (I don't know if this is possible)

so at the end, we would end up with something like this

git (monorepo)
- App1
- App2
- App3
- App4
- shared-code
--- components
--- helpers
--- models
--- ...

Is that possible? What would I need to do to achieve this setup? Or do you have a better solution?

Thank you for any kind of help, Ondrej




In need to either convert Spring's default HAL format to JSON API, or make Ember Data accept HAL json format

My Ember.js front-end application is to consume REST API created in Spring (Boot). The problem is: - Spring returns json response in HAL format - Ember Data expect the response to be fully compliant with JSON API specs

So far I have found that there are at least two "adapters" for each side.

This one is supposed to convince Ember Data to use the Spring's response as it is: ember-data-hal-9000

This one makes Spring's response compliant with JSON API specs: Katharsis - HATEOAS for Java based on JSON API standard

I've read that both have its own problems but has anyone successfully employed either of them? Ideally both of them, so a comparison can be made?




mardi 21 novembre 2017

How do I change a value in a .hbs file

posts.hbs

I want to add a suffix to the "onePost.id" value and it has to be done in this file.

<br>
<h2> Blog Posts </h2>   
<ul>


    <li id = > 
    </li><br>


</ul>






Using the same URL for multiple nested ember routes

I have a case using Ember where I want to make the top level URL available (ie. localhost:4200/demo), and have all the routes underneath also display the same URL (localhost:4200/demo). So the route file, if possible would look something like:

this.route('demo', function() {
  this.route('one', { path: '/' });
  this.route('submit', { path: '/' });
});

I understand that ENV.locationtype can be set for the whole app, but is there a way to conditionally set this for specific URLs underneath a parent URL?




Referencing global libraries from an ember component

I am using ember-remarkable because I want to add both markdown parsing and syntax highlighting to my project. The only thing it's missing is line numbers, which I want to add by using this library: highlightjs-line-numbers.js

I override ember-remarkable's md-text component with the following:

import MDTextComponent from 'ember-remarkable/components/md-text';

export default MDTextComponent.extend({
  tagName: null,

  didRender() {
    this._super(...arguments);

    this.$("code[class*='language-']").each((i, block) => {
      this.$(block).addClass('hljs');
      hljs.lineNumbersBlock(block);
    });
  }
});

Everything works! However, my editor complains that hljs is not defined, even though it is available on the page.

How do I avoid this error?




How do I pass a value from one .hbs file to another

I am trying to pass the index value from posts.hbs to the delete-post.hbs and then from delete-post.hbs to my delete-post.js function.

posts.hbs

<br>
<h2> Blog Posts </h2>
<ul>


    <li id = >  
    </li><br>


</ul>



delete-post.hbs

<a class="ui red button" >Delete</a>`

delete-post.js

    import Component from '@ember/component';

export default Component.extend
({
  actions:
  {
    deletePost(input)
    {
        alert(input);
    }   
  }

});




Ember 2.16 Error when creating a state hash in routes/application

Im new to ember coming from react. Inside the routes/application.js I want to use a "state" hash to hold variables outside supporting functions, model(), and actions().

Here is what works:

  session: Ember.inject.service(),
  servers: null,
  clients: null,
  variable3: null,
  variable4: null,
  variable3_id: null,
  selectedDate: null,
  currentUser: Ember.inject.service(),

and this is what I want to do:

state: {
    session: Ember.inject.service(),
    servers: null,
    clients: null,
    variable3: null,
    variable4: null,
    variable3_id: null,
    selectedDate: null,
    currentUser: Ember.inject.service(),
},

When I access it with, say get, get(this, 'state.session') I get this error:

ember.debug.js:29034 Error while processing route: analytics Assertion Failed: Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container. Error: Assertion Failed: Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.

When I dont put the variables in my state hash, and access with get, get(this, 'session') I dont get any issues. What is going on here? Did I provide enough info or am I missing something?

Thanks




what are ember js static data best practices

I have some static data which will never change, like the data behind menu items

{
  "menuItems": [{
    "name": "Shows",
    "route": "shows"
  }, {
    "name": "Podcasts",
    "route": "podcasts"
  }]
}

i created a json file in /dist folder and in the application route i'm creating a model from the file like

export default Route.extend({
  model() {
    return $.getJSON('/static/model.json')
  }
});

is there a better practice to initialize model with static data?




Remove a particular event listener in EmberJS

I would like to only listen the first didRender in a EmberJS Component.

initialDidRender: Ember.on('didRender', function() {
    // Do some stuff

    this.off('didRender');
}),

allOtherDidRender: Ember.on('didRender', function() {
    // Do some stuff
})

Using this.off works great for my usecase but if I want to define another didRender listener in the future, it will also remove that one.

Is there a way to only disable initialDidRender of my example?

I also tried this.set('initialDidRender', null); but it throw error on future didRender events.




EmberJS - How to print values from Model outside of type functions

My model (medid) is successfully loaded on my template (medid.hbs) but when I try to put a value from the record in as text it doesn't render anything.

In other templates everything I rendered from the model was in a table iterated on with an helper. Here I used to populate the table rows.

I assumed that I could just use something like 'Hello my name is but that doesn't work. I'm probably missing something obvious

How do I access my model data for printing outside of a handlebars helper?




lundi 20 novembre 2017

Equivalent to ember engines in react

In ember.js Ember Engines let you compose multiple standalone applications into a single application. Is there an equivalent in react.js?

What I want to do is provide a generic login page and serve different applications depending on which customer signes in.




How to use a filtered computed property with ember-drag-drop sortable-objects?

I'm using ember-drag-drop to implement a sortable list. This worked fine until I needed to implement a text filter on the list.


  
    
      
    
  


The filteredItems is a computed property which filters the original list based on a user's text input.

filteredRules: computed('items', 'term', function() {
  let term = this.get('term');
  let items = this.get('items');

  if (term.length > 0) {
    return items.filter(item => item.conditions.some(cond => cond.field.toLowerCase().indexOf(term) > -1 || (cond.term && cond.term.toLowerCase().indexOf(term) > -1)));
  } else {
    return items;
  }
}),

The problem is that a computed can't (normally) be written back to.

How can I still allow sorting of the original items data set while still allowing filtering?




Highchart is not showing in heroku, but works in local environment

I am using ember-highcharts in my app. I tested in my localhost and it is working fine, the graphic is showing in the screen.

I deployed my application in heroku, and try to show the graphic but the error below appears:

Uncaught TypeError: Cannot read property 'parentGroup' of undefined
at object.setState (highcharts.src.js:33606)
at SVGGElement. (highcharts.src.js:33080)

Here is my code:


  
 
  <div class="modal__warning">Dados insuficientes</div>


chartOptions: {
chart: {
  plotBackgroundColor: null,
  plotBorderWidth: 0,
  plotShadow: false
},
title: {
  text: null
},
tooltip: {
  pointFormat: '<b>{point.percentage:.1f}%</b>'
},
plotOptions: {
  pie: {
    colors: [
      '#60E0A1',
      '#F19692',
      '#d5d5d5',
      '#68599D',
      '#A69BC5'
    ],
    dataLabels: {
      enabled: false
    },
    size: '100%',
    showInLegend: true,
    startAngle: -90,
    endAngle: 90,
    center: ['50%', '100%']
  }
},
yAxis: {
  title: {
    text: null
  }
 }
}

Does anyone know what the problem could be? Just remember that in my local machine is working fine!

Thanks in advance :)




emberJS: Is it possible to use helpers in Component/controller Javascript?

If I create a helper, then it's straight forward to use it in HBS files. But can I use it in JS files of a controller or a component?




How to embed one ember application in another ember application?

I am having a simple ember application and I need to embed this into another ember application . How can I do this embedding ?




Multiple Files Download

i had the following code to download file(s)

var link = document.createElement("a");

link.setAttribute('download', null);
link.style.display = 'none';
document.body.appendChild( link );
response.forEach(function(download){
    link.setAttribute( 'href', download.link );
    link.setAttribute( 'download', download.filename );
    link.click();
});
document.body.removeChild( link );

however, i only able to initiate the download of 1 file, it suppose to have 2 files. The array response has the following attribute:

{ link: 'http://ift.tt/2zPUc6l', filename: 'file1.txt'} { link: 'http://ift.tt/2Af21D6', filename: 'file2.txt'}

Thanks




dimanche 19 novembre 2017

Broccoli-stew doesn't print anything

I tried using broccoli-stew (or broccoli-debug) to debug my tree, because I'm not sure if it's moving the correct files to the right location. When I import with app.import('vendor/my-app/file.css'); it gives me an error... I want to see my nodes

I tried using on treeForVendor(), but it doesn't do anything.

var Funnel = require('broccoli-funnel');
var MergeTrees = require('broccoli-merge-trees');
var log = require('broccoli-stew').log;

module.exports = {
    ...
    treeForVendor(vendorTree) { 
        var f = new Funnel(...);
        // here is the problem
        log(f, { output: 'tree', label: 'my-app tree'});
        // I don't want to print using console.log(f); 
        return new MergeTrees([vendorTree, f]);
    }
    ...
}




samedi 18 novembre 2017

Ember.js: "this.$()" not working on component

Method this.$() is not working on a component. Following code:

app/components/example-component.js:

import Ember from 'ember';

export default Ember.Component.extend({

  exampleMethod() {
    console.log('"this" on exampleMethod():');
    console.log(this);
    console.log(this.$());
  },
});

Gets following error on web console:

TypeError: this.$ is not a function

How is this.$() to be used and how to get the jQuery element of a component?

Environment:

DEBUG: -------------------------------
DEBUG: Ember : 2.13.0
DEBUG: Ember Data : 2.13.1
DEBUG: jQuery : 3.2.1
DEBUG: Ember Simple Auth : 1.3.0
DEBUG: -------------------------------




Accessing my VMware Ubuntu client through Wi-Fi network

I am trying to connect to my client VM through my home network but am not able to do it. Hopefully I am able to explain my situation - it is way out of my field. :/ The client runs Ember server.

Through the Virtual Network Editor and NAT settings, I am able to expose the client's Ember port (4200) to the shame port of my Host. So hitting localhost:4200 shows the ember application.

My host is ethernet-connected to the router and has an ip 192.168.1.110 which I can access through the Wi-Fi network. What I am trying to achieve is hitting 192.168.1.110:4200 through the Wi-Fi network and exposing the Ember application.

I am not sure if what I want to achieve has to do with my router's forwarding, with VMWare settings, or anything else. :/

Edit: Host is running Windows 10.




vendredi 17 novembre 2017

Ember Component can't use vendor.js function

I adopted a legacy project that uses EmberJS 2.5.1, and I have a component that is unable to use the JQuery UI Sortable method. The vendor folder contains jquery.ui.min.js, and ember-cli-build.js imports it.

This is what I currently have in my code:

Ember.$("#cute_table_of_puppies_eating_clowns tbody").sortable({}) (Sortable has been simplified for example purposes...)

In Chrome's Debugger it converts to...

_ember["default"].$("#cute_table_of_puppies_eating_clowns tbody").sortable({})

The JQuery selector works, but it cannot find the selector. I put a break point on that line, and tried $("#cute_table_of_puppies_eating_clowns tbody").sortable({}) from the console. This ends up working.

What do I need to do to properly use this function from a component?




Route model not rendered when using filter on route change

I'm trying to setup mirage on a new app for testing.

ember-cli: 2.16.2

ember-cli-mirage: 0.4.0

I have a dummy test, just trying to setup mirage and verify it's working. I would do something similar to test route.model(). Using mirage's JSONAPISerializer, nothing in my factory and migrage-model.

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

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

My test :

import {moduleFor, test} from 'ember-qunit';
import {startMirage} from 'frontend/initializers/ember-cli-mirage';

moduleFor('route:trips.index', 'Unit | Route | trips.index', {
  needs: ['service:session', 'model:trip', 'adapter:application'],

  beforeEach() {
    this.server = startMirage();
  },

  afterEach() {
    this.server.shutdown();
  }
});

test('model', function (assert) {
  let route = this.subject();

  this.server.create('trip');

  Ember.run(() => {
    this.get('store').findAll('trip')
  });

  assert.ok(route);
});

I get this error:

TypeError: Cannot read property 'push' of null
    at Class._setupRelationshipsForModel

Works fine on development/production and using a real server to get the data.

If i dont create my record with mirage, there is no exception.

Looks like the problem only occurs within Ember.run

This will not raise the exception, but I think I need Ember.run to test properly...

test('model', function (assert) {
  let route = this.subject();

  this.server.create('trip');

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

  assert.ok(route);
});




How to pass `action` through `locale` string?

here is my local string:

'CS2I.navbar.title' : 'Split Your Bills <a href="#" >Link</a>',

After I am getting the template, there action disappears. how to pass the action through locale?

any help?




EmberJS - How to update dateFrom Query Param with Pikaday input

I am using the following input from the ember-pikaday addon:

<div class="col-sm-3"><label>Date From:</label></div>

I cannot get the value of the input to update the query parameter in the URL. If I use a standard input it works in the following controller:

import Controller from '@ember/controller';

export default Controller.extend({

queryParams: ['dateFrom', 'dateTo', 'unitNumber'],
dateFrom: null,
dateTo: null,
unitNumber: null,

  actions: {
    selected(x){
      module = x
    },

    submitQuery(dateFrom, dateTo, unitNumber){
        switch(module) {
          case 'Option 1':
          this.transitionToRoute('option1', {queryParams: {dateFrom: this.get('dateFrom'), dateTo: this.get('dateTo'), unitNumber: this.get('unitNumber') }})
        break;

//switch statement truncated for readability
    }
   }
  }
});

I suspect I need an action when a date is selected but I do not know how to handle the update within the action. I tried the following:

//onSelection=(action 'select') added to pikday input

select() {
dateFrom = this.set('dateFrom')
}

But it did not represent in the URL. I think that would be incorrect scoping anyway. I am still very new to Ember (and coding). Any help would be very appreciated.




jeudi 16 novembre 2017

What do ember server and ng serve really do?

I've read this Q&A:

What happens when you run ng serve?

It explains that when setting up an Angular 4 app using the official Angular quickstart steps (using Angular CLI to scaffold the Angular 'project'), and then running this command via the Angular CLI:

ng serve --open

... that what actually seems to be happening is that ng serve is doing the same as what the Ember server does, as it somehow 'piggybacks' on Ember. But what is the Angular server actually doing? This is JavaScript that will all be executed client-side. I'm not following why we need a server for Angular, and in what respect that the server is a 'server' at all. To be clear what I mean, why would we need a server to run the app in the client?? What is the Angular server really doing, and how should I think about this 'server' - I mean what is now our 'client'?




Ember JS best way to show a full screen loading screen button press

I'm new with Ember and I would like to show a full screen overlay when a user press a "get stuff from server" button.

What is the best way to achieve this? Does Ember already provide something built-in? Or the only way is to have a piece of HTML in one of my template and show/hide it when the promise where I make the ajax call returns?




Is it possible to build in-repo addon structure that optionally extends a base addon but the app remains unaware of that?

I'm trying to make a base in-repo addon that provides functionality through namespace like platform/services/whatever.

In addition to that I want if another addon isEnabled() that extends or reopens that same service (in some way) I want it to all be merged together without having to call the second addon's service by name like platform-second/services/whatever

I just want a nice clean abstraction. The reason I'm doing it this way is because based on an ENV variable, I need to build / inject different stuff into index.html and different app.imports.

and I want it to be completely separated into separate little in-repo addons to keep it clean.

I want the app to not need to know the platform but just be able to utilize methods of the general platform addon.

So for example platform.services.whatever.myMethod() might be a noOp by default, but if the second addon extends that and implements that, it'll fire that version instead automatically.

Wonder if I'm making any sense at all LOL

If you have any tips or advice on how one might implement this setup, please let me know.

I currently have the in-repo addons built but ideally I'd have the base platform addon be the one that actually has the app folder contents and the other addons that "extend" or "override" the methods / properties of that addon's objects would just be isEnabled() based on that ENV variable.

I should add that I can't simply do merge tree and override the original file because I need the base functionality of those files.

So if I extend one method of the base platform.services.whatever.myMethod() then I still need the rest of that services methods and properties as well.




Ember.js : Custom file structure & file naming

I want to use the following file structure and file naming:

/app
  /components
    /some-component
      component.some-component.template.hbs
      component.some-component.class.js
  /routes
    /some-route
      route.some-route.handler.js
      route.some-route.template.hbs
      route.some-route.controller.js
  /models
   model.some-model.js

It's kind of similar to the pods structure but it's not exactly it since the file naming is totally different.

Any hints on how I can achieve this? I tried overriding Resolver methods as it's been suggested here but this is only for when you use pods and you simply want to group all of you route-folders in one parent-folder.




encoding problems unicode to utf8 with nodejs/emberjs

I come back with a new question, here we go I transfered an emberJs application from GoogleCloud to a new server OVH. But eversince I got encoding problem.

I get a json response containing those character '\u0102\u0160' before it was decoded as é but instead I have a foncĂŠs. It is the exact same code.

Can anyone help me with that issue ?




mercredi 15 novembre 2017

How to add content to ember component dynamically

I am writing a web application in ember.js for the first time. I'm using ember-leaflet in order to create a map, which is the main page of the application. The map is located in a component called main-map and looks like:



  
    
      
    
  

  
    
      
    
  

  


This main-map component is located in my application.hbs so it is present in all routes in my website. In one route that I have, called search-address, I need to add a marker to the map based on the user input. The marker will look something like:


   
     <h4> My address </h4>
   
 

I need a way to modify the main-map from within my search-address.js file in order to add these markers to my map. How can I accomplish this in Ember?




Convert number to tuple (latin) name

Wikipedia defines names for tuples (multiples) of specific length (up to 31 and some significant others afterwards) at http://ift.tt/2z4qqec.

For example:

  • 1 = single
  • 2 = double
  • 3 = triple
  • 4 = quadruple
  • 5 = quintuple
  • 6 = sextuple

Is there an easy way in JavaScript (specifically Ember) to convert from a number to the named tuple. So I could do something like

console.log(numberToNamedTuple(5)); // quintuple

At the moment I am anticipating copying and pasting the list from wikipedia into an array and then writing a function to do a lookup on that. Is there an existing function I should be using instead or something I have overlooked perhaps?

Please note this question is related to the mathematic / real world definition of a tuple rather than the programming use of tuples as per python and other languages.




Is there a way to get my page URL to update when changing steps within a Single-Page Ember Application?

I have a client of mine who's using a single page application, built in Ember, and they are trying to use analytics to measure dropoff rates at each stage of the form.

I need to try to give them a trigger they can fire when a new stage is reached, in order to update the URL of the page, thereby allowing them to track it in analytics.

Is this even the best way to achieve this?

Hopefully this makes sense, sorry, total lack of Ember knowledge on my side.

Thanks




i18n - How to use it in application.hbs?

In which route/component should I inject the "i18n" service for it to be used in application.hbs? I'm trying to use it in other HBS files, and if I inject "i18n" into the route/component - I'm able to use it.

But it's just not working in application.hbs




EmberJS - Sending form input values via query param to execute a query

I currently have a form that has 4 inputs. The first input is a selector and the other 3 are parameters for executing a query based on date range or customer ID.

I am trying to send the values of the inputs to a route so that I can return the query results via my RESTAdapter.

Here is the form on my template:

<div class="col-sm-3"><label>Module:</label>

            
            
            
            
            
  
        </div>

          <div class="col-sm-3"><label>Date From:</label></div>
          <div class="col-sm-3"><label>Date To:</label></div>
          <div class="col-sm-3"><label>Customer ID:</label></div>
          <div class="col-lg-10 col-lg-offset-5" style="margin-top:15px">
            <button type="reset" class="btn btn-default">Reset</button>
            <button type="submit"class="btn btn-info">Submit</button>
            </div>

To handle this I have the following in my controller:

module: null, //Variable to hold the value of the first 'Select a Module' input

actions: {
  selected(x){
    module = x
},

  submitQuery(dateFrom){ //dateFrom added as an example of an input
      switch(module) {
        case 'Option1':
         this.transitionToRoute('Option1') 

I have tried adding query params to the this.transitionToRoute like this.transitionToRoute('Option1', queryParams: {dateFrom: 'dateFrom'}) but the item doesn't appear in the URL on the new route upon Submit.

I've also tried adding the query params on the controller as a standalone object like:

queryParams: ['dateFrom'],
  dateFrom: this.get('dateFrom'),

but this stops the template from rendering with an error to say that dateFrom is undefined. This is the same with any variation of http://ift.tt/2AMN48m etc.

I don't know if my mistake is how am trying to access the values or in how I have set up my controller.

My desired result is a case where I can submit the following query from the form:

Select from Option one where where list_date >= date(dateFrom) and list_date <= date(dateTo) //(customer ID is option and handled seperately but you get the idea)




mardi 14 novembre 2017

Ember.js load data on template

I want to load data from model to template in ember as shown in code

        import Ember from 'ember';
         const { Route, RSVP, set } = Ember;
          export default Ember.Route.extend({
          csvDataService: Ember.inject.service(),
          apiService: Ember.inject.service(),
          selectedDescription:"",
            model() {
            const performanceIndicatorData = this.get('csvDataService').getPerformanceIndicatorData();
            const sites = this.store.findAll('site');
            const units = this.store.findAll('unit');
            const components = this.store.findAll('component');
            const advice=apiService.get("advice-list").then((res)=> { return res;},(error) => {});

            return Ember.RSVP.hash({
              performanceIndicatorData, sites, units, components,advice
                });
          },
          setupController(controller, model) {
              set(controller, 'sites', model.sites);
              set(controller, 'units', model.units);
              set(controller, 'components', model.components);
              set(controller, 'performanceIndicatorData', model.performanceIndicatorData);
              set(controller, 'advice', model.advice)
           },

    })

As shown in above code from model to template , I am returning complete promise after getting the data so how can I return one by one data so that whatever data will come from backed , it will not wait for entire data, it render to template




How to use mongodb from ember acceptance test?

I use ember mocha for testing, and I don’t know why I can’t use the package npm mongodb from my acceptance test.

In my acceptance test I import :

` import mongodb from ‘myproject/app/helpers/mongodbp’;

In this file mongodbp.js I have :

    import  mongodb  from 'npm:mongodb';
export default mongodb;

But when I use mongodb from my acceptance test, I catch the following error :

‘TypeError: net.createConnection is not a function*********’

/* jshint expr:true */
import {
  describe,
  it,
  after,
  before,
  beforeEach,
  afterEach
} from 'mocha';
import { expect } from 'chai';
import Ember from 'ember';
import startApp from '../helpers/start-app';
import destroyApp from '../helpers/destroy-app';
import { LoginPage } from './LoginPage';

import mongodb from 'myApp/helpers/mongodbp';

describe('Acceptance: Users', function () {
  this.timeout(15000);

  var application;

  beforeEach(function () {  
    application = startApp();

    mongodb.MongoClient.connect('mongodb://localhost:27017/myDb', function (err, db) {
      if(err)
        {
            console.log("***************************"+err+"************************************");
        }
        else {
        // Fetch a collection
        var collection = db.collection('users');

        // Insert a document (insert user)
        collection.insertOne(jsonfile, function (err, result) {

            // Force close the connection
            db.close();
        });
      }

    });

    var page = new LoginPage();
    page.loginmyApp();
  });

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

  it('consult user added', function () {

   click('#user-test');
   this.timeout(15000);
   andThen(function () {
    expect(currentPath()).to.equal('users.index');


  });

  });

});

How can I use mongodb from my acceptance tests in the before hook ?

Thanks in advance




ember Error: Compile Error: is not a helper

I got the following error while developing our front-end with Ember.js:

ember Error: Compile Error: '...' is not a helper

What is the meaning of this error?




lundi 13 novembre 2017

EmberJS - user signin - what's the best way to approach?

I have a layout for user to signin, with the usual "user firstname", "lastname", "email" and a few more fields. I'm using "component" to show this content to the user. I also need to validate this data locally.

Now I need to tie the UI to the data. I have two options: 1. Use model 2. Use member variables in component

And when everything is okay, when user clicks on the "register" button, I need to send this data to the back-end.

What do you suggest is the best way to do this?




Access variable in Ember controller

how can I access a variable in Ember controller? I've tried those methods, but it doesn't work:

import ObjectController from '@ember/controller';
export default ObjectController.extend({

  currentPhase: 1,

  init: function () {
      var selfReference = this;
      this.set("currentPhase",1);
  },

  strings: {
      title: "Title",
      phase1: "Fase " + selfReference.get("currentPhase"),
      phase2: "Fase " + currentPhase
  }
});




How to display multiple routes in one page using Ember js?

I'm new to Ember and I'm stuck with an issue that I cannot solve. I have two routes - home and lhstree. When /home is called, I need both the routes to be rendered ie. lhstree should be rendered within home template. For this purpose, I used named outlet. That worked fine. But the problem is, I need to supply data to the lhstree template. But the model hook for the lhstree template is never called. I even tried adding alert messages in the model hook, but that too is never executed. The below is my code. Any help is appreciated.

router.js

Router.map(function() {
 this.route('home');
 this.route('lhstree');
});

home.hbs

<html>
<head>
</head>
<body>
    Home hbs rendering
    
</body>
</html>

home.js

export default Route.extend({
    renderTemplate:function()
    {
        this.render();
        this.render('lhstree',{outlet:'lhstree',into:'home'});
    }

});

lhstree.hbs

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

lhstree.js

model() //THIS MODEL IS NEVER CALLED
{
  return ['Player1', 'Player2'];
  }

As I mentioned, the model hook of lhstree route is never called. So, the player names Player1 and Player2 are never displayed when home template is rendered.




ember-pikaday does not create action when value is changed to null

I'm using ember-pikaday on my web application. I have faced a problem while I'm testing my date component. When the value is set to null, it does not create action, and the binding value remains the last setted value. This is my component:



This is my test.

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

moduleForComponent('my-component', 'TODO: put something here', {
  integration: true
});

 function updateDateValue(_this, val){
   let datecomponent = _this.$('input');
   datecomponent.click();
   datecomponent.val(val);
   datecomponent[0].dispatchEvent(new Event('change'));
 }

  test('it renders', function(assert) {

  let actionListenerValue;
  this.on('myaction', function(val) { actionListenerValue=val; });

  this.render(hbs``);

  updateDateValue(this, '01.04.2016');

  assert.equal(this.$('input').val(), '01.04.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '01.04.2016');

  updateDateValue(this, '05.02.2016');
  assert.equal(this.$('input').val(), '05.02.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '05.02.2016');

  updateDateValue(this, null);
  assert.notOk(this.$('input').val());
  assert.notOk(actionListenerValue); // this line throws error

});

I have prepared a twiddle of my problem.




ember-drag-sort: implementing a sortable list based on an HTML table?

Originally asked by @livfwd on GitHub.

It seems like the :before :after pseudo-elements break the table layout and put the placeholder in unexpected places when dragging rows within a table.

Are there any known workarounds for this?




ember-drag-sort: how to determine the new parent in the dragged list?

Originally asked by @andrewsyd on GitHub.

For a nested list, is there a way to determine in the dragEnd action which "sub-list" the item has been dropped into? (e.g. a class name, id etc)

In my scenario, I am sorting ember data records that can belong to each other (i.e. a nested, 'tree' structure). When I drag one nested record "into" another (making the dragged record a child of the second record), I need to update the parent attribute in ember-data. My question is, how do you pass some id of the second record (the new parent) to the dragEnd action?

Is this even possible?




Ember-Flexi component not working in Windows machine

I am newly to EmberJs,here i am using ember flexi component,my problem is flexi is fetch the page based on the device is working in MAC,but not working in windows Machine,its showing blank page only. Note: Not getting any Error message also, Thanks in Advance




dimanche 12 novembre 2017

Identifying targetList in ember-drag-sort

I am currently trying to implement ember-drag-sort into my Ember.js app.

Is there a way to determine in the dragEnd action which list the targetList is actually referring to? (e.g. a class name)

In my scenario, I am sorting ember data records that can belong to each other (i.e. nested structure). When I drag one record "into" another (the target list), I need to set the dragged record's parent as the record the target list represents.

Is this possible?




Cannot call a router action from the view

Here are my routes :

this.route('produits', function(){ 
  this.route('new');
  this.route('edit', { path: '/:produit_id/edit' }, function() {
    this.route('documents');
  });
});

Here is my action in routes/produit/edit/documents.js :

actions: {
    refreshRoute() {
      this.refresh();
    }   
}

In document.hbs as soon as I use , it result in the following error: Assertion Failed: An action named 'refreshRoute' was not found in (generated produits.edit.documents controller)

Why is it not working, when using the same syntax works in CRUD views?




samedi 11 novembre 2017

How can I pass arguments to an ember service while it is injected?

I have a component, say MyComponent. I have injected a service into this component, say MyService.

When 'MyComponent' is used inside another component(say ParentComponent), it passes some arguments to 'MyComponent' through the template. 'MyService' which is injected in 'MyComponent' needs this template arguments. How can I pass it to the service while injecting the service?

Right now I have written a special function inside the service which will be called in the init() function of 'MyComponent'. I don't know if that is the right way.

Here is a rough code example:

parent-component/template.hbs:

// some html

// some html

my-component/component.js:

export default Component.extend({
 // some js
 myService: inject.service(),
 init() {
  this._super(...arguments);
  get(this, 'myService').passDownMyArguments(get(this, 'myOptions'));
 },
 // some js again
})

I want to know if I can pass 'myOptions' to the service when it is injected rather than calling another function within the service.




vendredi 10 novembre 2017

Ember, relations, and multiple calls

I have a route with the following model :

model() {
const product = this.modelFor('products.edit');
return Ember.RSVP.hash({
  product: product
});
},

WHen I disclay product.licences it shows all the licence from the product.

If I add this line :

const allLicences = this.get('store').findAll('licence'); 

To get a list of licences that can be added to the product, without even returning it via the RSVP, I end up with all the licence in product.licences.

Why does ember act like that? Des he assume every licence in memory is linked to the product?




How to get the data object from a single record in the model?

Recently this became a bug in my application, although I don't know what changed to make it so (I haven't upgraded the version of Ember, which is still 1.13). What I need to find out is how to access the object of a single record on the model in the conventional way.

I have the following code to filter my model based on two other properties:

  recordsBySelectedShapeAndColor = get(this, "model").filter(function(rec) {
    //filter the model by the chosen shape and color
    return (
      get(rec, "shape") === theShape &&
      get(rec, "color") === theColor
    );
  });

I then need to create a summary of those filtered records, which I'm using reduce() for, but if that filter returns only one record, then reduce doesn't return the right results, so I have the following condition:

if (recordsBySelectedShapeAndColor.length < 2) {
  summary = recordsBySelectedShapeAndColor[0]._data;
} else {
  summary = recordsBySelectedShapeAndColor.reduce(function(a, b) {
...
}

It's the line within the if that is no longer returning the a simple object, so I changed it to summary = recordsBySelectedShapeAndColor[0]._internalModel._data; and it works, but it seems fishy (._data always did too). Is it code smell to be accessing underscored properties? If so, how can I get just the data from that single record on the model?




How to remove the data from array?

This is the data saving in my rethinkdb database. and i save the data for addtowatchlater is array. I use ember.js for frontend and tornado for backend and database for rethinkdb.

{ "accesstoken": "ajflasjjfasjfjasfasdfjasjflsajjfas" ,

"addtowatchlater": [

{"beatdescription": "aa" , "beatname": "aa" , "categoryname": "DJ" , "filename": "asfasdfasdfasdfa" , "id": "423423454352342344545423434" , "price": "aa" , "soldout": "No" , "stamp": "1510244267000" , "userid": "816fbfe8-ea81-4198-98f0-5fb0db01e25e" },

{ "beatdescription": "aa" , "beatname": "aa" , "categoryname": "DJ" , "filename": "asfasdfasdfasdfa" , "id": "423423454352342344545423434" , "price": "aa" , "soldout": "No" , "stamp": "1510244267000" , "userid": "816fbfe8-ea81-4198-98f0-5fb0db01e25e"}] ,

"id": "et4545er5454354354354353" ,

"role": "user" ,

"status": "Active" , }

I want to Remove one json data from addtowatchlater array field. when i remove i want like this for example.

{ "accesstoken": "ajflasjjfasjfjasfasdfjasjflsajjfas" ,

"addtowatchlater": [

{ "beatdescription": "aa" , "beatname": "aa" , "categoryname": "DJ" , "filename": "asfasdfasdfasdfa" , "id": "423423454352342344545423434" , "price": "aa" , "soldout": "No" , "stamp": "1510244267000" , "userid": "816fbfe8-ea81-4198-98f0-5fb0db01e25e"}

] ,

"id": "et4545er5454354354354353" ,

"role": "user" ,

"status": "Active" , }

I want like this. I Don't know how to do. please help me. please help me how to do. Reall Thanks




Update model(then on-screen data) after updating an adapter's host name for accessing API

I'm loading data into my Ember-Data store using an adapter(has 2 properties - 'host' and 'namespace').

For argument's sake, let's say our host-name is "https://yyyyy.com", and let's say the data is about customers. The namespace could be 'api'. With that in mind, a common request could be directed to "http://ift.tt/2Ar662V".

For simplicity, this returns an array of JSON objects, and each object only has a single key - that being 'id'. What i'd like to do is access customer data from a different runtime dynamically from within the same app. This means that through the use of some event - for example an "onclick", we change the host from "https://yyyyy.com" to "https://zzzzz.com".

Here's the data I currently have, followed by what i've attempted, and its results:

/templates/customers.hbs

<h3>Customers route</h3>

<button >test importing the new adapter host</button>

    
  ID:      


/routes/customers.js

import Ember from 'ember';   
const { Route, set } = Ember;

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

  //use of 'reload' is to prevent loading records from cache
  return this.store.findAll('customer', {reload: true});

  },

  setupController(controller, model){    
    set(controller, 'customers', model);    
  },
  actions:{        
    testNewAdapterHost(){

      // alert(this.get('store').adapterFor('baseadapter').get('host')); 
      // returns "https://yyyyy.com" (what I was hoping to see from that alert)

      this.get('store').adapterFor('baseadapter').set('host','https://zzzzz.com');
alert(this.get('store').adapterFor('baseadapter').get('host')); 
// returns "https://zzzzz.com" (new host value - what I was hoping to see from that alert)

      I have tried the following suggestions to get the model to reload with this new host in place, thus hoping for the DOM to update with a new list of customers
      // this.get('model').reload();
      // this.store.get('model').reload();    
      // this.get('model').refresh();
      // the 3 above statements flag an undefined error

      // this.refresh();     
      // this.store.findAll('project', {reload: true});
      // this.get('currentModel').reload();
      // the 3 above statements cause a fresh GET request but with the old host value - ie using https://yyyyy.com instead of the desired https://zzzzz.com (verified through network tab in chrome dev tools)

    } 

Is the way I access the adapter through the use of injecting the store an incorrect way to change/update its host property??

The reason for using 'store' to inject the adapter is based on this answer. (see comments added to the answer)

adapters/baseadapter.js

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({

  host: 'http://yyyyy.com',      
  //host: 'http://zzzzz.com',      
  namespace: 'api'

});

As mentioned in the comments, some statements return an error(syntax may be off - if so then i'm hoping for a point in the right direction as the docs haven't proven helpful so far).

Other statements cause a fresh request, but the host doesn't seem to have updated.

I'm having no trouble displaying the data from either url when testing each host as the initial value when the app is run.

Any help is appreciated.




Validation of arrays of arrays using ember-changeset-validations

I'm using ember-changeset-validations together with ember-form-for and it works perfectly, so thanks for that.

Currently, I had to handle a situation when my changeset contains Ember.A() which contains ordinary arrays of primitives. Validations are automatically executed when the top-array is changed but changes inside of child-array are not seen from ember-changeset(-validations). I have created a separate key in changeset (_NAME_index) which matches the content of top-array and it executes the validation (as 'set' is caught as normally).

Is there a better way how to do it?




jeudi 9 novembre 2017

Ember Engines Component does not render content

I inherited an ember application and can't figure out how to add a component to an engine.

I tried to create the component with:

web-app$ ember g component about-profile -ir fs-engine
installing component
  create lib/fs-engine/addon/components/about-profile.js
  create lib/fs-engine/addon/templates/components/about-profile.hbs
installing component-test
  create tests/integration/components/about-profile-test.js
installing component-addon
  create lib/fs-engine/app/components/about-profile.js

I then added the following to lib/fs-engine/addon/templates/components/about-profile.hbs

<article>
  <h1>Test</h1>
  <p>Please work</p>
</article>

I try to invoke this component at the template file lib/fs-engine/addon/templates/gw/itemdetail.hbs

<div></div>

It returns empty. Nothing is rendered. No error messages are displayed anywhere.

I am sure I am missing something very basic since I am new to Ember but I did read Ember Engines guide (http://ift.tt/2kn5aFk) and Ember Component guide (http://ift.tt/2n6MLAi).

thanks for your help!




Ember.js: saving a relationships destroy belongsTo relationships

I have a model, lets call it house, and an other, kitchen. When I try to save the house model, its relationships belongsTo() to kitchen is destroyed.

house has a belongsTo() relationships to kitchen, like that:

export default DS.Model.extend(DeviceValidation, {
    name: DS.attr('string'),
    kitchen: DS.belongsTo('kitchen', {polymorphic:true}),
});

kitchen is a very simple model:

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

I am creating my record, filling it and finally saving it in a component. This is the function associated to it.

 createHouse() {
    this.createKitchen().then(() => { // this will create, fill and save a kitchen record
          this.createAnSetHouse(); // this will create and fill a house record as 'house'
          console.log(this.get('house').get('kitchen')); // this properly get the kitchen record
          this.get('house').save().then(() => {
              console.log(this.get('house').get('kitchen')); // and here the relationships is set to null ???
          / * rest of the function * / 
    }

As you can see in the snippets above, once, I save the jhouse record, the relationships is set to null, even if it was properly set beforehand.

Any tips is appreciated.




Disabling browser back button globally

I am keeping my own back button on the application. since I don't want to enable the browsers back button. ( client requires ). to do this I implemented this code a page:

init(){

        history.pushState(null, null, document.URL);
        Ember.$(window).on('popstate', function () {
            history.pushState(null, null, document.URL);
        });

    },

it works fine. no issues. But I do have 2 constrain here:

  1. I don't want to write the same code to call my application pages. i have number of pages.

  2. init will call only one on controller loads. so, user can go forward and backwards after init action expires.

So simply how to handle this scenario?




Array value is being persisted in mutlple instances of same component

I have a component with property arr:[], and i am pushing some value to this property by this.get('arr').push('value one'); on init. If i use this component multiple times, the arr's value is being persisted in all the other components. For ex: If i push some value on component init, this.get('arr').push('value one'). If i use this component for one time it works fine, but for second use/instance, arr already has length 1 before i push to it.

Have a look at the console of this twiddle.

http://ift.tt/2m7Dbil

Is this behavior odd or it is supposed to work like this?




mercredi 8 novembre 2017

Ember js and Docker not finding ember-cli-build

I am unsure what the issue is because when I do ember s it works fine but when I do docker-compose up it throws this error: web_1 | Error: No ember-cli-build.js found. Please see the transition guide: http://ift.tt/292ONso

and the file is sitting the in the directory; any ideas?

Here is my dockerfile:

# 1: Use node 6.4.0 as base:
        FROM node:6.4.0


        # Install Ember CLI and Bower and NPM
        RUN npm install
        RUN npm install -g ember-cli@2.7.0
        RUN npm install -g bower

        # install watchman
        RUN \
            git clone http://ift.tt/1NDIdGH &&\
            cd watchman &&\
            git checkout v3.5.0 &&\
            ./autogen.sh &&\
            ./configure &&\
            make &&\
            make install

        # Expose the app and live-reload ports:
        EXPOSE 4200 35730

        # Set the default command:
        CMD ["ember", "server", "--live-reload-port", "35730"]

docker-compose file: version: '2' services: web: image: danlynn/ember-cli:2.7.0 build: context: . dockerfile: Dockerfile command: ember server --live-reload-port 35730 #entrypoint: /usr/src/app/development-entrypoint

      volumes:
        # Mount the app code inside the container's `/usr/src/app` directory:
        - .:/usr/src/app

      # Keep the stdin open, so we can attach to our app container's process
      # and do things such as debugging, etc:
      stdin_open: true

      # Enable sending signals (CTRL+C, CTRL+P + CTRL+Q) into the container:
      tty: true

      ports:
        # Bind the host's 4200 port to the container's ember app server
        # port 4200:
        - 4200:4200
        # Bind the host's 35730 port to the container's ember cli live reload
        # server port 35730:
        - 35730:35730




Ember, remove wrapping element or change classNames for route

I'm trying come back to ember.js after 2 years working with another frameworks. Most annoying "surprise" for me is there no views anymore, therefore i cannot customize html elements using something like classNames or tagName. To be more detailed I'll explain what is my problem relative for:

Lets pretend we have created route, /myroute for instance. Content of our templates/myroute.hbs is:

<div>test</div>

Ok, lets see our html using inspector:

<body class="ember-application">
  <div id="ember341" class="ember-view">
    <div>test</div>
  </div>
</body>

I'd like to know how i can remove this element <div id="ember341" class="ember-view"> in a new ember way, how i can change class property, tag ?

Thanks !




Docker NPM Issue - node_modules appears empty

I am using this as my docker

        # 1: Use node 6.4.0 as base:
        FROM node:6.4.0

        # 2: We'll set the application path as the working directory
        WORKDIR /usr/src/web-client

        # 3: We'll add the app's binaries path to $PATH:
        ENV PATH=/usr/src/web-client/bin:$PATH

        ADD package.json /tmp/package.json
        RUN cd /tmp && npm install
        RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/

        # 4: Install ember-cli and friends:
        RUN set -ex \
          && npm install -g ember-cli \
          && npm install -g bower \
          && npm install -g phantomjs-prebuilt \
          && npm install -g check-dependencies

        # 5: Install watchman:
        RUN set -ex \
          && export WATCHMAN_VERSION=4.6.0 \
          && curl -SL "http://ift.tt/2zuikIX" | tar -xz -C /tmp/ \
          && cd /tmp/watchman-${WATCHMAN_VERSION} \
          && ./autogen.sh \
          && ./configure \
          && apt-get update && apt-get install -y --no-install-recommends python-dev \
          && make \
          && make install \
          && apt-get purge -y --auto-remove python-dev \
          && rm -rf /var/lib/apt/lists/* \
          && rm -rf /tmp/*

        # 6: Expose the app and live-reload ports:
        EXPOSE 4200 35730

        # 7: Set the default command:
        CMD ["ember", "server", "--live-reload-port", "35730"]

and this as my docker compose file

version: '2'

services: web: image: selleo/ember-cli:2.7.0 build: context: . dockerfile: Dockerfile command: ember server --live-reload-port 35730

volumes:
  # Mount the app code inside the container's `/usr/src/app` directory:
  - .:/usr/src/web-client

# Keep the stdin open, so we can attach to our app container's process
# and do things such as debugging, etc:
stdin_open: true

# Enable sending signals (CTRL+C, CTRL+P + CTRL+Q) into the container:
tty: true

ports:
  # Bind the host's 4200 port to the container's ember app server
  # port 4200:
  - 4200:4200
  # Bind the host's 35730 port to the container's ember cli live reload
  # server port 35730:
  - 35730:35730
volumes:
    - ./src:/var/www/html
    - /var/www/html/node_modules

and I am getting this error: node_modules appears empty, you may need to run npm install when I run docker-compose up. And I am unsure because when I build this it shows that it is installing bower and npm files.